The QCap demo moved to SQuADDS: this page now sends visitors there
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreDeleted-3
- .tlsq_deployDeleted-1
- DockerfileDeleted-16
- README.md+5-57
- app.pyDeleted-96
- examples/interdigital.gdsDeleted
- examples/lattice_1q.gdsDeleted
- examples/lattice_5q.gdsDeleted
- examples/shielded_concentric.gdsDeleted
- examples/transmon_pocket.gdsDeleted
- examples/xmon.gdsDeleted
- geomgnn/.ruff_cache/.gitignoreDeleted-2
- geomgnn/.ruff_cache/0.3.2/1469527473019908334Deleted
- geomgnn/.ruff_cache/0.3.2/15008937266116554827Deleted
- geomgnn/.ruff_cache/0.3.2/16722831700881126324Deleted
- geomgnn/.ruff_cache/CACHEDIR.TAGDeleted-1
- geomgnn/SOURCES.jsonDeleted-233
- geomgnn/__init__.pyDeleted-8
- geomgnn/_tlsq/__init__.pyDeleted
- geomgnn/_tlsq/embed/__init__.pyDeleted
- geomgnn/_tlsq/embed/fastprior.pyDeleted-925
- geomgnn/_tlsq/embed/fastprior_loc.pyDeleted-210
- geomgnn/_tlsq/embed/proxy.pyDeleted-1043
- geomgnn/_tlsq/geometry.pyDeleted-256
- geomgnn/_tlsq/uge/__init__.pyDeleted-5
- geomgnn/_tlsq/uge/blocks.pyDeleted-526
- geomgnn/_tlsq/uge/graph.pyDeleted-74
- geomgnn/_tlsq/uge/localtok.pyDeleted-126
- geomgnn/_tlsq/uge/nnk.pyDeleted-341
- geomgnn/_tlsq/uge/proxies.pyDeleted-102
- geomgnn/_tlsq/uge/scene.pyDeleted-90
- geomgnn/access.pyDeleted-167
- geomgnn/api.pyDeleted-536
- geomgnn/app_flagship.pyDeleted-651
- geomgnn/app_gnn.pyDeleted-314
- geomgnn/app_paper.pyDeleted-325
- geomgnn/bundle.pyDeleted-33
- geomgnn/farfield.pyDeleted-73
- geomgnn/fastmom.pyDeleted-147
- geomgnn/fastprior_pkg.pyDeleted-1297
- geomgnn/flagship.pyDeleted-69
- geomgnn/ground_ui.pyDeleted-246
- geomgnn/infer.pyDeleted-72
- geomgnn/learned_prior.pyDeleted-49
- geomgnn/levelpar.pyDeleted-97
- geomgnn/lp_surrogate.pyDeleted-396
- geomgnn/overlap.pyDeleted-80
- geomgnn/paper.pyDeleted-439
- geomgnn/pilot_p2.pyDeleted-214
- geomgnn/priorv2.pyDeleted-215
123numba_cache__pycache__bake1managed by deploy/sync.py --flagship (registry v2)12345678910111213141516# Docker variant (agents/embedspeed, scripts/embedspeed/make_docker_space.py): numba cache baked at build time.FROM python:3.12-slimRUN useradd -m -u 1000 userUSER userENV SYSTEM=spaces HOME=/home/user PATH=/home/user/.local/bin:$PATH NUMBA_CPU_NAME=generic NUMBA_CACHE_DIR=/home/user/app/numba_cache \ GRADIO_SERVER_NAME=0.0.0.0 PORT=7860 PYTHONUNBUFFERED=1 OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 MKL_NUM_THREADS=2WORKDIR /home/user/appCOPY --chown=user requirements.txt .RUN pip install --no-cache-dir --user -r requirements.txt "gradio==6.29.1" && pip freeze > IMAGE_FREEZE.txtCOPY --chown=user . .# OAuth Spaces (hf_oauth): Gradio builds real login routes only when SYSTEM=spaces (set above: HF does not set it in Docker# Spaces, but it does pass SPACE_ID and the OAUTH_* variables at run time). At build time those are absent, so warm.py gets# placeholders for this one step.RUN SPACE_ID=build/warm OAUTH_CLIENT_ID=warm OAUTH_CLIENT_SECRET=warm OAUTH_SCOPES="openid profile" \ OPENID_PROVIDER_URL=https://huggingface.co TLSQ_NUM_THREADS=2 python warm.pyCMD ["python", "app.py"]2 unmodified lines345678910111213142 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374752 unmodified linesemoji: 🔌colorFrom: bluecolorTo: graysdk: dockerapp_port: 7860app_file: app.pypinned: falseshort_description: 'Maxwell capacitance of planar layouts: QCap models'hf_oauth: truethumbnail: https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolve/main/assets/qcap_og.png---2 unmodified lines<img class="hidden dark:block" src="https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolve/main/assets/qcap_horizontal_dark.png" width="320" alt="QCap" /></center># Planar Capacitance ModelThe model of our paper *QCap: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout*, trained on all 45,771 designs of our Q3D dataset, the test designs included. Upload a GDS layout and get the full Maxwell capacitance matrix of every conductor in it. Because the model has seen the test designs, it has no held-out score of its own. Its held-out accuracy, from the same model trained without the test designs, is in the paper.- **Paper docsite:** [lfl-lab.github.io/SQuADDS/qcap](https://lfl-lab.github.io/SQuADDS/qcap/), with the explainer videos and the [tutorials](https://lfl-lab.github.io/SQuADDS/qcap/#tutorials)- **Paper:** [lfl-lab.github.io/SQuADDS/ml-paper/paper](https://lfl-lab.github.io/SQuADDS/ml-paper/paper/)- **Code:** [github.com/LFL-Lab/SQuADDS](https://github.com/LFL-Lab/SQuADDS)- **Data:** [Q3D dataset](https://huggingface.co/datasets/SQuADDS/SQuADDS_PlanarCapacitance) and [synthetic dataset](https://huggingface.co/datasets/SQuADDS/SQuADDS_PlanarCapacitance-Synthetic), part of the [SQuADDS datasets](https://huggingface.co/collections/SQuADDS/squadds-datasets-6a65152b857f8efa5620880a)- **Models:** [QCap models](https://huggingface.co/SQuADDS/QCap) (QCap, QCap-Lite and QCap-Fast), part of the [SQuADDS models](https://huggingface.co/collections/SQuADDS/squadds-models-6af8b7da67a22df62af374c6)- **API:** [SQuADDS ML inference API](https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api)- **Point of contact:** [Sadman Ahmed Shanto](mailto:shanto@usc.edu)## How to use it1. Try a bundled example, or sign in with Hugging Face and upload your own GDS file.2. Pick the ground layer and the conductor layer (1/0 and 1/10 by default). If both are on one layer, the Space finds the ground and shows its pick on a numbered image for you to confirm.3. Choose a model and a substrate, and press Predict. You get the matrix in fF, self terms included.## Models| model | how it works | error on 39 new layouts, % (MAE / RMSE, fF) | median time ||---|---|---|---|| QCap (default) | the extrapolated prior from two coarse method-of-moments solves, corrected by the networks | 1.05 (0.132 / 0.188) | 1.1 s || QCap-Lite | the same recipe on two coarser solves | 2.044 (0.258 / 0.348) | 0.56 s || QCap-Fast | a learned prior replaces the solves, then the networks correct it | 3.175 (0.583 / 0.824) | 0.24 s |The 39 layouts are generated rings with a neighbour (3 or 4 conductors) that no part of any model saw in training. On them the extrapolated prior alone scores 1.765 % (MAE 0.275 / RMSE 0.376 fF). Times are on two CPUs of an Intel Xeon E5-2640 v4 cluster node.QCap-Fast is for quick screening of the component families it was trained on. Use QCap otherwise.## APIThe same endpoints work over `gradio_client` or REST (`/gradio_api/call/<name>`).```pythonimport osfrom gradio_client import Client, handle_filec = Client("shanto268/PlanarCapacitanceModel", oauth_token=os.environ["HF_TOKEN"]) # counts as you for the daily limitr = c.predict(handle_file("layout.gds"), "1/0", "1/10", 0, "Si (cryogenic, training)", 11.45, 350, "QCap",api_name="/predict_gds")print(r["names"], r["matrix_fF"], r["timing_s"]["total_s"])````model` is `QCap`, `QCap-Lite` or `QCap-Fast` (any case). When ground and conductors share a layer, pass the ground's piece numbers as the last argument (`ground_pieces`, for example `"1"` or `"1,4"`) if the automatic pick is wrong.## Limits of this demoThe examples run without sign-in. Sign in with Hugging Face to run your own layout: 10 predictions per day (UTC), for layouts with fewer than 70 conductors, ground included. A repeat of a result you already have does not count. The API follows the same rules: anonymous calls run the bundled examples only, and a call made with `oauth_token` counts as you. To run many layouts, larger ones or designs you would rather not upload, run the same models on your own computer with SQuADDS: [Run it on your own computer](https://lfl-lab.github.io/SQuADDS/source/ml_local.html).## PrivacyUploaded layouts are processed in memory and held there only while the Space runs, to answer repeat requests. Nothing is written to permanent storage, and no file names or geometry are logged or kept. To enforce the daily limit, your Hugging Face username and your network address are turned into keyed hashes, held in memory and cleared at the end of the UTC day. They are never stored or logged. We keep only daily totals (runs per model and per layout size, refusals by reason, errors, response times and the number of distinct users that day) to understand how the demo is used. Hugging Face keeps ordinary web access logs under its own policy.## Citation2 unmodified lines34567891011122 unmodified lines1516171819202122232 unmodified linesemoji: 🔌colorFrom: bluecolorTo: graysdk: staticpinned: falselicense: mitshort_description: 'Moved: the QCap demo now runs on SQuADDS'thumbnail: https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolve/main/assets/qcap_og.png---2 unmodified lines<img class="hidden dark:block" src="https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolve/main/assets/qcap_horizontal_dark.png" width="320" alt="QCap" /></center>The QCap demo has moved to [huggingface.co/spaces/SQuADDS/planar-capacitance](https://huggingface.co/spaces/SQuADDS/planar-capacitance). This page sends you there.The model is QCap, from our paper [*QCap: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout*](https://arxiv.org/abs/2611.22057) (arXiv:2611.22057). Weights: [SQuADDS/QCap](https://huggingface.co/SQuADDS/QCap).## Citation
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Flagship Space (deploy/GNN_SPACE.md "Flagship Space"): GDS -> full Maxwell capacitance matrix with three models (QCap default,QCap-Lite, QCap-Fast) retrained on all on-stack data, through geomgnn.flagship. Names, tiers and numbers come from registry.yaml(flagship_hub, flagship_tiers)."""
import osimport platformimport sysimport threadingimport tracebackfrom pathlib import Path
if platform.machine() in ("x86_64", "AMD64"): # OpenBLAS SkylakeX Cholesky kernel segfaulted on a v3 MoM system (LIMITS.md) os.environ.setdefault("OPENBLAS_CORETYPE", "Haswell")os.environ.setdefault("GRADIO_ANALYTICS_ENABLED", "False")os.environ.setdefault("NUMBA_CACHE_DIR", os.path.join(os.environ.get("TMPDIR", "/tmp"), "numba_cache")) # writable on the Space# Speed (agents/embedspeed): in-memory LRU of finished responses and the per-body embedding cache on /tmp, both size-bounded# (uploads are held only while the Space runs; nothing is written to permanent storage).os.environ.setdefault("TLSQ_RESPONSE_CACHE", "64")os.environ.setdefault("TLSQ_RESPONSE_CACHE_MB", "1024")os.environ.setdefault("TLSQ_EMBED_CACHE", os.path.join(os.environ.get("TMPDIR", "/tmp"), "tlsq_embed_cache"))os.environ.setdefault("TLSQ_EMBED_CACHE_MB", "1024")os.environ.setdefault("TLSQ_PRIOR_LEVEL_CACHE_MB", "256") # solved prior levels (QCap and QCap-Lite share 1.5) and meshes (substrate changes)os.environ.pop("TLSQ_GNN_PRIOR_MODE", None) # every tier names its own solver mode (registry flagship_hub.prior_stacks)
HERE = Path(__file__).resolve().parentif (HERE / "geomgnn").exists(): # built bundle (deploy/sync.py --flagship): vendored packages, registry and weights sys.path.insert(0, str(HERE)) os.environ.setdefault("TLSQ_REGISTRY", str(HERE / "registry.yaml")) os.environ.setdefault("TLSQ_MODEL_DIR", str(HERE / "models")) os.environ.setdefault("TLSQ_OFFLINE", "1")else: # repository checkout sys.path.insert(0, str(HERE.parents[1] / "tlsq_infer" / "src")) sys.path.insert(0, str(HERE.parents[1] / "geomgnn" / "src")) os.environ.setdefault("TLSQ_REGISTRY", str(HERE.parents[1] / "registry.yaml"))
from tlsq_infer import set_num_threads # noqa: E402from tlsq_infer.registry import load_registry # noqa: E402
os.environ.setdefault("TLSQ_NUM_THREADS", str(set_num_threads()))
from geomgnn import app_flagship as G # noqa: E402from geomgnn.app_flagship import build_app # noqa: E402
reg = load_registry()ex = HERE / "examples"if not ex.exists(): # repository checkout: the bundle's examples (sync.py --flagship adds the lattices from data_local) import shutil import tempfile
ex = Path(tempfile.mkdtemp()) / "examples" shutil.copytree(HERE.parent / "PlanarCapacitanceModel" / "examples", ex, ignore=shutil.ignore_patterns("__pycache__", "client.py")) for name, src in (("lattice_1q.gds", "grid_qubit_1.gds"), ("lattice_5q.gds", "grid_qubit_5.gds")): f = HERE.parents[2] / "data_local" / "release_core" / "gds" / "ref" / "grid" / src if f.exists(): shutil.copy(f, ex / name)BAKE = Path(os.environ.get("TLSQ_RESPONSE_BAKE", HERE / "bake" / "respcache.pkl")) # the examples' results, baked at image build
def preload(): """Load every tier (SHA checks) + numba warmup + one small prediction; then the baked example results, if they verify here.""" from geomgnn import flagship as FS from geomgnn import paper as PA
FS.preload(reg, example=ex / "interdigital.gds") if BAKE.exists() and int(os.environ.get("TLSQ_RESPONSE_CACHE", "0")) > 0: PA.STARTUP["bake"] = G.load_bake(BAKE, ex)
def _preload_background(): try: preload() except BaseException: # noqa: BLE001 (a Space that cannot load its models must not serve) traceback.print_exc() os._exit(1) G.READY.set()
def bake(): """Image build (warm.py, after the import's preload): every example x model into the response cache, pickled to BAKE.""" return G.bake(ex, BAKE)
demo = build_app(reg["flagship_hub"]["title"], examples_dir=ex)demo.queue(default_concurrency_limit=int(os.environ.get("TLSQ_CONCURRENCY", 1)), max_size=32)if os.environ.get("TLSQ_PRELOAD", "1") != "0": if __name__ == "__main__": # the server: the page is up while the tiers load; predictions wait for them (G.READY) G.READY.clear() threading.Thread(target=_preload_background, name="preload", daemon=True).start() else: # imported (warm.py, tests): load before returning preload()
if __name__ == "__main__": from geomgnn import ui as UI
demo.launch(server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"), server_port=int(os.environ.get("PORT", 7860)), favicon_path=str(UI.FAVICON_PNG))12# Automatically created by ruff.*1Signature: 8a477f597d28d172789f06886806bc55123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233{ "stage": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage", "note": "frozen geomfast inference stack (FINALIZATION_V1), namespaced under geomgnn; only import lines rewritten", "files": { "_tlsq/__init__.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/__init__.py", "source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "rewrites": [] }, "_tlsq/geometry.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/geometry.py", "source_sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b", "sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b", "rewrites": [] }, "_tlsq/embed/__init__.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/__init__.py", "source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "rewrites": [] }, "_tlsq/embed/proxy.py": { "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/embed/proxy.py", "source_sha256": "f87a0f1614ca93b73aac0747d0acdafbd9b8c243f69c68c98d8919e158a57b28", "sha256": "f87a0f1614ca93b73aac0747d0acdafbd9b8c243f69c68c98d8919e158a57b28", "rewrites": [], "note": "phase B speed-up (2026-11-15): the training-source copy src/tlsq/embed/proxy.py (byte-identical); row-blocked image table, bounded image-table cache, compiled bitwise interpolation (np.interp fallback); every prior bit-identical to the frozen stage file", "frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/proxy.py", "frozen_stage_sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e" }, "_tlsq/embed/fastprior.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/fastprior.py", "source_sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1", "sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1", "rewrites": [] }, "_tlsq/embed/fastprior_loc.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/fastprior_loc.py", "source_sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b", "sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b", "rewrites": [] }, "_tlsq/uge/__init__.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/__init__.py", "source_sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22", "sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22", "rewrites": [] }, "_tlsq/uge/blocks.py": { "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/blocks.py", "source_sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c", "sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c", "rewrites": [], "note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py).", "frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/blocks.py", "frozen_stage_sha256": "c58313f167f7df0ef0de6b321ab6b7214a661aef10b461e2bf90a60999fb4632" }, "_tlsq/uge/graph.py": { "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/graph.py", "source_sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa", "sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa", "rewrites": [], "note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py).", "frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/graph.py", "frozen_stage_sha256": "aeb8c58cf6c1d2169eab8a58fba362634d7489f3414f260a9fc55a02048217ee" }, "_tlsq/uge/localtok.py": { "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/localtok.py", "source_sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd", "sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd", "rewrites": [], "note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py).", "frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/localtok.py", "frozen_stage_sha256": "8b47bd454353709a29ad996243d0f8b4b0d94991ee43715145af41a912dd9319" }, "_tlsq/uge/proxies.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/proxies.py", "source_sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38", "sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38", "rewrites": [] }, "_tlsq/uge/scene.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/scene.py", "source_sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285", "sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285", "rewrites": [] }, "pilot_p2.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/pilot_p2.py", "source_sha256": "c38264c43ab342ba64338892edf23c8abd4b88503b99bce322431efb7db77c77", "sha256": "c38264c43ab342ba64338892edf23c8abd4b88503b99bce322431efb7db77c77", "rewrites": [] }, "infer.py": { "source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/infer.py", "source_sha256": "f1829b165b1c1abac5e9e8b6e9ccda8bcf91f977c331ee4b408615455e902d09", "sha256": "cee37e8ed6f229363801b9a8118aea9dfb4ce5f476e6e2d8ff13cfa734e87b96", "rewrites": [ [ "W=Path(__file__).resolve().parent;sys.path.insert(0,str(W/'vendor'))", "W=Path(__file__).resolve().parent" ], [ "from pilot_p2 import build_model", "from .pilot_p2 import build_model" ], [ "from tlsq.uge.scene import scene_from_gds,tlsq_namer", "from ._tlsq.uge.scene import scene_from_gds,tlsq_namer" ], [ "from tlsq.uge.graph import scene_graph", "from ._tlsq.uge.graph import scene_graph" ], [ "from tlsq.uge.proxies import CapacitanceMoM", "from ._tlsq.uge.proxies import CapacitanceMoM" ], [ "spec=importlib.util.spec_from_file_location('tlsq.uge.localtok',W/'localtok.py');lt=importlib.util.module_from_spec(spec);sys.modules[spec.name]=lt;spec.loader.exec_module(lt)", "from ._tlsq.uge import localtok as lt" ], [ " from tlsq.embed import proxy,fastprior", " from ._tlsq.embed import proxy,fastprior" ], [ " from tlsq.embed.fastprior_loc import micro_mom_loc", " from ._tlsq.embed.fastprior_loc import micro_mom_loc" ], [ "from ._tlsq.uge.graph import scene_graph\n", "from ._tlsq.uge.graph import scene_graph\nfrom ._tlsq.uge.blocks import edge_matrix\n" ], [ "E=np.array([[row['edges'][tuple(p)][k] for k in ek] for p in pairs],np.float32)[None]", "E=edge_matrix(row['edges'],ek,n)[None]" ] ], "note": "agents/embedspeed: E from edge_matrix (array edge table or the dicts; same float32 values)." }, "fastmom.py": { "source": "/Users/shanto/LFL/tl_squadds/scripts/geomfast/fastmom.py", "source_sha256": "8f3642b22bd81325a782ee2a07d0341761d017351d838f484ee375cda025e85c", "sha256": "7447474366ddae654100467125c84ddb7fb503a1c9d4fd1264825bde164de951", "rewrites": [ [ "from tlsq.embed import proxy as P", "from ._tlsq.embed import proxy as P" ] ] }, "priorv2.py": { "source": "/Users/shanto/LFL/tl_squadds/scripts/priorv2/priorv2.py", "source_sha256": "1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c", "sha256": "64057e92e37a04a0231dfdc34df52a20542f88c2b2a3e8c2cc00a32d9ec1d21b", "rewrites": [ [ "from tlsq.embed import fastprior as F, proxy as P", "from ._tlsq.embed import fastprior as F, proxy as P" ] ], "note": "prior v2m (agents/priorv2/FINALIZATION_V2.json module_sha256); vendored 2026-10-17" }, "fastprior_pkg.py": { "source": "/Users/shanto/LFL/tl_squadds/scripts/fastprior_pkg/fastprior_pkg.py", "source_sha256": "4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a", "sha256": "4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a", "rewrites": [], "note": "gated fast-solve package (agents/fastprior_pkg/RESULTS.md), verbatim; bound with bind('geomgnn'); vendored 2026-10-17" }, "lp_surrogate.py": { "source": "/Users/shanto/LFL/tl_squadds/scripts/learnedprior/lp_surrogate.py", "source_sha256": "55804c9349a2ca4a74f3ae821a19c4637dbaf16d25b65c8ee70c746b767d2707", "sha256": "55804c9349a2ca4a74f3ae821a19c4637dbaf16d25b65c8ee70c746b767d2707", "rewrites": [], "note": "learned prior surrogate (agents/learnedprior; HASHES.json lp_surrogate.py), verbatim; fast tier; vendored 2026-10-18" }, "schema_p2d.json": { "source": "/Users/shanto/LFL/tl_squadds/scripts/learnedprior/schema_p2d.json", "source_sha256": "17eba5f7b5d01668019df9301507133dfe4e38689acbde5256f3ade2107df8e9", "sha256": "17eba5f7b5d01668019df9301507133dfe4e38689acbde5256f3ade2107df8e9", "rewrites": [], "note": "P2d feature schema read by lp_surrogate.py (HASHES.json schema_p2d.json), verbatim; vendored 2026-10-18" }, "train_mf.py": { "source": "/Users/shanto/LFL/tl_squadds/scripts/multifid/train_mf.py", "source_sha256": "d4df1310cf8758d6e5165c514fc0bac497768b7e37da91dd2bede717fd746676", "sha256": "d4df1310cf8758d6e5165c514fc0bac497768b7e37da91dd2bede717fd746676", "rewrites": [], "note": "multifid network (agents/multifid; HASHES.json train_mf.py), verbatim; paper Space cheap-physics arms; vendored 2026-10-19" }, "x1_core.py": { "source": "/Users/shanto/LFL/tl_squadds/scripts/v4test/x1_core.py", "source_sha256": "f4ee1cb4074eb7a3dc019072722f36d58a320d6bf711af3c66c7a5cbc96499cc", "sha256": "0a4be5ec3b8819bdc6d6314775c7f8acf46f4a54569d975011726ec1912c5100", "rewrites": [ [ " from train_mf import build", " from .train_mf import build" ], [ " import lp_surrogate as S", " from . import lp_surrogate as S" ], [ "import numpy as np\n", "import numpy as np\n\nfrom ._tlsq.uge.blocks import edge_matrix\n" ], [ " E = np.array([[row['edges'][tuple(p)][k] for k in ek] for p in pairs], np.float32).reshape(len(pairs), len(ek))", " E = edge_matrix(row['edges'], ek, n)" ] ], "note": "X1 shared model code (multifid forward, Richardson c0, to_maxwell); paper Space arms; vendored 2026-10-19, import lines rewritten agents/embedspeed: E from edge_matrix (same float32 values)." }, "_tlsq/uge/nnk.py": { "source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/nnk.py", "source_sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84", "sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84", "rewrites": [], "note": "agents/embedspeed (2026-10-20): the training-source copy src/tlsq/uge (byte-identical). Exact batched embedding, numba NN kernel, edge table, numex / far-decimation / cache modes; in the default bitwise mode every feature is bit-identical to the frozen stage file (deploy/tests/test_embed_parity.py, tests/test_embed_parity_src.py, deploy/tests/test_embed_regression.py)." }, "farfield.py": { "source": "/Users/shanto/LFL/tl_squadds/scripts/farfield/farfield.py", "source_sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836", "sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836", "rewrites": [], "note": "far-pair arms of agents/farfield (PROTOCOL.md sec. 2), verbatim; arm 'b' (slab dipole for signal far pairs in different ground pockets) is installed on top of priorv2 by geomgnn.api for patch priorv2m_sf, the corrected prior with substrate far field (user adoption 2026-10-20); vendored 2026-10-20" } }}12345678"""geomgnn: the frozen geomfast GNN (paper_v4; agents/geomfast/FINALIZATION_V1.json) for the GNN Space.
The inference code is the frozen geomfast stage, namespaced (`geomgnn.infer`, `geomgnn.pilot_p2`, `geomgnn._tlsq`; only importlines rewritten, see SOURCES.json) so it cannot collide with `tlsq_infer` or the repository's `tlsq`. `geomgnn.api` adapts itto `tlsq_infer.layout.PreparedLayout` and to the registry entries `gnn_models` (deploy/registry.yaml)."""
__version__ = "0.1.0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925"""Local (windowed) MoM prior: PRIOR_SCHEME.md Part III prototype.
The Maxwell entry C_ij is defined with every other conductor at 0 V, and a ground plane screens the field, so theentries of a conductor are set by its neighbourhood. The layout is partitioned into windows (recursive bisection ofthe conductor sites until the metal edge length inside each window fits a panel budget); a window models its coreconductors (whose matrix rows it provides), the halo conductors within R_g of the core as separate nets at 0 V, theground plane cropped by a margin around core + halo, and every farther conductor filled into the ground. Each windowis a strip-merged conductor-anchored mesh (the flagship mesh family, PRIOR_SCHEME.md Part II) solved densely with theexact near field and one right-hand side per core conductor, optionally Richardson-extrapolated (h and 2 h). Windowsthat are translation copies of one another are solved once (geometric hash). Cost: O(number of distinct windows) x(a bounded dense solve), independent of the chip size; a layout that fits one window is one global solve.Pairs never co-windowed (farther than R_g apart) are not predicted: NaN in C and True in far_mask."""
from __future__ import annotations
import hashlibimport timefrom concurrent.futures import ProcessPoolExecutorfrom multiprocessing import get_context
import numpy as npimport shapelyfrom scipy.spatial import cKDTree
from ..geometry import sample_boundaryfrom ..uge.blocks import _kratiofrom . import proxy as P
PANELS_PER_EDGE_H = 0.75 # merged panels per (um of metal edge / h), measured on grid_qubit_1 (18.6k at h = 2 um, 50 mm of edges)
def _valid(g): g = shapely.make_valid(g) parts = [p for p in getattr(g, "geoms", [g]) if p.geom_type in ("Polygon", "MultiPolygon")] return shapely.union_all(parts) if parts else shapely.Polygon()
def gap_of(metals: list) -> float: tree = shapely.STRtree(metals) d = np.inf for i, g in enumerate(metals): j, dist = tree.query_nearest(g, return_distance=True, exclusive=True, all_matches=False) if len(dist): d = min(d, float(dist[0])) return d
def within(geoms: list, targets: list, R: float) -> np.ndarray: """Boolean (len(geoms),): geometry within distance R of any target (STRtree, O(n log n)).""" out = np.zeros(len(geoms), bool) if not targets or not geoms: return out tree = shapely.STRtree(geoms) for t in targets: out[tree.query(t, predicate="dwithin", distance=R)] = True return out
def plan_windows(G, conds: list, h: float, R_g: float, margin: float, panel_budget: int, global_budget: int | None = None, split_gain: float = 0.75, level_rings: tuple = ()) -> list: """Windows (dicts: core, halo, box). One global window (every conductor in the core, no halo, no crop) when the metal edge length of the whole layout fits global_budget panels; otherwise recursive bisection of the conductor sites (bbox centres) until the estimated merged panel count of the window fits panel_budget. The estimate weights the metal edge length by the grading level it will be meshed at (1, 1/2, 1/4, ... beyond each of level_rings um from the core; ground edges beyond R_g of the members are filled and count 0), so the budget measures the core content, not the fixed halo + margin overhead. Each split is snapped to the widest coordinate gap between sites in the central half of the sorted order (cores follow the natural cell structure); a split whose child is not below split_gain x the parent (a dense cluster) is not made and the window is solved whole (H-matrix above dense_max).""" sites = np.array([[(b[0] + b[2]) / 2, (b[1] + b[3]) / 2] for b in shapely.bounds(np.array(conds, dtype=object))]) per_panel = h / PANELS_PER_EDGE_H all_idx = np.arange(len(conds)) L_all = G.length + sum(c.length for c in conds) if L_all <= (global_budget if global_budget is not None else panel_budget) * per_panel: return [{"core": all_idx, "halo": np.zeros(0, int), "box": None, "n_core": len(conds), "n_halo": 0}] out = [] Gb = G.boundary gtree = shapely.STRtree(list(getattr(Gb, "geoms", [Gb]))) rings = list(level_rings) + [np.inf]
def window_of(core): halo = within(conds, [conds[i] for i in core], R_g) halo[core] = False halo = np.nonzero(halo)[0] x0, y0, x1, y1 = shapely.union_all([conds[i] for i in np.concatenate([core, halo])]).bounds box = (x0 - margin, y0 - margin, x1 + margin, y1 + margin) return halo, box
def est_panels(core, halo, box): cg = shapely.union_all([conds[i] for i in core]) members = shapely.union_all([conds[i] for i in np.concatenate([core, halo])]) b = shapely.box(*box) gl = shapely.union_all([gtree.geometries[k] for k in gtree.query(b)]) if len(gtree.geometries) else Gb edges = shapely.union_all([shapely.intersection(gl, b).intersection(members.buffer(R_g)), members.boundary]) L, prev, w = 0.0, None, 1.0 for r in rings: ring = cg.buffer(r) if np.isfinite(r) else b if prev is not None: ring = ring.difference(prev) L += w * shapely.intersection(edges, ring).length prev, w = (cg.buffer(r) if np.isfinite(r) else b), w / 2 return L / per_panel
def rec(idx, n_parent=None): halo, box = window_of(idx) n = est_panels(idx, halo, box) if len(idx) == 1 or n <= panel_budget or (n_parent is not None and n > split_gain * n_parent): out.append({"core": idx, "halo": halo, "box": box, "est_panels": n}) return s = sites[idx] ax = int(np.argmax(s.max(0) - s.min(0))) order = idx[np.argsort(s[:, ax], kind="stable")] x = sites[order, ax] lo = max(1, len(order) // 4) hi = max(lo + 1, min(len(order), (3 * len(order)) // 4 + 1)) gaps = x[lo:hi] - x[lo - 1:hi - 1] m = lo + int(np.argmax(gaps)) rec(order[:m], n), rec(order[m:], n)
rec(all_idx) for w in out: w["n_core"], w["n_halo"] = len(w["core"]), len(w["halo"]) return out
def window_metals(G, conds: list, w: dict, fill_um: float = 250.0, keep_um: float = 0.0) -> list: """[ground, core..., halo...] of window w: ground = chip ground cropped to the box plus every farther conductor inside the box as ground metal (0 V), whose etched surroundings within fill_um are filled in where they are more than keep_um from any member (their edges leave the mesh; nothing changes within keep_um of a member).""" members = np.concatenate([w["core"], w["halo"]]).astype(int) if w["box"] is None: return [G] + [conds[i] for i in members] box = shapely.box(*w["box"]) far = np.setdiff1d(np.nonzero(within(conds, [box], 0.0))[0], members) Gw = shapely.intersection(G, box) if len(far): chip = shapely.box(*G.bounds) farg = shapely.union_all([conds[i] for i in far]) fill = shapely.intersection(shapely.intersection(chip.difference(G), farg.buffer(fill_um)), box) fill = fill.difference(shapely.union_all([conds[i] for i in members]).buffer(keep_um)) Gw = shapely.union_all([Gw, shapely.intersection(farg, box), fill]) return [_valid(Gw)] + [conds[i] for i in members]
def anchored_cells_graded(metals: list, h_f: float, core, levels: tuple, grade: float = 2.0, majority: bool = False): """`proxy.anchored_cells` with the finest panel graded by the distance to the core conductors: h_f within levels[0] of `core`, 2 h_f up to levels[1], 4 h_f up to levels[2], ... (same lattice; with levels=() identical to the plain mesh). Returns centres (n, 2), sizes (n, 2), owner (n,).""" edges = shapely.union_all([g.boundary for g in metals]) sig = metals[1:] if len(metals) > 1 else metals ax, ay = shapely.union_all(sig).bounds[:2] X0, Y0, X1, Y1 = shapely.union_all(metals).bounds span = max(X1 - X0, Y1 - Y0) K = max(0, int(np.ceil(np.log2(max(span / 16, h_f) / h_f)))) h0 = h_f * 2**K ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0)) ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0)) gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1)) xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) gq = P._Geoms(list(metals) + [edges, core]) lv = np.asarray(levels, float) tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) out_c, out_h, out_o = [], [], [] while len(xs): boxes = shapely.box(xs, ys, xs + h, ys + h) cov, hit, inn, pcs = P._cover(gq, boxes, h, tst, inn) keep = cov.sum(0) > 1e-3 xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep] pcs = [p[keep] for p in pcs] cx, cy = xs + h / 2, ys + h / 2 full = cov.max(0) > 0.999 if len(lv): maybe = h <= h_f * 2 ** len(lv) * 1.0001 # cells that can be at their last level hl = np.zeros(len(xs)) if maybe.any(): dc = P._distance(gq, len(metals) + 1, boxes[maybe]) hl[maybe] = h_f * 2.0 ** np.searchsorted(lv, dc, side="right") last = h <= hl * 1.0001 else: last = h <= h_f * 1.0001 d = np.full(len(xs), np.inf) far = full & ~last d[far] = P._distance(gq, len(metals), boxes[far]) leaf = full & (last | (h <= grade * d + 1e-12)) out_c.append(np.stack([cx[leaf], cy[leaf]], 1)) out_h.append(np.stack([h[leaf], h[leaf]], 1)) out_o.append(cov[:, leaf].argmax(0)) cut = last & ~leaf if majority and cut.any(): take = cut & (cov.max(0) >= 0.5) out_c.append(np.stack([cx[take], cy[take]], 1)) out_h.append(np.stack([h[take], h[take]], 1)) out_o.append(cov[:, take].argmax(0)) cut = cut & False if cut.any(): gs = gq.get() for k, g in enumerate(gs[:len(metals)]): shapely.prepare(g) sel = np.nonzero(cut & (cov[k] > 1e-3))[0] if not len(sel): continue pcs_k = pcs[k][sel] bb = shapely.bounds(pcs_k) cen = shapely.get_coordinates(shapely.centroid(pcs_k)) inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) if not inside.all(): cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside])) out_c.append(cen) out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) out_o.append(np.full(len(sel), k)) gq.put(gs) split = ~leaf & ~last hs = h[split] / 2 xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) h = np.concatenate([hs] * 4) tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
def strip_merge(c, wh, o, metals, h_f: float, lmax_mult: float = 16.0, grade: float = 1.0): """`proxy.strip_merge` with the strip length bounded by lmax_mult x the panel's own lattice level (max(width across the edge, h_f), so coarser regions get proportionally longer strips) and by grade x the distance to the nearest polygon vertex (coarse square cells therefore merge into longer strips than in proxy.strip_merge).""" lines, S, verts = P._segments(metals) near = shapely.STRtree(lines).nearest(shapely.points(c)) d = S[near, 1] - S[near, 0] horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1]) dv, _ = P.cKDTree(verts).query(c, workers=-1) allow = np.minimum(lmax_mult * np.maximum(wh.min(1), h_f), grade * dv) out_c, out_wh, out_o = [], [], [] for axis, mask in ((0, horiz), (1, ~horiz)): if not mask.any(): continue idx = np.nonzero(mask)[0] other = 1 - axis key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1) order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]]) idx, key = idx[order], key[order] same = np.all(key[1:] == key[:-1], 1) lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2 adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6) start = 0 while start < len(idx): end, length, cap = start, wh[idx[start], axis], allow[idx[start]] while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]): end += 1 length += wh[idx[end], axis] cap = min(cap, allow[idx[end]]) cc, ww = np.zeros(2), np.zeros(2) cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other] ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other] out_c.append(cc) out_wh.append(ww) out_o.append(o[idx[start]]) start = end + 1 return np.array(out_c), np.array(out_wh), np.array(out_o)
def solve_window_rows(metals: list, n_core: int, h: float, eps_r: float = 11.45, lmax_mult: float = 16.0, merge_grade: float = 1.0, grade: float = 2.0, rich: bool = True, dense_max: int = 12000, levels: tuple = ()) -> tuple: """Rows of the Maxwell matrix for the core conductors (metals[1:1+n_core]): (rows (n_core, len(metals)), info). levels: distances (um) from the core beyond which the finest panel doubles (core-graded mesh); () = uniform.""" info = {} core = shapely.union_all(metals[1:1 + n_core])
def one(hh, tag, majority=False): t = time.perf_counter() raw = anchored_cells_graded(metals, hh, core, levels, grade, majority=majority) c, wh, o = strip_merge(*raw, metals, hh, lmax_mult, merge_grade) info[f"mesh_s_{tag}"], info[f"raw_{tag}"], info[f"panels_{tag}"] = time.perf_counter() - t, len(raw[0]), len(c) info[f"share_{tag}"] = [float(np.mean(o == 0)), float(np.mean((o >= 1) & (o <= n_core))), float(np.mean(o > n_core))] t = time.perf_counter() B = (o[:, None] == np.arange(1, 1 + n_core)[None, :]).astype(float) if len(c) <= dense_max: A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) info[f"assemble_s_{tag}"] = time.perf_counter() - t t = time.perf_counter() try: Q = P._chol_solve(A, B) except np.linalg.LinAlgError: # cut panels of different nets overlap: whole finest cells by majority (as the flagship) if majority: raise del A info[f"majority_{tag}"] = True return one(hh, tag, majority=True) info[f"solver_{tag}"] = "dense" else: H = P._HMatrix(c, wh, eps_r, P.HMAT["leaf"], P.HMAT["eta"], P.HMAT["eps"]) info[f"assemble_s_{tag}"] = time.perf_counter() - t t = time.perf_counter() Xp, _, _ = H.pcg(B[H.perm], P.HMAT["tol"], P.HMAT["maxit"]) Q = np.empty_like(Xp) Q[H.perm] = Xp info[f"solver_{tag}"] = "H-matrix PCG" info[f"solve_s_{tag}"] = time.perf_counter() - t return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) # (n_core, n_metals): charge on a with core k at 1 V
Rf = one(h, "f") if not rich: return Rf, info Rc = one(2 * h, "c") return 2 * Rf - Rc, info
def canonical_hash(metals: list, n_core: int, h: float) -> str: """Translation-invariant key of a window (lattice anchored to the signal bbox, coordinates rounded to 0.1 nm).""" x0, y0 = shapely.union_all(metals[1:]).bounds[:2] tr = [shapely.transform(g, lambda xy: np.round(xy - [x0, y0], 4)) for g in metals] hsh = hashlib.sha1(f"{n_core}:{h:.9g}:".encode()) for g in tr: hsh.update(shapely.to_wkb(g)) return hsh.hexdigest()
def _job(args): wi, metals, n_core, h, kw = args rows, info = solve_window_rows(metals, n_core, h, **kw) return wi, rows, info
def local_prior(G, conds: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, rich: bool = True, panel_budget: int = 12000, halo_gaps: float = 100.0, margin_gaps: float = 100.0, margin_min_um: float = 150.0, fill_um: float = 250.0, lmax_mult: float = 16.0, merge_grade: float = 1.0, workers: int = 1, cache: bool = True, dense_max: int = 12000, global_budget: int | None = None, level_gaps: tuple = ()) -> tuple: """Local prior of a layout (ground G, conductors conds, never merged): (C (N+1, N+1) fF with NaN for far pairs, far_mask, info). Finest panel h = gap / cells_per_gap; with rich=True the Richardson pair is (h, 2 h). Windows are solved in parallel on `workers` processes.""" t_all = time.perf_counter() metals_all = [G] + list(conds) gap = gap_of(metals_all) h = gap / cells_per_gap R_g, margin = halo_gaps * gap, max(margin_gaps * gap, margin_min_um) t = time.perf_counter() wins = plan_windows(G, conds, h, R_g, margin, panel_budget, global_budget, level_rings=tuple(float(g) * gap for g in level_gaps)) t_plan = time.perf_counter() - t t = time.perf_counter() mats = [window_metals(G, conds, w, fill_um, keep_um=R_g) for w in wins] keys = [canonical_hash(m, w["n_core"], h) if cache else str(i) for i, (m, w) in enumerate(zip(mats, wins))] t_build = time.perf_counter() - t uniq = {} for i, k in enumerate(keys): uniq.setdefault(k, i) kw = dict(eps_r=eps_r, lmax_mult=lmax_mult, merge_grade=merge_grade, rich=rich, dense_max=dense_max, levels=tuple(float(g) * gap for g in level_gaps)) jobs = [(i, mats[i], wins[i]["n_core"], h, kw) for i in uniq.values()] t = time.perf_counter() if workers > 1 and len(jobs) > 1: with ProcessPoolExecutor(workers, mp_context=get_context("fork")) as ex: res = {wi: (rows, info) for wi, rows, info in ex.map(_job, jobs)} else: res = {wi: (rows, info) for wi, rows, info in map(_job, jobs)} t_solve = time.perf_counter() - t N = len(conds) + 1 acc, cnt = np.zeros((N, N)), np.zeros((N, N)) for i, w in enumerate(wins): rows, _ = res[uniq[keys[i]]] idx = np.concatenate([[0], w["core"] + 1, w["halo"] + 1]).astype(int) for k, ci in enumerate(w["core"] + 1): acc[ci, idx] += rows[k] cnt[ci, idx] += 1 C = np.full((N, N), np.nan) have = cnt > 0 C[have] = acc[have] / cnt[have] # symmetrise: mean of the two estimates when both exist, the one available otherwise; ground row from the columns S = np.where(have & have.T, 0.5 * (np.nan_to_num(C) + np.nan_to_num(C.T)), np.where(have, C, C.T)) S[0, 0] = np.nan far = ~(have | have.T) np.fill_diagonal(far, False) infos = [res[j][1] for j in uniq.values()] info = {"n_windows": len(wins), "n_unique": len(uniq), "h_um": h, "min_gap_um": gap, "R_g_um": R_g, "margin_um": margin, "panels_f": [i["panels_f"] for i in infos], "est_panels": [w.get("est_panels", 0) for w in wins], "raw_f": [i["raw_f"] for i in infos], "panels_c": [i.get("panels_c", 0) for i in infos], "cores": [w["n_core"] for w in wins], "halos": [w["n_halo"] for w in wins], "solvers": sorted({i["solver_f"] for i in infos}), "n_far_pairs": int(far[np.triu_indices(N, 1)].sum()), "mesh_s": sum(i["mesh_s_f"] + i.get("mesh_s_c", 0.0) for i in infos), "assemble_s": sum(i["assemble_s_f"] + i.get("assemble_s_c", 0.0) for i in infos), "solve_s": sum(i["solve_s_f"] + i.get("solve_s_c", 0.0) for i in infos), "level_gaps": list(level_gaps), "plan_s": t_plan, "build_s": t_build, "windows_wall_s": t_solve, "total_s": time.perf_counter() - t_all, "rich": rich} return S, far, info
# ---------------------------------------------------------------- flagship-fast: the cheap prior (PRIOR_SCHEME.md Part III, sections 12 and 16)# Hybrid H = micro-MoM (`micro_mom`: the flagship mesh family at a fixed panel budget per window, dense Cholesky) for self,# ground and co-windowed pairs + the closed-form edge-coupling prior (`formula_prior`) for pairs never co-windowed.# Mirrored verbatim (function sources) in deploy/tlsq_infer/src/tlsq_infer/_vendor/fastprior.py.
# formula constants: frozen 2026-10-09, not tuned on labelsFORMULA_STEP_UM = 0.25 # boundary sample step (as the pair tokens)FORMULA_R_GAPS = 150.0 # pairs farther apart than this (in smallest gaps) use the bounding-box formFORMULA_SCREEN_UM = 1.0 # the screening factor is evaluated every FORMULA_SCREEN_UM of boundary and held in betweenLITE_REFINE = 3 # rejected window solves: refine h by 2 up to this many times before majority-owned cellsLITE_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/80LITE_WINDOW_BUDGET = 2.0 # windows of large layouts: panel budget = this x the budget of the one-window (component) priorLITE_WINDOW_PPG = [None] # windows of large layouts: panels per smallest gap of the finest level instead of a budget (None = budget; PRIOR_SCHEME.md 14.4)LITE_MAX_CORE = [None] # windows of large layouts: conductors per core (None = the max_core argument; PRIOR_SCHEME.md 14.4.2)LITE_GROWTH = 2.0 # merged panels per halving of h (measured 1.6-2.2 on the training families)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)DIPOLE_K = 8 # nearest boundary samples searched for the nearest other conductor (gbar)ROW_SUM_EPS = 0.0143 # training median of 1 - sum_j |C_ij| / C_ii (self = row sum / (1 - eps))EPS0_FF_UM = 8.8541878128e-3
def plan_cores(sites: np.ndarray, max_core: int = 8) -> list: """Cores (index arrays) by recursive bisection of the conductor sites (n, 2) along the longer extent until each core has <= max_core conductors; each split is snapped to the widest coordinate gap between sites in the central half of the sorted order (ties broken by the other coordinate, so the cores do not depend on the conductor order).""" out = []
def rec(idx): if len(idx) <= max_core: out.append(idx) return s = sites[idx] ax = int(np.argmax(s.max(0) - s.min(0))) order = idx[np.lexsort((s[:, 1 - ax], s[:, ax]))] x = sites[order, ax] lo = max(1, len(order) // 4) hi = max(lo + 1, min(len(order), (3 * len(order)) // 4 + 1)) m = lo + int(np.argmax(x[lo:hi] - x[lo - 1:hi - 1])) rec(order[:m]), rec(order[m:])
rec(np.arange(len(sites))) return out
def _rot90(k: int): """Exact rotation of coordinates by k x 90 degrees (swaps and sign flips only).""" def f(xy): x, y = xy[:, 0], xy[:, 1] return np.stack([(x, y), (-y, x), (-x, -y), (y, -x)][k % 4], 1) return f
def canonical_frames(G, conds: list) -> list: """The layout in canonical frames, so that the lattice-anchored mesh (and hence the prior) does not depend on the position, the 90-degree orientation or the conductor order of the input: rotations by k x 90 degrees whose rotation-invariant key (signal bounding box, sorted conductor centroids and convex-hull vertices about the box centre, ground bounds, rounded to 1 nm) is smallest (several when the layout is symmetric), translation of the signal bounding box corner to the origin, coordinates rounded to 1e-6 um, collinear vertices removed (`shapely.simplify(0)`), rings in normal form (`shapely.normalize`), conductors sorted by (centroid, area). Returns [(G, conds, order)]: conds[k] of a frame is input conductor order[k].""" keys = [] for k in range(4): f = _rot90(k) sig = [shapely.transform(c, f) for c in conds] b = shapely.bounds(np.array(sig, dtype=object)) x0, y0, x1, y1 = b[:, 0].min(), b[:, 1].min(), b[:, 2].max(), b[:, 3].max() cen = shapely.get_coordinates(shapely.centroid(np.array(sig, dtype=object))) - [(x0 + x1) / 2, (y0 + y1) / 2] hull = shapely.get_coordinates(shapely.convex_hull(shapely.union_all(sig)))[:-1] - [(x0 + x1) / 2, (y0 + y1) / 2] gb = np.round(np.array(shapely.transform(G, f).bounds) - [(x0 + x1) / 2, (y0 + y1) / 2] * 2, 3) key = ((round(x1 - x0, 3), round(y1 - y0, 3)) + tuple(sorted(map(tuple, np.round(cen, 3).tolist()))) + tuple(sorted(map(tuple, np.round(hull, 3).tolist()))) + tuple(gb.tolist())) keys.append((key, k, x0, y0)) best = min(kk[0] for kk in keys) out = [] for key, k, x0, y0 in keys: if key != best: continue f = _rot90(k)
def to(g, f=f, x0=x0, y0=y0): return shapely.normalize(shapely.simplify(shapely.transform(g, lambda xy: np.round(f(xy) - [x0, y0], 6)), 0.0))
cs = [to(c) for c in conds] cen = shapely.get_coordinates(shapely.centroid(np.array(cs, dtype=object))) order = np.lexsort((np.round([c.area for c in cs], 6), np.round(cen[:, 1], 6), np.round(cen[:, 0], 6))) out.append((to(G), [cs[i] for i in order], order)) return out
def _gap_size(metals: list) -> tuple: """(smallest gap, layout size) exactly as mom_capacitance_gds_flagship computes them (all pairs; small layouts).""" bbox = shapely.union_all(metals).bounds size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) return gap, size
def _graded_mesh(metals: list, n_core: int, h: float, levels: tuple, majority: bool = False) -> tuple: """Core-graded flagship-family mesh (`anchored_cells_graded` + `strip_merge`): finest panel h within levels[0] of the core conductors (metals[1:1 + n_core]), doubling beyond each level. Returns (centres, sizes, owners, h, raw count).""" raw = anchored_cells_graded(metals, h, shapely.union_all(metals[1:1 + n_core]), levels, majority=majority) c, wh, o = strip_merge(*raw, metals, h) return c, wh, o, h, len(raw[0])
def _lite_mesh(metals: list, h: float, budget: float, n_core: int = 0, levels: tuple = ()) -> tuple: """Flagship-family mesh at the finest lattice level h 2^k predicted to fit the budget: a probe mesh at the level estimated (2 merged panels per h of metal edge) to hold ~budget / 4 panels, then the level LITE_GROWTH^j finer predicted to hold <= budget panels (each halving of h multiplies the panels by ~LITE_GROWTH), doubled while it does not fit. levels (um from the n_core core conductors): core-graded mesh (`_graded_mesh`); () = uniform (`proxy.mesh_flagship`). With an unbounded budget: the mesh at h. Returns (centres, sizes, owners, h, raw count).""" def mesh(hh): if not levels: return P.mesh_flagship(metals, hh, budget) while True: r = _graded_mesh(metals, n_core, hh, levels) if len(r[0]) <= budget: return r hh *= 2.0
if not np.isfinite(budget): return mesh(h) L = sum(g.length for g in metals) k = max(0, int(np.ceil(np.log2(max(2.0 * L / (h * budget / 4), 1.0))))) probe = mesh(h * 2.0**k) j = min(int(np.floor(np.log(budget / len(probe[0])) / np.log(LITE_GROWTH))), int(round(np.log2(probe[3] / h)))) return probe if j <= 0 else mesh(probe[3] / 2.0**j)
def _sym_solve(A, B): """Solve with the lower triangle of the Fortran-ordered A from `proxy._assemble`: Cholesky, or the symmetric indefinite (Bunch-Kaufman) factorisation when A is not positive definite.""" try: return P._chol_solve(A.copy(order="F"), B) except np.linalg.LinAlgError: from scipy.linalg import solve return solve(A, B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False)
def _window_solve(metals: list, n_core: int, h: float, budget: float, eps_r: float, all_rhs: bool, levels: tuple = ()) -> tuple: """Flagship-family mesh of one window at the lattice level of h that fits the budget (`_lite_mesh`), exact near field, dense Cholesky (H-matrix PCG above DENSE_MAX panels); right-hand sides: every metal (all_rhs, as `proxy._cap_flagship`) or the n_core core conductors; levels: core-graded mesh (`_lite_mesh`). A solve is rejected when the system is not positive definite, a metal has no panel or (all_rhs) a mutual entry is not negative (cut 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 meshed with majority-owned finest cells (as the flagship). Returns (R (n_rhs, n_metals) charges per metal, info).""" cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core) t_mesh = t_asm = t_sol = 0.0 hh, cap, refined, majority = h, budget, 0, False while True: t = time.perf_counter() if not refined: c, wh, o, hh, n_raw = _lite_mesh(metals, hh, cap, n_core, levels) elif levels: c, wh, o, hh, n_raw = _graded_mesh(metals, n_core, hh, levels, majority) else: c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority) t_mesh += time.perf_counter() - t t = time.perf_counter() try: if len(c) <= P.DENSE_MAX: A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) t_asm += time.perf_counter() - t t = time.perf_counter() Bm = (o[:, None] == cols[None, :]).astype(float) if all_rhs: Q = P._chol_solve(A, Bm) else: # windows: an indefinite system (overlapping cut panels on the coarse graded levels) is solved by LDL^T Q = _sym_solve(A, Bm) else: Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols] R = np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) off = np.ones(R.shape, bool) off[np.arange(len(cols)), cols] = False ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0))) except np.linalg.LinAlgError: ok = False t_sol += time.perf_counter() - t if ok or majority: break if refined < LITE_REFINE: hh, cap, refined = hh / 2, np.inf, refined + 1 else: majority = True return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, "assemble_s": t_asm, "solve_s": t_sol}
def _lite_window(G, conds: list, core, R_g: float, margin: float, fill_um: float, tree, etched) -> tuple: """Window of a core: ([ground, core..., halo...], halo). Halo = conductors within R_g of a core conductor (separate nets at 0 V); ground = chip ground clipped to the core + halo box widened by margin, plus every farther conductor in the box as ground metal with its etched surroundings within fill_um filled where farther than R_g from a member.""" hit = tree.query([conds[i] for i in core], predicate="dwithin", distance=R_g)[1] halo = np.setdiff1d(np.unique(hit), core) members = np.concatenate([core, halo]).astype(int) b = shapely.bounds(np.array([conds[i] for i in members], dtype=object)) box = (b[:, 0].min() - margin, b[:, 1].min() - margin, b[:, 2].max() + margin, b[:, 3].max() + margin) far = np.setdiff1d(tree.query(shapely.box(*box), predicate="intersects"), members) Gw = shapely.clip_by_rect(G, *box) if len(far): farg = shapely.clip_by_rect(shapely.union_all([conds[i] for i in far]), *box) fill = shapely.intersection(shapely.clip_by_rect(etched, *box), farg.buffer(fill_um, quad_segs=4)) fill = fill.difference(shapely.union_all([conds[i] for i in members]).buffer(R_g, quad_segs=4)) Gw = shapely.union_all([Gw, farg, fill]) return [_valid(Gw)] + [conds[i] for i in members], halo
_LITE_BUDGET_USED: list = [0.0]_LITE: dict = {} # layout of the running micro_mom call, inherited by forked window workers
def _lite_job(k: int) -> tuple: L = _LITE t = time.perf_counter() metals, halo = _lite_window(L["G"], L["conds"], L["cores"][k], L["R_g"], L["margin"], L["fill_um"], L["tree"], L["etched"]) t_build = time.perf_counter() - t bx = shapely.bounds(metals[0]) h = max(L["h"], max(bx[2] - bx[0], bx[3] - bx[1]) / 4096) budget = L["budget"] if LITE_WINDOW_PPG[0]: # resolution-controlled windows (PRIOR_SCHEME.md 14.4): finest panel gap / ppg, no budget h, budget = L["gap"] / LITE_WINDOW_PPG[0], np.inf R, info = _window_solve(metals, len(L["cores"][k]), h, budget, L["eps_r"], False, L["levels"]) info.update(build_s=t_build, n_halo=len(halo), n_core=len(L["cores"][k])) return k, halo, R, info
def micro_mom(G, conds: list, eps_r: float = 11.45, budget: float = 1500, cells_per_gap: float = 3.0, max_core: int = 8, halo_gaps: float = 100.0, margin_gaps: float = 100.0, margin_min_um: float = 150.0, fill_um: float = 250.0, workers: int = 1, level_gaps: tuple = LITE_LEVEL_GAPS, window_budget: float | None = None, canonical: bool = True) -> tuple: """Cheap micro-MoM prior (PRIOR_SCHEME.md section 12, M / hybrid H): (C (N+1, N+1) fF Maxwell, far_mask, info). <= max_core conductors: one global window = the layout as given, h = max(gap / cells_per_gap, size / 4096) doubled on the flagship lattice until the merged mesh has <= budget panels, every metal excited (with budget = inf this is `proxy.mom_capacitance_gds_flagship(rich=False)` bit for bit; `_lite_mesh` picks the level). More conductors: cores of <= max_core by bisection, one window per core (halo within halo_gaps, ground clipped at margin_gaps), entry (i, j) = mean of the two window estimates when both exist (a non-negative window estimate is not used), ground row from the columns, C_00 = row sum / (1 - ROW_SUM_EPS); pairs never co-windowed (far_mask, > halo_gaps apart) in different ground pockets take the screened dipole value (`dipole_far`), in the same pocket the closed form (`formula_prior`, quadrature step one smallest gap). level_gaps: core-graded window meshes (finest panel within level_gaps[0] smallest gaps of the core, doubling beyond each level); window systems that are not positive definite are solved by LDL^T; window budget = window_budget or LITE_WINDOW_BUDGET x budget. Windows run on `workers` forked processes. canonical: solved in the `canonical_frames` (mean over them when the layout is symmetric; invariant to translation, 90-degree rotation and conductor order), returned in the input order.""" t_all = time.perf_counter() if canonical: # mean over the canonical frames (one unless the layout is symmetric), in the input order runs = [] for Gc, cc, order in canonical_frames(G, conds): C, far, info = micro_mom(Gc, cc, eps_r, budget, cells_per_gap, max_core, halo_gaps, margin_gaps, margin_min_um, fill_um, workers, level_gaps, window_budget, canonical=False) inv = np.r_[0, np.argsort(order) + 1] runs.append((C[np.ix_(inv, inv)], far[np.ix_(inv, inv)], info)) C = runs[0][0] if len(runs) == 1 else sum(r[0] for r in runs) / len(runs) far = np.logical_or.reduce([r[1] for r in runs]) info = runs[0][2] for k in ("mesh_s", "assemble_s", "solve_s", "build_s", "formula_s"): info[k] = sum(r[2][k] for r in runs) info["n_frames"] = len(runs) info["total_s"] = time.perf_counter() - t_all return C, far, info metals = [G] + list(conds) N = len(metals) far = np.zeros((N, N), bool) if len(conds) <= max_core: gap, size = _gap_size(metals) h = max(gap / cells_per_gap, size / 4096) R, wi = _window_solve(metals, len(conds), h, budget, eps_r, True) C = 0.5 * (R + R.T) info = {"n_windows": 1, "min_gap_um": gap, "h_um": [wi["h_um"]], "panels": [wi["panels"]], "panels_per_gap": [gap / wi["h_um"]], "majority": [wi["majority"]], "refined": [wi["refined"]], "mesh_s": wi["mesh_s"], "assemble_s": wi["assemble_s"], "solve_s": wi["solve_s"], "build_s": 0.0, "plan_s": 0.0, "formula_s": 0.0, "n_far_pairs": 0, "budget": budget} info["total_s"] = time.perf_counter() - t_all return C, far, info t = time.perf_counter() gap = gap_of(metals) R_g, margin = halo_gaps * gap, max(margin_gaps * gap, margin_min_um) b = shapely.bounds(np.array(conds, dtype=object)) cores = plan_cores(np.stack([(b[:, 0] + b[:, 2]) / 2, (b[:, 1] + b[:, 3]) / 2], 1), LITE_MAX_CORE[0] or max_core) tree = shapely.STRtree(conds) etched = shapely.box(*G.bounds).difference(G) _LITE.clear() _LITE.update(G=G, conds=conds, cores=cores, R_g=R_g, margin=margin, fill_um=fill_um, tree=tree, etched=etched, h=gap / cells_per_gap, gap=gap, budget=LITE_WINDOW_BUDGET * budget if window_budget is None else window_budget, eps_r=eps_r, levels=tuple(float(x) * gap for x in level_gaps)) _LITE_BUDGET_USED[:] = [_LITE["budget"]] t_plan = time.perf_counter() - t t = time.perf_counter() if workers > 1 and len(cores) > 1: with ProcessPoolExecutor(min(workers, len(cores)), mp_context=get_context("fork")) as ex: res = list(ex.map(_lite_job, range(len(cores)))) else: res = [_lite_job(k) for k in range(len(cores))] t_win = time.perf_counter() - t _LITE.clear() acc, cnt = np.zeros((N, N)), np.zeros((N, N)) for k, halo, R, _ in res: idx = np.concatenate([[0], cores[k] + 1, halo + 1]).astype(int) for r, ci in enumerate(cores[k] + 1): use = (R[r] < 0) | (idx == ci) # a non-negative mutual estimate of a window (tiny far entries) is not used acc[ci, idx[use]] += R[r][use] cnt[ci, idx[use]] += 1 have = cnt > 0 Cw = np.where(have, acc / np.where(have, cnt, 1), 0.0) C = np.where(have & have.T, 0.5 * (Cw + Cw.T), np.where(have, Cw, Cw.T)) far = ~(have | have.T) np.fill_diagonal(far, False) t = time.perf_counter() iu = np.nonzero(np.triu(far, 1)) t_dip, n_dip = 0.0, 0 if len(iu[0]): pid = np.r_[-10**9, pocket_ids(G, conds)] cross = pid[iu[0]] != pid[iu[1]] # different ground pockets: screened dipole; same pocket: closed form if (~cross).any(): F, _ = formula_prior(G, conds, eps_r, step_um=max(FORMULA_STEP_UM, gap), pairs=np.stack(iu, 1)[~cross], gap=gap, workers=workers) C[iu[0][~cross], iu[1][~cross]] = F[iu[0][~cross], iu[1][~cross]] if cross.any(): t_dip = time.perf_counter() C[iu[0][cross], iu[1][cross]] = dipole_far(G, conds, np.stack(iu, 1)[cross], eps_r, gap) t_dip, n_dip = time.perf_counter() - t_dip, int(cross.sum()) C[iu[1], iu[0]] = C[iu] t_form = time.perf_counter() - t C[0, 0] = np.abs(C[0, 1:]).sum() / (1 - ROW_SUM_EPS) infos = [r[3] for r in res] 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], "panels": [i["panels"] for i in infos], "panels_per_gap": [gap / i["h_um"] for i in infos], "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], "mesh_s": sum(i["mesh_s"] for i in infos), "assemble_s": sum(i["assemble_s"] for i in infos), "solve_s": sum(i["solve_s"] for i in infos), "build_s": sum(i["build_s"] for i in infos), "plan_s": t_plan, "windows_wall_s": t_win, "formula_s": t_form, "n_far_pairs": int(len(iu[0])), "dipole_s": t_dip, "n_dipole_pairs": n_dip, "budget": _LITE_BUDGET_USED[0], "workers": workers, "level_gaps": list(level_gaps)} info["total_s"] = time.perf_counter() - t_all return C, far, info
def pocket_ids(G, conds: list) -> np.ndarray: """Ground pocket of every conductor: index of the interior ring of the ground metal that contains it (STRtree of the rings' polygons, `within`); a conductor in no ring gets its own id (-1 - k).""" rings = [shapely.Polygon(r) for p in getattr(G, "geoms", [G]) for r in p.interiors] out = -1 - np.arange(len(conds)) if rings: c, r = shapely.STRtree(rings).query(list(conds), predicate="within") out[c] = r return out
def _edge_samples(geoms: list, step: float) -> tuple: """Points every <= step along every polygon edge of geoms (vertices included), with the index of their geometry: (points (n, 2), owner (n,)). Vectorised over all edges (no per-ring interpolation).""" segs, sown = [], [] for k, g in enumerate(geoms): for p in getattr(g, "geoms", [g]): for ring in [p.exterior, *p.interiors]: xy = np.asarray(ring.coords) segs.append(np.stack([xy[:-1], xy[1:]], 1)) sown.append(np.full(len(xy) - 1, k)) S, sown = np.concatenate(segs), np.concatenate(sown) L = np.sqrt(((S[:, 1] - S[:, 0]) ** 2).sum(1)) n = np.maximum(1, np.ceil(L / step).astype(int)) seg = np.repeat(np.arange(len(S)), n) t = (np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)) / np.repeat(n, n) return S[seg, 0] + t[:, None] * (S[seg, 1] - S[seg, 0]), sown[seg]
def dipole_far(G, conds: list, pairs, eps_r: float = 11.45, gap: float | None = None) -> np.ndarray: """Screened-dipole far couplings (PRIOR_SCHEME.md 14.2): for metal-index pairs (k, 2) (1 = first conductor), 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 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 nearest other metal: ground edge samples (step gap / 4) by one k-d tree, other conductors by one k-d tree of all conductor samples with owner labels (DIPOLE_K neighbours). Returns the values (k,).""" metals = [G] + list(conds) gap = gap_of(metals) if gap is None else gap pairs = np.asarray(pairs, int).reshape(-1, 2) pts, own = _edge_samples(list(conds), gap) own = own + 1 sel = np.isin(own, np.unique(pairs)) q = pts[sel] dg, _ = cKDTree(_edge_samples([G], gap / 4)[0]).query(q) d, idx = cKDTree(pts).query(q, k=min(DIPOLE_K, len(own))) if d.ndim == 1: d, idx = d[:, None], idx[:, None] d = np.where(own[np.minimum(idx, len(own) - 1)] != own[sel][:, None], d, np.inf).min(1) gbar = np.bincount(own[sel], np.minimum(dg, d), len(metals)) / np.maximum(np.bincount(own[sel], minlength=len(metals)), 1) area = np.array([g.area for g in metals]) perim = np.array([g.length for g in metals]) At = area + ALPHA_GAP_SHARE * perim * gbar cen = shapely.get_coordinates(shapely.centroid(np.array(metals, dtype=object))) a, b = pairs[:, 0], pairs[:, 1] d2 = ((cen[a] - cen[b]) ** 2).sum(1) + (At[a] + At[b]) / np.pi return -(1 + eps_r) * EPS0_FF_UM * At[a] * At[b] / (2 * np.pi * d2 ** 1.5)
def _ground_segments(G): """Edge segments (m, 2, 2) of the ground metal and an STRtree over them.""" _, S, _ = P._segments([G]) return S, shapely.STRtree(shapely.linestrings(S))
def _metal_length(A: np.ndarray, B: np.ndarray, S: np.ndarray, tree) -> np.ndarray: """Length of ground metal crossed by each segment A[k] -> B[k] (endpoints off the metal): crossings with the ground edges (STRtree) sorted along the segment, alternate inside / outside intervals summed.""" out = np.zeros(len(A)) if not len(A): return out li, gi = tree.query(shapely.linestrings(np.stack([A, B], 1)), predicate="intersects") if not len(li): return out p, r = A[li], B[li] - A[li] q, s = S[gi, 0], S[gi, 1] - S[gi, 0] den = r[:, 0] * s[:, 1] - r[:, 1] * s[:, 0] ok = np.abs(den) > 1e-12 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) order = np.lexsort((t, li)) li, t = li[order], t[order] start = np.r_[0, np.nonzero(np.diff(li))[0] + 1] n = np.diff(np.r_[start, len(li)]) rank = np.arange(len(li)) - np.repeat(start, n) keep = rank < np.repeat(n // 2 * 2, n) sgn = np.where(rank % 2 == 1, 1.0, -1.0) out += np.bincount(li[keep], weights=(sgn * t)[keep], minlength=len(A)) return out * np.sqrt(((B - A) ** 2).sum(1))
def _cps_m(d, w1, w2): """Coplanar-strip modulus (as `blocks.edge_features`; w = inf for the ground).""" if np.isinf(w1) or np.isinf(w2): wf = w2 if np.isinf(w1) else w1 return d / (d + wf) return d * (d + w1 + w2) / ((d + w1) * (d + w2))
_FORM: dict = {} # samples and trees of the running formula_prior call, inherited by forked row workers
def _formula_row(i: int) -> tuple: """Row i of the directed sums I[i, j] of `formula_prior` (j = the near metals of i; ground last term included).""" F = _FORM 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"] I = np.zeros(near.shape[0]) dmin_other, dG = np.full(len(pts[i]), np.inf), None for j in np.nonzero(near[i])[0]: d, idx = kd[j].query(pts[i], distance_upper_bound=R if j > 0 else np.inf) ok = np.isfinite(d) if j > 0: dmin_other = np.minimum(dmin_other, d) else: dG = d if not ok.any(): continue dd = np.maximum(d[ok], 0.05) if j == 0: S = np.ones(ok.sum()) else: sel = np.arange(0, ok.sum(), every) A = pts[i][ok][sel] lg = _metal_length(A, pts[j][idx[ok][sel]], F["SG"], F["gtree"]) S = np.exp(-lg / (dd[sel] + min(width[i], width[j])))[np.arange(ok.sum()) // every] I[j] = k * np.sum(step_um * _kratio(_cps_m(dd, width[i], width[j])) * S) if dG is not None: share = float(np.mean(dG <= dmin_other)) I[0] += 8 * EPS0_FF_UM * (1 + F["eps_r"]) / 2 * np.sqrt(F["area"][i] / np.pi) * share return i, I
def formula_prior(G, conds: list, eps_r: float = 11.45, step_um: float = FORMULA_STEP_UM, R_gaps: float = FORMULA_R_GAPS, pairs=None, gap: float | None = None, screen_um: float = FORMULA_SCREEN_UM, workers: int = 1, max_core: int = 8) -> tuple: """Closed-form edge-coupling prior (PRIOR_SCHEME.md section 12, F): (C (N+1, N+1) fF Maxwell, info). No mesh, no solve. 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 samples p of i (modulus of the local widths 2 A / P and the distance to the nearest sample of j, within R_gaps 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 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 ground). Pairs farther than R_gaps: the same form on the bounding boxes (facing length (P_i + P_j) / 2, distance of the boxes, l_G = ground area fraction x distance). Self terms: row sums / (1 - ROW_SUM_EPS). pairs (k, 2) of metal indices (0 = ground): only those mutual entries (the rest 0, no self terms). More than max_core conductors: the quadrature step is at least gap / 4 and the screening spacing at least one gap (numerically equivalent: median 0.02 %, max 1.2 % on the grids vs 0.25 um), rows on `workers` forked processes.""" t0 = time.perf_counter() metals = [G] + list(conds) N = len(metals) gap = gap_of(metals) if gap is None else gap if len(conds) > max_core: step_um, screen_um = max(step_um, gap / 4), max(screen_um, gap) R = R_gaps * gap k = EPS0_FF_UM * (1 + eps_r) / 2 want = np.zeros((N, N), bool) if pairs is None: want[np.triu_indices(N, 1)] = True else: pairs = np.sort(np.asarray(pairs, int).reshape(-1, 2), 1) want[pairs[:, 0], pairs[:, 1]] = True area = np.array([g.area for g in metals]) perim = np.array([g.length for g in metals]) width = np.r_[np.inf, 2 * area[1:] / perim[1:]] tree = shapely.STRtree(list(conds)) near = np.zeros((N, N), bool) a, b = tree.query(list(conds), predicate="dwithin", distance=R) near[a + 1, b + 1] = True near[0, 1:] = near[1:, 0] = True np.fill_diagonal(near, False) near &= want | want.T gx0, gy0, gx1, gy1 = G.bounds need = np.unique(np.nonzero(near)[0]) pts, kd = {}, {} for i in np.unique(np.r_[need, np.nonzero(near.any(0))[0]]): p = sample_boundary(metals[i], step_um) if i == 0: # ground edge = boundary of the etched region (not the chip outline) 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) p = p[~on] pts[i] = p kd[i] = cKDTree(p) SG, gtree = _ground_segments(G) _FORM.clear() _FORM.update(pts=pts, kd=kd, near=near, width=width, area=area, R=R, k=k, step=step_um, eps_r=eps_r, every=max(1, int(round(screen_um / step_um))), SG=SG, gtree=gtree) rows = [i for i in need if i > 0] if workers > 1 and len(rows) > 1: with ProcessPoolExecutor(min(workers, len(rows)), mp_context=get_context("fork")) as ex: res = list(ex.map(_formula_row, rows, chunksize=max(1, len(rows) // (4 * workers)))) else: res = [_formula_row(i) for i in rows] _FORM.clear() I = np.zeros((N, N)) for i, row in res: I[i] = row C = np.zeros((N, N)) iu = np.nonzero(np.triu(near, 1)) gnd = iu[0] == 0 C[iu] = np.where(gnd, I[iu[1], iu[0]], 0.5 * (I[iu] + I[iu[1], iu[0]])) fa, fb = np.nonzero(np.triu(want & ~near & ~near.T, 1)) if len(fa): bb = shapely.bounds(np.array(metals, dtype=object)) dx = np.maximum(0.0, np.maximum(bb[fa, 0] - bb[fb, 2], bb[fb, 0] - bb[fa, 2])) dy = np.maximum(0.0, np.maximum(bb[fa, 1] - bb[fb, 3], bb[fb, 1] - bb[fa, 3])) dd = np.maximum(np.hypot(dx, dy), 0.05) fG = G.area / max(shapely.box(*G.bounds).area, 1e-12) w1, w2 = width[fa], width[fb] m = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) S = np.exp(-fG * dd / (dd + np.minimum(w1, w2))) C[fa, fb] = k * 0.5 * (perim[fa] + perim[fb]) * _kratio(m) * S C = -(C + C.T) info = {"n_sampled_pairs": int(len(iu[0])), "n_bbox_pairs": int(len(fa)), "min_gap_um": gap, "step_um": step_um, "samples": int(sum(len(p) for p in pts.values()))} if pairs is None: np.fill_diagonal(C, np.abs(C).sum(1) / (1 - ROW_SUM_EPS)) info["total_s"] = time.perf_counter() - t0 return C, info123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210"""Local-gap (graded) lite micro-MoM prior: PRIOR_SCHEME.md Amendment MESH (2026-10-11).
The lite prior meshes every metal edge at h = gap / ppg with gap the layout's global smallest conductor gap. A sliver(exp12: the 35 nm end slit of a pad lead, 10.2 um long) therefore sets the whole mesh, and h sits on the size / 4096floor at every ppg (the resolution knob is dead). Here the panel size is set by the LOCAL gap of each quadtree cell:
h(cell) = clamp(local_gap(cell) / ppg, h_floor, H), H = G_ref / ppg, h_floor = size / FLOOR_DIV
local_gap(cell) = min over the metals k the cell touches and the other metals j of distance(cell & metal_k, metal_j)(the gap of the edge stretch inside the cell, never smaller than the global smallest gap); G_ref = the smallest pairgap among conductor pairs whose gap is >= SLIVER_UM ("sliver" pairs only refine their own neighbourhood). Same lattice(H 2^-k, anchored to the signal bounding box), exact cut panels, strip merge bounded by each panel's own size, slabkernel and exact near field as `fastprior.micro_mom`. A layout without a sliver pair is passed to `fastprior.micro_mom`unchanged (bit-identical prior). Resolution descriptor: proxy_min_gap_um = G_ref, proxy_h_min_um = H (log ppg)."""
from __future__ import annotations
import time
import numpy as npimport shapely
from . import fastprior as Ffrom . import proxy as P
SLIVER_UM = 0.25 # pair gaps below this are slivers (no labelled layout has a gap in [0.04, 1.99] um; exp12 slits 34.9-35.6 nm)FLOOR_DIV = 4096 # h_floor = layout size / FLOOR_DIV (the existing floor)
def ref_gap(metals: list, sliver: float = SLIVER_UM) -> tuple: """(G_ref, smallest gap, layout size, number of sliver pairs). G_ref = smallest pair gap >= sliver; when every pair is a sliver, the edge-length-weighted 5th percentile of the local gap of the boundary (0.25 um samples).""" gmin, size = F._gap_size(metals) n = len(metals) d = np.array([shapely.distance(metals[i], metals[j]) for i in range(n) for j in range(i + 1, n)]) ok = d >= sliver if ok.any(): return float(d[ok].min()), float(gmin), float(size), int((~ok).sum()) lg = [] for i, g in enumerate(metals): others = shapely.union_all([metals[k] for k in range(n) if k != i]) for ln in getattr(g.boundary, "geoms", [g.boundary]): pts = shapely.line_interpolate_point(ln, np.arange(0, ln.length, 0.25)) lg.append(shapely.distance(pts, others)) return float(max(np.percentile(np.concatenate(lg), 5), gmin)), float(gmin), float(size), int((~ok).sum())
def _local_gap(metals: list, boxes, hit, inn, pcs, sel) -> np.ndarray: """local_gap of the cells sel (indices): min over touched metals k and other metals j of distance(cell & k, j).""" lg = np.full(len(sel), np.inf) m = len(metals) for k in range(m): t = hit[k, sel] if not t.any(): continue ix = sel[t] geo = np.where(inn[k, ix], boxes[ix], pcs[k][ix]) bad = np.array([g is None for g in geo]) geo[bad] = boxes[ix][bad] dk = np.full(len(ix), np.inf) for j in range(m): if j != k: dk = np.minimum(dk, shapely.distance(geo, metals[j])) lg[t] = np.minimum(lg[t], dk) return lg
def anchored_cells_local(metals: list, H: float, h_floor: float, ppg: float, grade: float = 2.0, majority: bool = False): """`proxy.anchored_cells` on the lattice of H (anchored to the signal bounding box) with the finest level of every cell set by its local gap: a cell (cut or whole) is final once h <= clamp(local_gap / ppg, h_floor, H). Returns centres (n, 2), sizes (n, 2), owner (n,).""" edges = shapely.union_all([g.boundary for g in metals]) sig = metals[1:] if len(metals) > 1 else metals ax, ay = shapely.union_all(sig).bounds[:2] X0, Y0, X1, Y1 = shapely.union_all(metals).bounds span = max(X1 - X0, Y1 - Y0) K = max(0, int(np.ceil(np.log2(max(span / 16, H) / H)))) h0 = H * 2**K ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0)) ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0)) gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1)) xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) gq = P._Geoms(list(metals) + [edges]) tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) out_c, out_h, out_o = [], [], [] while len(xs): boxes = shapely.box(xs, ys, xs + h, ys + h) cov, hit, inn, pcs = P._cover(gq, boxes, h, tst, inn) keep = cov.sum(0) > 1e-3 xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep] pcs = [p[keep] for p in pcs] cx, cy = xs + h / 2, ys + h / 2 full = cov.max(0) > 0.999 cand = h <= H * 1.0001 last = cand & (h <= h_floor * 1.0001) need = np.nonzero(cand & ~last)[0] if len(need): tgt = np.clip(_local_gap(metals, boxes, hit, inn, pcs, need) / ppg, h_floor, H) last[need] = h[need] <= tgt * 1.0001 d = np.full(len(xs), np.inf) far = full & ~last d[far] = P._distance(gq, len(metals), boxes[far]) leaf = full & (last | (h <= grade * d + 1e-12)) out_c.append(np.stack([cx[leaf], cy[leaf]], 1)) out_h.append(np.stack([h[leaf], h[leaf]], 1)) out_o.append(cov[:, leaf].argmax(0)) cut = last & ~leaf if majority and cut.any(): take = cut & (cov.max(0) >= 0.5) out_c.append(np.stack([cx[take], cy[take]], 1)) out_h.append(np.stack([h[take], h[take]], 1)) out_o.append(cov[:, take].argmax(0)) cut = cut & False if cut.any(): gs = gq.get() for k, g in enumerate(gs[:len(metals)]): shapely.prepare(g) sel = np.nonzero(cut & (cov[k] > 1e-3))[0] if not len(sel): continue pcs_k = pcs[k][sel] bb = shapely.bounds(pcs_k) cen = shapely.get_coordinates(shapely.centroid(pcs_k)) inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) if not inside.all(): cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside])) out_c.append(cen) out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) out_o.append(np.full(len(sel), k)) gq.put(gs) split = ~leaf & ~last hs = h[split] / 2 xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) h = np.concatenate([hs] * 4) tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
def mesh_local(metals: list, H: float, h_floor: float, ppg: float, majority: bool = False) -> tuple: """Strip-merged local mesh (strip length <= 16 x the panel's own size and <= the distance to the nearest vertex). Returns (centres, sizes, owners, raw count).""" raw = anchored_cells_local(metals, H, h_floor, ppg, majority=majority) c, wh, o = F.strip_merge(*raw, metals, h_floor) return c, wh, o, len(raw[0])
def _solve(metals: list, H: float, h_floor: float, ppg: float, eps_r: float) -> tuple: """`fastprior._window_solve(all_rhs=True)` on the local mesh: rejected solves (not PD, a metal without a panel, a non-negative mutual entry) refine (H, h_floor) / 2 up to LITE_REFINE times, then majority-owned cut cells.""" t_mesh = t_sol = 0.0 cols = np.arange(len(metals)) refined, majority = 0, False while True: t = time.perf_counter() c, wh, o, n_raw = mesh_local(metals, H, h_floor, ppg, majority) t_mesh += time.perf_counter() - t t = time.perf_counter() try: if len(c) <= P.DENSE_MAX: A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) Q = P._chol_solve(A, (o[:, None] == cols[None, :]).astype(float)) del A else: Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r) R = np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) off = ~np.eye(len(metals), dtype=bool) ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and np.all(R[off] < 0)) except np.linalg.LinAlgError: ok = False t_sol += time.perf_counter() - t if ok or majority: break if refined < F.LITE_REFINE: H, h_floor, refined = H / 2, h_floor / 2, refined + 1 else: majority = True return R, {"H_um": H, "h_floor_um": h_floor, "h_min_um": float(wh.min()), "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, "solve_s": t_sol}
def micro_mom_loc(G, conds: list, eps_r: float = 11.45, ppg: float = 3.0, sliver: float = SLIVER_UM, floor_div: float = FLOOR_DIV, canonical: bool = True) -> tuple: """Local-gap lite prior of a <= 8-conductor layout: (C (N+1, N+1) fF, far_mask (all False), info). Layouts without a sliver pair: `fastprior.micro_mom(budget=inf, cells_per_gap=ppg)` (the existing liteppg prior, bit-identical). Mean over the canonical frames of symmetric layouts, returned in the input order (as micro_mom).""" t_all = time.perf_counter() metals = [G] + list(conds) gref, gmin, size, n_sl = ref_gap(metals, sliver) if n_sl == 0 or len(conds) > 8: # no sliver (or windows: out of scope) -> the existing prior C, far, info = F.micro_mom(G, conds, eps_r, budget=np.inf, cells_per_gap=ppg) info.update(local=False, G_ref_um=float(info["min_gap_um"]), H_um=float(min(info["h_um"])), n_sliver_pairs=n_sl) return C, far, info runs = [] frames = F.canonical_frames(G, conds) if canonical else [(G, list(conds), np.arange(len(conds)))] for Gc, cc, order in frames: R, wi = _solve([Gc] + list(cc), gref / ppg, size / floor_div, ppg, eps_r) C = 0.5 * (R + R.T) inv = np.r_[0, np.argsort(order) + 1] runs.append((C[np.ix_(inv, inv)], wi)) C = sum(r[0] for r in runs) / len(runs) wi = runs[0][1] info = {"local": True, "n_windows": 1, "n_frames": len(runs), "min_gap_um": gref, "G_ref_um": gref, "gmin_um": gmin, "n_sliver_pairs": n_sl, "H_um": wi["H_um"], "h_floor_um": wi["h_floor_um"], "h_um": [wi["H_um"]], "h_min_um": wi["h_min_um"], "panels": [wi["panels"]], "panels_per_gap": [gref / wi["H_um"]], "majority": [wi["majority"]], "refined": [wi["refined"]], "mesh_s": sum(r[1]["mesh_s"] for r in runs), "solve_s": sum(r[1]["solve_s"] for r in runs)} info["total_s"] = time.perf_counter() - t_all return C, np.zeros(C.shape, bool), info12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043"""Cheap physics proxy: thin-film method-of-moments capacitance on the metal masks.
Planar conductors of negligible thickness on a dielectric half-space: the quasi-static Green's function is1 / (4 pi eps0 eps_eff r) with eps_eff = (eps_r + 1) / 2. The metal is discretised into square cells (pulse basis,point matching); a uniformly charged square of side a has self-potential q / (4 pi eps0 eps_eff) * 4 ln(1 + sqrt 2) / a.Solving P q = v for each conductor at 1 V (others at 0 V) gives the full Maxwell capacitance matrix, includingshielding and other non-local effects that local descriptors cannot represent. Truncation: the ground plane isrepresented only inside the design window (a proxy, not a replacement for Q3D).
v2 (`mom_capacitance_gds`) works on the exact GDS polygons with the whole ground plane and an adaptive quadtree mesh(cells no larger than `grade` x their distance to a metal edge, edge cells down to ~1/3 of the smallest gap). On thegallery designs it reaches 5-6 % (NCAP, star) and 12 % (concentric) median error with no training, vs 14-32 % for v1."""
from __future__ import annotations
import osimport queueimport threadingfrom collections import OrderedDictfrom concurrent.futures import ThreadPoolExecutorfrom functools import partial
import numpy as npimport shapelyfrom scipy.linalg import cho_factor, cho_solvefrom scipy.spatial import cKDTree
EPS0_FF_PER_UM = 8.8541878128e-3SELF = 4 * np.log(1 + np.sqrt(2))NUM_THREADS = 0 # threads of the mesh / assembly pool and of the concurrent v3-rich solves; 0 = torch.get_num_threads()_LOCK = threading.Lock()_POOL: list = [] # [(threads, executor)]if hasattr(os, "register_at_fork"): os.register_at_fork(after_in_child=_POOL.clear) # a forked worker must not reuse the parent's pool threads
def _nthreads() -> int: if NUM_THREADS: return NUM_THREADS try: import torch except ImportError: return 1 return torch.get_num_threads()
def _run(tasks: list) -> list: """Results of the zero-argument callables in order, on the thread pool when more than one thread is allowed (numpy ufuncs and shapely's vectorised functions release the GIL). Tasks never wait on other pool tasks.""" n = _nthreads() if n < 2 or len(tasks) < 2: return [t() for t in tasks] with _LOCK: if not _POOL or _POOL[0][0] != n: _POOL[:] = [(n, ThreadPoolExecutor(n, thread_name_prefix="tlsq-mom"))] pool = _POOL[0][1] return list(pool.map(lambda t: t(), tasks))
def _spans(n: int, size: int) -> list: return [(a, min(a + size, n)) for a in range(0, n, size)]
class _Geoms: """Private copies of geometries (exact WKB round trip) handed out to one pool task at a time and made on demand: GEOS prepared geometries keep mutable search state and must not be shared between threads (nor with a concurrent solve)."""
def __init__(self, geoms: list): self.wkb, self.free = shapely.to_wkb(geoms), queue.SimpleQueue()
def get(self) -> list: try: return self.free.get_nowait() except queue.Empty: return list(shapely.from_wkb(self.wkb))
def put(self, gs: list) -> None: self.free.put(gs)
def _cover(gq, boxes, h, tst, inn): """Coverage area(box & metal) / h^2 of every box by every metal (m, n), evaluated exactly only where a box straddles a metal: a box properly inside a metal covers 1 and a box disjoint from it 0 (same decisions as the exact areas). tst (m, n): metals the box can touch (its parent did); inn (m, n): metals the box lies properly inside (from its parent). Returns cov, hit (box intersects the metal), inn, and per metal the pieces box & metal where they were computed.""" m, n = tst.shape cov, hit, inn = inn.astype(float), inn.copy(), inn.copy() pcs = [np.empty(n, dtype=object) for _ in range(m)] work = [(k, ix[a:b]) for k in range(m) for ix in [np.nonzero(tst[k])[0]] for a, b in _spans(len(ix), 256)]
def task(k, ix): gs = gq.get() try: g = gs[k] shapely.prepare(g) b = boxes[ix] ht = shapely.intersects(g, b) it = shapely.contains_properly(g, b) p = shapely.intersection(b[ht & ~it], g) return ht, it, p, shapely.area(p) finally: gq.put(gs)
for (k, ix), (ht, it, p, a) in zip(work, _run([partial(task, k, ix) for k, ix in work])): hit[k, ix], inn[k, ix] = ht, it cov[k, ix[it]] = 1.0 s = ix[ht & ~it] cov[k, s] = a / h[s] ** 2 pcs[k][s] = p return cov, hit, inn, pcs
def _distance(gq, j: int, geoms) -> np.ndarray: """shapely.distance(geoms, geometry j of the queue), in chunks on the pool.""" def task(a, b): gs = gq.get() try: return shapely.distance(geoms[a:b], gs[j]) finally: gq.put(gs) return np.concatenate([np.zeros(0)] + _run([partial(task, a, b) for a, b in _spans(len(geoms), 256)]))
def mom_capacitance(masks: np.ndarray, window_um: float, eps_r: float = 11.45, cells: int = 64) -> np.ndarray: """masks: (n_cond, R, R) coverage in [0, 1] (channel 0 = ground). Returns the (n_cond, n_cond) Maxwell C in fF.""" nc, R, _ = masks.shape f = R // cells cov = masks.reshape(nc, cells, f, cells, f).mean((2, 4)) # coverage per coarse cell owner = np.where(cov.max(0) >= 0.5, cov.argmax(0), -1) ii, jj = np.nonzero(owner >= 0) lab = owner[ii, jj] a = window_um / cells xy = np.stack([(jj + 0.5) * a, (ii + 0.5) * a], 1) d = np.sqrt(((xy[:, None, :] - xy[None, :, :]) ** 2).sum(-1)) np.fill_diagonal(d, 1.0) P = 1.0 / d np.fill_diagonal(P, SELF / a) P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 B = (lab[:, None] == np.arange(nc)[None, :]).astype(float) # conductor b at 1 V Q = cho_solve(cho_factor(P, lower=True), B) C = np.stack([Q[lab == a_].sum(0) for a_ in range(nc)]) # C[a, b] = charge on a with b at 1 V return 0.5 * (C + C.T)
def quadtree_cells(metals: list, bbox, h0: float, h_min: float, grade: float = 2.0, limit: int | None = None): """Square cells covering the metal polygons: a cell is kept whole when it lies inside one conductor and is no larger than `grade` x its distance to the nearest metal edge; edge cells are split down to h_min, where they go to the conductor covering >= 50 % of them. Returns centres (n, 2), sides (n,), owner (n,); None once more than `limit` cells.""" edges = shapely.union_all([g.boundary for g in metals]) x0, y0, x1, y1 = bbox nx, ny = int(np.ceil((x1 - x0) / h0)), int(np.ceil((y1 - y0) / h0)) gx, gy = np.meshgrid(x0 + h0 * np.arange(nx), y0 + h0 * np.arange(ny)) xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) gq = _Geoms(list(metals) + [edges]) tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) out_c, out_h, out_o, count = [], [], [], 0 while len(xs): boxes = shapely.box(xs, ys, xs + h, ys + h) cov, hit, inn, _ = _cover(gq, boxes, h, tst, inn) keep = cov.sum(0) > 1e-3 xs, ys, h, cov, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], hit[:, keep], inn[:, keep] cx, cy = xs + h / 2, ys + h / 2 full = cov.max(0) > 0.999 d = np.full(len(xs), np.inf) # the edge distance only decides for cells inside one conductor d[full] = _distance(gq, len(metals), shapely.points(cx[full], cy[full])) leaf = full & (h <= grade * d + 1e-12) last = h <= h_min * 1.0001 take_last = last & ~leaf & (cov.max(0) >= 0.5) acc = leaf | take_last out_c.append(np.stack([cx[acc], cy[acc]], 1)) out_h.append(h[acc]) out_o.append(cov[:, acc].argmax(0)) count += int(acc.sum()) if limit is not None and count > limit: return None split = ~acc & ~last hs = h[split] / 2 xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) h = np.concatenate([hs] * 4) tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
def anchored_cells(metals: list, h_f: float, grade: float = 2.0, majority: bool = False, limit: int | None = None): """v3 mesh: quadtree on a lattice anchored to the signal conductors, independent of the chip size and position.
Finest cells have side h_f; coarse cells are h_f * 2^k on the same lattice (origin = lower-left corner of the signal conductors' bounding box), so the cells near the conductors do not change when the ground plane grows, shrinks or the layout is translated. A cell is kept whole when it lies inside one conductor and is no larger than `grade` x the distance from the cell to the nearest metal edge (cells touching an edge reach h_f); finest-level cells that straddle an edge are cut along the exact polygon boundaries into one panel per metal (no rounding of gaps to the grid). Returns centres (n, 2), sizes (n, 2) = (width, height) of each panel, owner (n,); None once the mesh has more than `limit` cells.""" edges = shapely.union_all([g.boundary for g in metals]) sig = metals[1:] if len(metals) > 1 else metals ax, ay = shapely.union_all(sig).bounds[:2] X0, Y0, X1, Y1 = shapely.union_all(metals).bounds span = max(X1 - X0, Y1 - Y0) K = max(0, int(np.ceil(np.log2(max(span / 16, h_f) / h_f)))) h0 = h_f * 2**K ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0)) ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0)) gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1)) xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0) gq = _Geoms(list(metals) + [edges]) tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool) out_c, out_h, out_o, count = [], [], [], 0 while len(xs): boxes = shapely.box(xs, ys, xs + h, ys + h) cov, hit, inn, pcs = _cover(gq, boxes, h, tst, inn) keep = cov.sum(0) > 1e-3 xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep] pcs = [p[keep] for p in pcs] cx, cy = xs + h / 2, ys + h / 2 full = cov.max(0) > 0.999 last = h <= h_f * 1.0001 d = np.full(len(xs), np.inf) # the edge distance only decides for whole cells above the finest level far = full & ~last d[far] = _distance(gq, len(metals), boxes[far]) leaf = full & (last | (h <= grade * d + 1e-12)) out_c.append(np.stack([cx[leaf], cy[leaf]], 1)) out_h.append(np.stack([h[leaf], h[leaf]], 1)) out_o.append(cov[:, leaf].argmax(0)) count += int(leaf.sum()) cut = last & ~leaf if majority and cut.any(): take = cut & (cov.max(0) >= 0.5) out_c.append(np.stack([cx[take], cy[take]], 1)) out_h.append(np.stack([h[take], h[take]], 1)) out_o.append(cov[:, take].argmax(0)) count += int(take.sum()) cut = cut & False if cut.any(): gs = gq.get() for k, g in enumerate(gs[:-1]): shapely.prepare(g) sel = np.nonzero(cut & (cov[k] > 1e-3))[0] if not len(sel): continue pcs_k = pcs[k][sel] # box & metal, computed by _cover (straddling cells only reach this level uncut) bb = shapely.bounds(pcs_k) cen = shapely.get_coordinates(shapely.centroid(pcs_k)) inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) if not inside.all(): rp = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside])) cen[~inside] = rp out_c.append(cen) out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) out_o.append(np.full(len(sel), k)) count += len(sel) gq.put(gs) if limit is not None and count > limit: return None split = ~leaf & ~last hs = h[split] / 2 xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs]) ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs]) h = np.concatenate([hs] * 4) tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4) return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
def mom_mesh(metals: list, max_cells: int = 8000, h_min: float | None = None, grade: float = 2.0, cells_per_gap: float = 3.0, mesh: str = "v2", offset: tuple = (0.0, 0.0)): """Mesh for the thin-film MoM. mesh="v3": conductor-anchored lattice with exact edge panels (`anchored_cells`); mesh="v2" (default, published priors): the original chip-anchored quadtree (reproduces the published v2 priors). Returns (centres, sides, owner, h_min).""" bbox = shapely.union_all(metals).bounds size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) if h_min is None: gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) h_min = max(gap / cells_per_gap, size / 4096) if mesh == "v2" and any(offset): h0 = size / 16 bbox = (bbox[0] - offset[0] * h0, bbox[1] - offset[1] * h0, bbox[2] + h0, bbox[3] + h0) while True: if mesh == "v3": r = anchored_cells(metals, h_min, grade, limit=max_cells) else: r = quadtree_cells(metals, bbox, size / 16, h_min, grade, limit=max_cells) if r is not None: return (*r, h_min) h_min *= 1.5 if mesh == "v2" else 2.0 # v3: stay on the same lattice
def rect_self(a, b): """Potential at the centre of a uniformly charged a x b rectangle per unit charge, times 4 pi eps (= SELF / a for a square).""" r = np.sqrt(a**2 + b**2) return (2 * a * np.log((b + r) / a) + 2 * b * np.log((a + r) / b)) / (a * b)
def _mom_solve_torch(c, h, o, n_metals, eps_r, dev): """Same assembly and Cholesky solve as `mom_solve`, in float64 torch on `dev` (opt-in via TLSQ_MOM_DEVICE).""" import torch
t = lambda x: torch.as_tensor(np.ascontiguousarray(x), dtype=torch.float64, device=dev) # noqa: E731 wh = np.stack([h, h], 1) if h.ndim == 1 else h C, WH = t(c), t(wh) hm = WH.max(1).values d = torch.cdist(C, C) d.fill_diagonal_(1.0) P = 1.0 / d near = d < 1.5 * torch.maximum(hm[:, None], hm[None, :]) near.fill_diagonal_(False) del d ii, jj = torch.nonzero(near, as_tuple=True) del near if len(ii): off = (torch.arange(3, dtype=torch.float64, device=dev) - 1) / 3 ox, oy = torch.meshgrid(off, off, indexing="xy") sx = C[jj, 0, None] + ox.reshape(-1)[None] * WH[jj, 0, None] sy = C[jj, 1, None] + oy.reshape(-1)[None] * WH[jj, 1, None] r = torch.sqrt((C[ii, 0, None] - sx) ** 2 + (C[ii, 1, None] - sy) ** 2) P[ii, jj] = (1.0 / torch.clamp(r, min=1e-9)).mean(1) P = 0.5 * (P + P.T) diag = t(rect_self(wh[:, 0], wh[:, 1]) if h.ndim == 2 else SELF / h) P.diagonal().copy_(diag) P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 B = t((o[:, None] == np.arange(n_metals)[None, :]).astype(float)) L, info = torch.linalg.cholesky_ex(P) del P if int(info): raise np.linalg.LinAlgError(f"{int(info)}-th leading minor not positive definite") return torch.cholesky_solve(B, L).cpu().numpy()
def _mom_solve_gpu_slot(c, h, o, n_metals, eps_r): """GPU solve if one of TLSQ_MOM_GPU_SLOTS slots (file locks shared by the worker processes) is free and the solve fits; None means: solve on the CPU instead.""" import fcntl import os import tempfile
import torch
slots = int(os.environ.get("TLSQ_MOM_GPU_SLOTS", "3")) tag = os.environ.get("SLURM_JOB_ID", "local") for k in range(slots): f = open(os.path.join(tempfile.gettempdir(), f"tlsq_gpu_{tag}_{k}.lock"), "w") try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: f.close() continue try: return _mom_solve_torch(c, h, o, n_metals, eps_r, os.environ["TLSQ_MOM_DEVICE"]) except RuntimeError as e: # includes torch.OutOfMemoryError if "out of memory" not in str(e).lower(): raise return None finally: torch.cuda.empty_cache() fcntl.flock(f, fcntl.LOCK_UN) f.close() return None
def _G(x, y): """Antiderivative of 1 / sqrt(x^2 + y^2) over x and y: x asinh(y / |x|) + y asinh(x / |y|) (0 on the axes).""" ax, ay = np.abs(x), np.abs(y) with np.errstate(divide="ignore", invalid="ignore"): g1 = np.where(ax > 0, x * np.arcsinh(y / np.where(ax > 0, ax, 1.0)), 0.0) g2 = np.where(ay > 0, y * np.arcsinh(x / np.where(ay > 0, ay, 1.0)), 0.0) return g1 + g2
def rect_potential(p, cq, wh): """Exact potential (x 4 pi eps) at points p (n, 2) of uniformly charged rectangles (unit total charge) centred at cq with sizes wh (n, 2): (1 / (w h)) * integral of 1 / r over the rectangle. Equals rect_self at the centre.""" x1, x2 = cq[:, 0] - wh[:, 0] / 2 - p[:, 0], cq[:, 0] + wh[:, 0] / 2 - p[:, 0] y1, y2 = cq[:, 1] - wh[:, 1] / 2 - p[:, 1], cq[:, 1] + wh[:, 1] / 2 - p[:, 1] return (_G(x2, y2) - _G(x1, y2) - _G(x2, y1) + _G(x1, y1)) / (wh[:, 0] * wh[:, 1])
def _mom_solve_exact_near(c, wh, o, n_metals, eps_r): """v3 panels: exact rectangle potential for near pairs (d < 1.5 max side) instead of the 3x3 point average. Used only when the 3x3 system is not positive definite (sliver edge panels on long fine combs), so priors that solved before are unchanged.""" P = _assemble(c, wh, rect_self(wh[:, 0], wh[:, 1]), eps_r, rect_potential) B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float) return _chol_solve(P, B)
def mom_solve(c, h, o, n_metals: int, eps_r: float = 11.45): """mom_solve_quad; for v3 panels (h of shape (n, 2)) a non-positive-definite system is re-solved with the exact near field (`_mom_solve_exact_near`).""" try: return mom_solve_quad(c, h, o, n_metals, eps_r) except np.linalg.LinAlgError: if h.ndim != 2: raise print("v3: 3x3 near-field system not positive definite, exact near field", flush=True) return _mom_solve_exact_near(c, h, o, n_metals, eps_r)
def mom_solve_quad(c, h, o, n_metals: int, eps_r: float = 11.45): """Point-matching solve on a mesh from `mom_mesh`: cell charges Q (n_cells, n_metals) for each conductor at 1 V. h: square sides (n,) or panel (width, height) (n, 2). Set TLSQ_MOM_DEVICE=cuda to assemble and solve on a GPU.""" import os
if os.environ.get("TLSQ_MOM_DEVICE") and SUBSTRATE["model"] == "halfspace": # the torch path has no image correction Q = _mom_solve_gpu_slot(c, h, o, n_metals, eps_r) if Q is not None: return Q wh = np.stack([h, h], 1) if h.ndim == 1 else h P = _assemble(c, wh, rect_self(wh[:, 0], wh[:, 1]) if h.ndim == 2 else SELF / h, eps_r, _near_quad) B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float) return _chol_solve(P, B)
def _near_quad(p, cq, wh): """Potential (x 4 pi eps) at points p of the panels centred at cq with sizes wh: mean of 1 / r over a 3x3 sample of the panel (point matching is poor for close, unequal cells).""" off = (np.arange(3) - 1) / 3 ox, oy = np.meshgrid(off, off) sx = cq[:, 0, None] + ox.ravel()[None] * wh[:, 0, None] sy = cq[:, 1, None] + oy.ravel()[None] * wh[:, 1, None] r = np.sqrt((p[:, 0, None] - sx) ** 2 + (p[:, 1, None] - sy) ** 2) return (1.0 / np.maximum(r, 1e-9)).mean(1)
def _near_pairs(c, hm): """Pairs i < j with |c_i - c_j| < 1.5 max(hm_i, hm_j): candidates from k-d trees per cell-size class, kept by the same floating-point test as the dense mask.""" n = len(c) tree, lev, key = cKDTree(c), np.floor(np.log2(hm)), [np.zeros(0, np.int64)] for L in np.unique(lev): sel = np.nonzero(lev == L)[0] pr = cKDTree(c[sel]).sparse_distance_matrix(tree, 1.5 * hm[sel].max() * (1 + 1e-9), output_type="ndarray") a, b = sel[pr["i"]], pr["j"] key.append(np.minimum(a, b) * n + np.maximum(a, b)) key = np.unique(np.concatenate(key)) ii, jj = key // n, key % n ok = (ii != jj) & (np.sqrt((c[ii, 0] - c[jj, 0]) ** 2 + (c[ii, 1] - c[jj, 1]) ** 2) < 1.5 * np.maximum(hm[ii], hm[jj])) return ii[ok], jj[ok]
SUBSTRATE = {"model": "slab_open", "t_um": 350.0} # MoM Green's function (PRIOR_SCHEME.md 14.6): "slab_open" (default since 2026-10-10: 350 um substrate, vacuum below), "halfspace" (released models' priors), "slab_pec"_IMG_CACHE: OrderedDict = OrderedDict() # LRU of image tables (model, t_um, eps_r) -> (du, T, w, D)_IMG_GRID: dict = {}_IMG_KEEP = (4, 512 << 20) # at most 4 tables and 512 MB (the newest is always kept)_INTERP: dict = {}
def _img_evict(): while len(_IMG_CACHE) > 1 and (len(_IMG_CACHE) > _IMG_KEEP[0] or sum(v[1].nbytes for v in _IMG_CACHE.values()) + sum(g.nbytes for g in _IMG_GRID.values()) > _IMG_KEEP[1]): _IMG_GRID.pop(_IMG_CACHE.popitem(last=False)[0], None)
try: # compiled np.interp on the uniform image table (_interp_uniform) import numba as _nb from numba.core import types as _nbt from numba.extending import intrinsic as _intrinsic
@_intrinsic def _fma(typingctx, a, b, c): def gen(context, builder, sig, args): return builder.fma(*args) return _nbt.float64(_nbt.float64, _nbt.float64, _nbt.float64), gen
@_nb.njit(nogil=True, cache=True) def _interp_run(x, du, fp, out, fused): """numpy's arr_interp on xp_j = du * j: the index by division, corrected with numpy's comparisons, then numpy's slope and slope * (x - xp_j) + fp_j, plain or fused (fma) as this numpy build's C compiler does it.""" n = fp.shape[0] last = du * (n - 1) for i in range(x.shape[0]): v = x[i] if v != v: out[i] = v continue if v > last: out[i] = fp[n - 1] continue if v < 0.0: out[i] = fp[0] continue j = min(int(v / du), n - 1) while j > 0 and du * j > v: j -= 1 while j < n - 1 and du * (j + 1) <= v: j += 1 xj = du * j if j == n - 1 or xj == v: out[i] = fp[j] continue x1 = du * (j + 1) s = (fp[j + 1] - fp[j]) / (x1 - xj) r = _fma(s, v - xj, fp[j]) if fused else s * (v - xj) + fp[j] if r != r: r = _fma(s, v - x1, fp[j + 1]) if fused else s * (v - x1) + fp[j + 1] if r != r and fp[j] == fp[j + 1]: r = fp[j] out[i] = rexcept ImportError: _interp_run = None
def _interp_uniform(d, du, T): """np.interp(d, du * arange(len(T)), T), bit for bit: the compiled kernel (plain or fused multiply-add, whichever matches this numpy build) when a probe at first use matches np.interp bit for bit, else None (the caller uses np.interp).""" if "fn" not in _INTERP: _INTERP["fn"] = None if _interp_run is not None: try: rng, ok = np.random.default_rng(0), [] for fp in (rng.normal(size=4096), T): # a rough table tells the two apart, then the real one xp = du * np.arange(len(fp)) x = np.concatenate([rng.uniform(-1, 1.01 * xp[-1], 50000), rng.uniform(0, 64 * du, 20000), xp[rng.integers(0, len(fp), 2000)], np.nextafter(xp[rng.integers(1, len(fp), 2000)], 0), xp[[0, -1]], [np.nan, np.inf, 1e300]]) ref, got = np.interp(x, xp, fp).tobytes(), [] for fused in (False, True): y = np.empty_like(x) _interp_run(x, du, fp, y, fused) got.append(y.tobytes()) ok.append([g == ref for g in got]) if ok[0][0] != ok[0][1] and ok[1][ok[0][1]]: _INTERP["fn"] = ok[0][1] except Exception: # noqa: BLE001 (llvm.fma or the compile unavailable: np.interp) pass fused = _INTERP["fn"] d = np.asarray(d, float) if fused is None or d.ndim == 0: return None x = np.ascontiguousarray(d) out = np.empty(x.shape) _interp_run(x.reshape(-1), du, T, out.reshape(-1), fused) return out
class substrate: """Context manager: the MoM Green's function inside the block (`SUBSTRATE`): model "slab_open" (default since 2026-10-10, PRIOR_SCHEME.md 14.6), "halfspace" (the kernel of the priors the released models were trained on) or "slab_pec"; t_um the substrate thickness (None: unchanged)."""
def __init__(self, model: str | None, t_um: float | None = None): self.new = {k: v for k, v in (("model", model), ("t_um", t_um)) if v is not None}
def __enter__(self): self.old = dict(SUBSTRATE) SUBSTRATE.update(self.new) return self
def __exit__(self, *exc): SUBSTRATE.clear() SUBSTRATE.update(self.old)
def _image_correction(d, eps_r: float, exact: bool = False): """Finite-substrate correction to the half-space kernel 1 / d (same units): sum_n w_n / sqrt(d^2 + D_n^2) for panels on the top face of a slab of thickness t (SUBSTRATE): "slab_open" = vacuum below (w_n = K^2n + K^(2n-1), D_n = 2 n t, K = (eps_r - 1) / (eps_r + 1); weights sum to eps_eff - 1, so the kernel tends to the vacuum one for d >> eps_r t), "slab_pec" = metal backside (w_n = -(1 + K) (-K)^(n-1); weights sum to -1). Images up to K^2n < 1e-4, the remaining weight as one more image; tabulated on a uniform grid of t / 1000 up to 100 mm and interpolated linearly (dense assembly), or summed exactly (exact=True: the H-matrix kernel, whose ACA blocks need a smooth kernel). None for the half-space (the published kernel).""" m = SUBSTRATE["model"] if m == "halfspace": return None key = (m, float(SUBSTRATE["t_um"]), float(eps_r)) if key in _IMG_CACHE: _IMG_CACHE.move_to_end(key) else: K, t = (eps_r - 1) / (eps_r + 1), float(SUBSTRATE["t_um"]) n = np.arange(1, 400) nmax = int(np.argmax(K ** (2 * n) < 1e-4)) + 1 n = n[:nmax] if m == "slab_open": w, total = K ** (2 * n) + K ** (2 * n - 1), K / (1 - K) else: w, total = -(1 + K) * (-K) ** (n - 1), -1.0 w, D = np.r_[w, total - w.sum()], np.r_[2 * n * t, 2 * (nmax + 1) * t] du = t / 1000 u = np.arange(0.0, 1e5 + 2 * du, du) T = np.empty(len(u)) for i in range(0, len(u), 1 << 18): # row blocks: the same sums, without len(u) x images temporaries (~8 GB at 10 um) ub = u[i:i + (1 << 18)] T[i:i + len(ub)] = (w[None, :] / np.sqrt(ub[:, None] ** 2 + D[None, :] ** 2)).sum(1) _IMG_CACHE[key] = (du, T, w, D) _img_evict() du, T = _IMG_CACHE[key][:2] if exact: w, D = _IMG_CACHE[key][2:] d2 = np.asarray(d, float) ** 2 return sum(wn / np.sqrt(d2 + Dn * Dn) for wn, Dn in zip(w, D)) out = _interp_uniform(d, du, T) if out is not None: return out if key not in _IMG_GRID: _IMG_GRID[key] = du * np.arange(len(T)) return np.interp(d, _IMG_GRID[key], T)
def _assemble(c, wh, diag, eps_r: float, near): """Interaction matrix / (4 pi eps0 eps_eff) for the lower Cholesky factorisation: far pairs 1 / d, near pairs (d < 1.5 max side) the symmetrised near(p, cq, wh) potential, diagonal `diag`; the same numbers as the dense construction. Built in row blocks on the pool threads without n x n temporaries, and only the half the factorisation reads: returns a Fortran-ordered matrix whose lower triangle holds the entries (its upper triangle is not initialised).""" n = len(c) k = 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 A = np.empty((n, n)) x, y = c[:, 0], c[:, 1]
def rows(r0, r1): d = x[r0:r1, None] - x[None, r0:] np.multiply(d, d, out=d) t = y[r0:r1, None] - y[None, r0:] np.multiply(t, t, out=t) d += t np.sqrt(d, out=d) corr = _image_correction(d, eps_r) d[np.arange(r1 - r0), np.arange(r1 - r0)] = 1.0 out = A[r0:r1, r0:] np.divide(1.0, d, out=out) if corr is not None: out += corr out /= k
_run([partial(rows, a, b) for a, b in _spans(n, 64)]) ii, jj = _near_pairs(c, wh.max(1)) img = _image_correction(np.zeros(1), eps_r) if len(ii): A[ii, jj] = 0.5 * (near(c[ii], c[jj], wh[jj]) + near(c[jj], c[ii], wh[ii])) / k if img is not None: A[ii, jj] += _image_correction(np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)), eps_r) / k A[np.arange(n), np.arange(n)] = diag / k if img is None else (diag + img[0]) / k return A.T
def _chol_solve(P, B): """Cholesky solve with the lower triangle of the Fortran-ordered P from `_assemble`, factorised in place (no copy).""" return cho_solve(cho_factor(P, lower=True, overwrite_a=True, check_finite=False), B, check_finite=False)
def mom_capacitance_gds(metals: list, eps_r: float = 11.45, max_cells: int = 8000, h_min: float | None = None, grade: float = 2.0, cells_per_gap: float = 3.0, offset: tuple = (0.0, 0.0), mesh: str = "v2"): """Thin-film MoM on the exact GDS polygons (ground to the chip edge), adaptive quadtree mesh (see `mom_mesh`).
metals: shapely geometries, one per conductor (index 0 = ground). `offset` (v2 mesh only) shifts the quadtree origin by that fraction of the coarsest cell. Returns (C fF in the same order, n_cells, h_min).""" c, h, o, h_min = mom_mesh(metals, max_cells, h_min, grade, cells_per_gap, mesh, offset) try: Q = mom_solve(c, h, o, len(metals), eps_r) # v3: exact near field if the 3x3 system is not positive definite except np.linalg.LinAlgError: if mesh != "v3": raise # cell cap coarser than the finger pitch: cut-panel boxes of different conductors overlap; finest cells as whole # squares owned by the metal covering >= 50 % (as the v2 mesh), exact near field print("v3: still not positive definite, majority finest cells", flush=True) c, h, o = anchored_cells(metals, h_min, grade, majority=True) Q = _mom_solve_exact_near(c, h, o, len(metals), eps_r) C = np.stack([Q[o == a].sum(0) for a in range(len(metals))]) return 0.5 * (C + C.T), len(c), h_min
def mom_capacitance_gds_avg(metals: list, n_offsets: int = 4, **kw): """MoM averaged over quadtree origins (offsets on a diagonal grid of the coarsest cell): removes the part of the discretisation error that jumps with mesh alignment as the geometry is swept.""" offs = [(i / n_offsets, ((i * 3) % n_offsets) / n_offsets) for i in range(n_offsets)] runs = [mom_capacitance_gds(metals, offset=o, mesh="v2", **kw) for o in offs] return np.mean([r[0] for r in runs], 0), int(np.mean([r[1] for r in runs])), runs[0][2]
def _both(f, g): """(f(), g()), a LinAlgError in place of a result; concurrently (g on a helper thread) when more than one thread is allowed: the gap/6 and gap/3 solves of v3-rich are independent.""" def call(fn): try: return fn() except np.linalg.LinAlgError as e: return e if _nthreads() < 2: return call(f), call(g) with ThreadPoolExecutor(1, thread_name_prefix="tlsq-rich") as ex: fut = ex.submit(call, g) a = call(f) return a, fut.result()
def mom_capacitance_gds_rich(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 8000, max_cells_fine: int = 16000, grade: float = 2.0): """v3 MoM with Richardson extrapolation: solves at gap/cells_per_gap and at half that cell size on the same conductor-anchored lattice and extrapolates the first-order discretisation error to zero cell size. If the cell cap forces both meshes to the same resolution, returns the finer solve. If the coarse system is not positive definite (sliver edge panels badly resolved by the 3x3 near-field rule; ~0.2 % of designs), returns the other solve alone (fine if the coarse one fails, coarse if the fine one fails). The two solves run concurrently when more than one thread is allowed. Returns (C, total cells, h of the fine mesh).""" rf, rc = _both(partial(mom_capacitance_gds, metals, eps_r, max_cells_fine, None, grade, 2 * cells_per_gap, mesh="v3"), partial(mom_capacitance_gds, metals, eps_r, max_cells, None, grade, cells_per_gap, mesh="v3")) if isinstance(rf, np.linalg.LinAlgError): print("v3-rich: fine mesh not positive definite, coarse solve only", flush=True) if isinstance(rc, np.linalg.LinAlgError): raise rc return rc Cf, nf, hf = rf if isinstance(rc, np.linalg.LinAlgError): print("v3-rich: coarse mesh not positive definite, fine solve only", flush=True) return Cf, nf, hf Cc, nc, hc = rc r = hc / hf C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1) return C, nc + nf, hf
# ---------------------------------------------------------------- flagship prior: strip-merged mesh, H-matrix solve, Richardson# Resolution-controlled (panels per gap, no small cap), the same conductor-anchored panels as v3 merged along straight# edges, the exact rectangle potential for near pairs, and for large systems an H-matrix (ACA far field) with# preconditioned CG instead of the dense Cholesky: O(n log n) time and memory.
DENSE_MAX = int(os.environ.get("TLSQ_MOM_DENSE_MAX", 12000)) # panels up to which the dense Cholesky is used (faster below this size)HMAT = dict(leaf=128, eta=2.0, eps=1e-9, tol=1e-12, maxit=1000) # ACA block tolerance (relative Frobenius) and PCG residual
def _segments(metals): segs, verts = [], [] for g in metals: for p in getattr(g, "geoms", [g]): for ring in [p.exterior, *p.interiors]: xy = np.asarray(ring.coords) verts.append(xy[:-1]) segs.append(np.stack([xy[:-1], xy[1:]], 1)) S = np.concatenate(segs) return shapely.linestrings(S), S, np.concatenate(verts)
def strip_merge(c, wh, o, metals, h_f, lmax_mult: float = 16.0, grade: float = 1.0): """Merge runs of equal-width panels along the direction of their nearest polygon edge (where the charge density is translation-invariant) into panels of length <= lmax_mult * h_f and <= grade * distance to the nearest vertex; the size across the edge is kept. Returns merged (centres, sizes, owners).""" lines, S, verts = _segments(metals) near = shapely.STRtree(lines).nearest(shapely.points(c)) d = S[near, 1] - S[near, 0] horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1]) dv, _ = cKDTree(verts).query(c, workers=-1) allow = np.minimum(lmax_mult * h_f, grade * dv) out_c, out_wh, out_o = [], [], [] for axis, mask in ((0, horiz), (1, ~horiz)): if not mask.any(): continue idx = np.nonzero(mask)[0] other = 1 - axis key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1) order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]]) idx, key = idx[order], key[order] same = np.all(key[1:] == key[:-1], 1) lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2 adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6) start = 0 while start < len(idx): end, length, cap = start, wh[idx[start], axis], allow[idx[start]] while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]): end += 1 length += wh[idx[end], axis] cap = min(cap, allow[idx[end]]) cc, ww = np.zeros(2), np.zeros(2) cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other] ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other] out_c.append(cc) out_wh.append(ww) out_o.append(o[idx[start]]) start = end + 1 return np.array(out_c), np.array(out_wh), np.array(out_o)
def mesh_flagship(metals: list, h: float, max_cells: int, grade: float = 2.0, lmax_mult: float = 16.0, merge_grade: float = 1.0, majority: bool = False): """Strip-merged v3 mesh at finest panel h, doubled (same lattice) until the merged mesh has at most max_cells panels. Returns (centres, sizes, owners, h, raw panel count).""" while True: raw = anchored_cells(metals, h, grade, majority=majority, limit=8 * max_cells) if raw is not None: c, wh, o = strip_merge(*raw, metals, h, lmax_mult, merge_grade) if len(c) <= max_cells: return c, wh, o, h, len(raw[0]) h *= 2.0
class _Kernel: """Entries of P / (4 pi eps0 eps_eff) in a permuted panel order: 1 / d for far pairs, the exact rectangle potential for near pairs (d < 1.5 max side) and rect_self on the diagonal; near and diagonal corrections to 1 / d are held in a CSR matrix so that any block is 1 / d + N[I, J] (the same numbers as `_assemble` with `rect_potential`)."""
def __init__(self, c, wh, eps_r, perm): from scipy.sparse import csr_matrix
self.x, self.y = c[perm, 0].copy(), c[perm, 1].copy() self.k = 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 self.eps_r = eps_r self.img = _image_correction(np.zeros(1), eps_r) is not None # finite-substrate image term (exact series in blocks / rows) n = len(c) ii, jj = _near_pairs(c, wh.max(1)) d = np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)) near = 0.5 * (rect_potential(c[ii], c[jj], wh[jj]) + rect_potential(c[jj], c[ii], wh[ii])) - 1.0 / d inv = np.empty(n, np.int64) inv[perm] = np.arange(n) rows = inv[np.concatenate([ii, jj, np.arange(n)])] cols = inv[np.concatenate([jj, ii, np.arange(n)])] vals = np.concatenate([near, near, rect_self(wh[:, 0], wh[:, 1]) - 1.0]) self.N = csr_matrix((vals, (rows, cols)), shape=(n, n))
def block(self, a0, a1, b0, b1): 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) corr = _image_correction(d, self.eps_r, exact=True) if a0 == b0: d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0 A = 1.0 / d if corr is not None: A += corr Nb = self.N[a0:a1, b0:b1] if Nb.nnz: A += Nb.toarray() return A / self.k
def row(self, i, b0, b1): d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2) r = 1.0 / d if self.img: r += _image_correction(d, self.eps_r, exact=True) Nr = self.N[i, b0:b1] if Nr.nnz: r += Nr.toarray()[0] return r / self.k
def _cluster_tree(c, leaf: int): """Recursive bisection of the panel centres along the longer side of their bounding box at the median: a permutation making every cluster a contiguous range, and nodes (a, b, lo, hi, left, right).""" perm, nodes = np.arange(len(c)), []
def rec(a, b): idx = perm[a:b] lo, hi = c[idx].min(0), c[idx].max(0) k = len(nodes) nodes.append([a, b, lo, hi, -1, -1]) if b - a > leaf: ax = int(np.argmax(hi - lo)) perm[a:b] = idx[np.argsort(c[idx, ax], kind="stable")] m = a + (b - a) // 2 nodes[k][4], nodes[k][5] = rec(a, m), rec(m, b) return k
rec(0, len(c)) return perm, nodes
def _aca(K, a0, a1, b0, b1, eps, max_rank): """Partial-pivoting adaptive cross approximation of the block (a0:a1, b0:b1) to relative Frobenius accuracy eps: (U, V) with block ~ U V^T, or None when the rank would exceed max_rank.""" m, n = a1 - a0, b1 - b0 U, V, used_r, used_c = [], [], np.zeros(m, bool), np.zeros(n, bool) i, norm2 = 0, 0.0 for _ in range(min(m, n, max_rank)): r = K.row(a0 + i, b0, b1) for u, v in zip(U, V): r -= u[i] * v rm = np.where(used_c, 0.0, np.abs(r)) j = int(np.argmax(rm)) if rm[j] == 0.0: break v = r / r[j] u = K.row(b0 + j, a0, a1) # column j of the block = row j of the symmetric kernel for uu, vv in zip(U, V): u -= vv[j] * uu used_r[i], used_c[j] = True, True nu, nv = float(u @ u), float(v @ v) norm2 += nu * nv + 2 * sum(float(u @ uu) * float(v @ vv) for uu, vv in zip(U, V)) U.append(u) V.append(v) if nu * nv <= eps**2 * norm2: break um = np.where(used_r, 0.0, np.abs(u)) i = int(np.argmax(um)) if um[i] == 0.0: break else: return None return np.stack(U, 1), np.stack(V, 1)
class _HMatrix: """Hierarchical matrix of the panel system: dense blocks for leaf pairs that are not well separated, ACA low-rank blocks for admissible pairs (min diameter <= eta x distance); only the upper block triangle is stored (symmetric)."""
def __init__(self, c, wh, eps_r, leaf=128, eta=2.0, eps=1e-9): self.n = len(c) self.perm, nodes = _cluster_tree(c, leaf) self.K = _Kernel(c, wh, eps_r, self.perm) self.eps = eps plan = []
def leafq(k): return nodes[k][4] < 0
def rec(s, t): a0, a1, lo_s, hi_s, sl, sr = nodes[s] b0, b1, lo_t, hi_t, tl, tr = nodes[t] if s == t: if leafq(s): plan.append(("d", a0, a1, a0, a1)) else: rec(sl, sl), rec(sr, sr), rec(sl, sr) return gap = np.maximum(0.0, np.maximum(lo_s - hi_t, lo_t - hi_s)) diam = min(np.sqrt(((hi_s - lo_s) ** 2).sum()), np.sqrt(((hi_t - lo_t) ** 2).sum())) if diam <= eta * np.sqrt((gap**2).sum()): plan.append(("l", a0, a1, b0, b1)) elif leafq(s) and leafq(t): plan.append(("d", a0, a1, b0, b1)) elif leafq(s): rec(s, tl), rec(s, tr) elif leafq(t): rec(sl, t), rec(sr, t) else: for u in (sl, sr): for v in (tl, tr): rec(u, v)
rec(0, 0) self.dense, self.low = [], []
def build(chunk): out = [] for kind, a0, a1, b0, b1 in chunk: if kind == "l": r = _aca(self.K, a0, a1, b0, b1, eps, max(2, min(a1 - a0, b1 - b0) // 2)) if r is not None: out.append(("l", a0, a1, b0, b1, r)) continue out.append(("d", a0, a1, b0, b1, self.K.block(a0, a1, b0, b1))) return out
for res in _run([partial(build, plan[a:b]) for a, b in _spans(len(plan), 64)]): for kind, a0, a1, b0, b1, M in res: (self.low if kind == "l" else self.dense).append((a0, a1, b0, b1, M)) self.pre = [(a0, a1, cho_factor(D, lower=True)) for a0, a1, b0, _, D in self.dense if a0 == b0] # block Jacobi self.n_threads = max(1, _nthreads())
def nbytes(self): return sum(D.nbytes for *_, D in self.dense) + sum(U.nbytes + V.nbytes for *_, (U, V) in self.low)
def matvec(self, X): def part(dense, low): Y = np.zeros_like(X) for a0, a1, b0, b1, D in dense: Y[a0:a1] += D @ X[b0:b1] if a0 != b0: Y[b0:b1] += D.T @ X[a0:a1] for a0, a1, b0, b1, (U, V) in low: Y[a0:a1] += U @ (V.T @ X[b0:b1]) Y[b0:b1] += V @ (U.T @ X[a0:a1]) return Y
T = self.n_threads if T < 2: return part(self.dense, self.low) return sum(_run([partial(part, self.dense[k::T], self.low[k::T]) for k in range(T)]))
def precondition(self, R): Z = np.empty_like(R) for a0, a1, cf in self.pre: Z[a0:a1] = cho_solve(cf, R[a0:a1], check_finite=False) return Z
def pcg(self, B, tol, maxit): """Conjugate gradients on every right-hand side column at once (independent columns), block-Jacobi preconditioned, until every column's relative residual is below tol. B and the result are in the permuted order.""" X, R = np.zeros_like(B), B.copy() Z = self.precondition(R) P, rz = Z.copy(), (R * Z).sum(0) bn = np.sqrt((B * B).sum(0)) for it in range(maxit): AP = self.matvec(P) alpha = rz / (P * AP).sum(0) X += alpha * P R -= alpha * AP res = (np.sqrt((R * R).sum(0)) / bn).max() if res < tol: return X, it + 1, res Z = self.precondition(R) rz_new = (R * Z).sum(0) P = Z + (rz_new / rz) * P rz = rz_new raise np.linalg.LinAlgError(f"H-matrix PCG did not converge in {maxit} iterations (residual {res:.1e})")
def mom_solve_fast(c, wh, o, n_metals: int, eps_r: float = 11.45, dense_max: int | None = None): """Panel charges Q (n, n_metals) for unit excitation of every conductor, exact near field: dense Cholesky for n <= dense_max panels (`_mom_solve_exact_near`), otherwise the H-matrix / PCG solve of the same system.""" n = len(c) if n <= (DENSE_MAX if dense_max is None else dense_max): return _mom_solve_exact_near(c, wh, o, n_metals, eps_r) H = _HMatrix(c, wh, eps_r, HMAT["leaf"], HMAT["eta"], HMAT["eps"]) B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float)[H.perm] Xp, _, _ = H.pcg(B, HMAT["tol"], HMAT["maxit"]) Q = np.empty_like(Xp) Q[H.perm] = Xp return Q
def _cap_flagship(metals, eps_r, h, max_cells, grade, lmax_mult, merge_grade): c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade) try: Q = mom_solve_fast(c, wh, o, len(metals), eps_r) except np.linalg.LinAlgError: # cut panels of different conductors overlap (lattice coarser than the finger pitch) print("flagship: system not positive definite, majority finest cells", flush=True) c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade, majority=True) Q = mom_solve_fast(c, wh, o, len(metals), eps_r) C = np.stack([Q[o == a].sum(0) for a in range(len(metals))]) return 0.5 * (C + C.T), len(c), h, n_raw
def mom_capacitance_gds_flagship(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 250000, grade: float = 2.0, rich: bool = True, lmax_mult: float = 16.0, merge_grade: float = 1.0): """Flagship prior: strip-merged conductor-anchored mesh at h_f = max(gap / (2 cells_per_gap), size / 8192) and, with rich=True, Richardson extrapolation with the mesh at 2 h_f (same lattice), both solved with `mom_solve_fast`. The resolution is set by cells_per_gap (the fine mesh has 2 cells_per_gap panels across the smallest gap; the coarse one cells_per_gap); max_cells is only a safety cap on the merged panel count (h doubles until it fits). The two solves run concurrently when more than one thread is allowed. Returns (C, total panels, h of the fine mesh, info dict).""" bbox = shapely.union_all(metals).bounds size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) hf = max(gap / (2 * cells_per_gap), size / 8192) if not rich: C, n, h, n_raw = _cap_flagship(metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade) 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} rf, rc = _both(partial(_cap_flagship, metals, eps_r, hf, max_cells, grade, lmax_mult, merge_grade), partial(_cap_flagship, metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade)) for r in (rf, rc): if isinstance(r, np.linalg.LinAlgError): raise r (Cf, nf, h_f, raw_f), (Cc, nc, h_c, raw_c) = rf, rc r = h_c / h_f C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1) info = {"h_target_um": hf, "min_gap_um": gap, "cap_hit": h_f > hf * 1.0001, "raw_cells": raw_f, "coarse_cells": nc, "extrapolated": bool(r >= 1.01)} return C, nf + nc, h_f, info123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256"""GDS conductor geometry: exact polygon metrics, separation spectra and spectral shape descriptors.
Only metal layers are used: (1,0) ground and (1,10) signal conductors. Port stubs (2,0)/(3,0) are ignored."""
from __future__ import annotations
from dataclasses import dataclass, field
import gdstkimport numpy as npimport shapelyfrom scipy import sparsefrom scipy.sparse.linalg import eigshfrom scipy.spatial import cKDTreefrom shapely.geometry import MultiPolygon, Polygon
GROUND_LAYER = (1, 0)SIGNAL_LAYER = (1, 10)BOUNDARY_STEP_UM = 0.25SEP_BINS_UM = np.geomspace(0.5, 2000.0, 41)N_FOURIER = 16MIC_TOL = [0.01] # inscribed-circle tolerance (um); 0.1 for the approximate token variants (PRIOR_SCHEME.md 14.3.1)RASTER_PX = 512N_EIG = 16K_BINS = 48
@dataclassclass Conductors: N: Polygon S: Polygon G: Polygon | MultiPolygon pocket: Polygon | MultiPolygon # etched region inside the chip (contains N and S) gap: Polygon | MultiPolygon # pocket minus signal metal (dielectric surface) chip: Polygon pads: list = field(default_factory=list) # extra 0 V bodies (merged into G)
def metals(self) -> dict: return {"N": self.N, "S": self.S, "G": self.G}
def _valid(geom): g = shapely.make_valid(geom) polys = [p for p in getattr(g, "geoms", [g]) if isinstance(p, (Polygon, MultiPolygon))] return shapely.union_all(polys)
def load_conductors(gds_path) -> Conductors: lib = gdstk.read_gds(str(gds_path)) cell = lib.top_level()[0] to_um = lib.unit / 1e-6 sig = [p for p in cell.polygons if (p.layer, p.datatype) == SIGNAL_LAYER] gnd = [p for p in cell.polygons if (p.layer, p.datatype) == GROUND_LAYER] if len(sig) < 2 or len(gnd) != 1: raise ValueError(f"expected >=2 signal + 1 ground polygons, got {len(sig)} + {len(gnd)}") polys = [_valid(Polygon(p.points * to_um)) for p in sig] if len(polys) == 2: N, S = polys pads = [] else: # multi-terminal (exp12): GDS order is not the net order. S = star at the origin; N = body fed by the # single port stub; the remaining pads are held at 0 V in the solve and are merged into ground. port = shapely.union_all([Polygon(p.points * to_um) for p in cell.polygons if (p.layer, p.datatype) != SIGNAL_LAYER and p.layer != GROUND_LAYER[0]]) s = next((i for i, g in enumerate(polys) if g.contains(shapely.Point(0, 0))), int(np.argmax([g.area for g in polys]))) n = min((i for i in range(len(polys)) if i != s), key=lambda i: polys[i].distance(port)) N, S = polys[n], polys[s] pads = [g for i, g in enumerate(polys) if i not in (n, s)] G0 = _valid(Polygon(gnd[0].points * to_um)) if abs(G0.area - gnd[0].area() * to_um**2) > 1e-6 * G0.area: raise ValueError("ground polygon area changed during repair") chip = shapely.box(*G0.bounds) pocket = chip.difference(G0) G = shapely.union_all([G0, *pads]) if pads else G0 gap = pocket.difference(N).difference(S) for g in pads: gap = gap.difference(g) return Conductors(N, S, G, pocket, gap, chip, pads)
def sample_boundary(geom, step: float = BOUNDARY_STEP_UM) -> np.ndarray: rings = [] for poly in getattr(geom, "geoms", [geom]): rings += [poly.exterior, *poly.interiors] pts = [] for r in rings: n = max(int(np.ceil(r.length / step)), 4) pts.append(shapely.get_coordinates(shapely.line_interpolate_point(r, np.linspace(0, r.length, n, endpoint=False)))) return np.concatenate(pts)
def boundaries(c: Conductors) -> dict[str, np.ndarray]: # ground edge = boundary of the etched pocket g = [sample_boundary(c.pocket)] + [sample_boundary(p) for p in c.pads] return {"N": sample_boundary(c.N), "S": sample_boundary(c.S), "G": np.concatenate(g)}
def shape_metrics(poly) -> dict: hull = poly.convex_hull x0, y0, x1, y1 = poly.bounds cx, cy = poly.centroid.x, poly.centroid.y ixx, iyy, ixy = _second_moments(poly, cx, cy) evals = np.linalg.eigvalsh([[ixx, ixy], [ixy, iyy]]) return { "area": poly.area, "perimeter": poly.length, "convex_area": hull.area, "solidity": poly.area / hull.area, "compactness": 4 * np.pi * poly.area / poly.length**2, "bbox_w": x1 - x0, "bbox_h": y1 - y0, "cx": cx, "cy": cy, "I_major": evals[1], "I_minor": evals[0], "elongation": np.sqrt(evals[1] / max(evals[0], 1e-30)), "inscribed_radius": shapely.maximum_inscribed_circle(poly, MIC_TOL[0]).length if isinstance(poly, Polygon) else np.nan, "n_vertices": int(shapely.get_num_coordinates(poly)), "n_holes": int(sum(len(p.interiors) for p in getattr(poly, "geoms", [poly]))), }
def _second_moments(geom, cx, cy) -> tuple[float, float, float]: ixx = iyy = ixy = 0.0 for poly in getattr(geom, "geoms", [geom]): for k, ring in enumerate([poly.exterior, *poly.interiors]): xy = np.asarray(ring.coords) - (cx, cy) x, y = xy[:-1, 0], xy[:-1, 1] xn, yn = xy[1:, 0], xy[1:, 1] a = x * yn - xn * y sgn = 1.0 if ring.is_ccw == (k == 0) else -1.0 ixx += sgn * np.sum(a * (y**2 + y * yn + yn**2)) / 12 iyy += sgn * np.sum(a * (x**2 + x * xn + xn**2)) / 12 ixy += sgn * np.sum(a * (x * yn + 2 * x * y + 2 * xn * yn + xn * y)) / 24 return abs(ixx), abs(iyy), ixy
def fourier_descriptors(poly, n_samples: int = 512) -> np.ndarray: """|c_k|/|c_1| for k=-N..N of the outer contour (translation/rotation/scale invariant).""" ring = max(getattr(poly, "geoms", [poly]), key=lambda p: p.area).exterior if not ring.is_ccw: ring = shapely.reverse(ring) pts = shapely.get_coordinates(shapely.line_interpolate_point(ring, np.linspace(0, 1, n_samples, endpoint=False), normalized=True)) c = np.fft.fft(pts[:, 0] + 1j * pts[:, 1]) / n_samples k = np.r_[np.arange(-N_FOURIER, 0), np.arange(0, N_FOURIER + 1)] mags = np.abs(c[k]) mags[k == 0] = 0.0 return mags / mags[k == 1][0]
def separation_spectrum(a_pts: np.ndarray, b_pts: np.ndarray) -> tuple[np.ndarray, dict]: d, _ = cKDTree(b_pts).query(a_pts) hist, _ = np.histogram(d, bins=SEP_BINS_UM, weights=np.full(len(d), BOUNDARY_STEP_UM)) dmin = float(d.min()) s = {"dmin": dmin, "P_inv": float(np.sum(BOUNDARY_STEP_UM / np.maximum(d, 0.05)))} for f in (1.05, 1.5, 2.0, 3.0): s[f"L_{f:g}dmin"] = float(np.sum(d <= f * dmin) * BOUNDARY_STEP_UM) for d0 in (5.0, 10.0, 20.0): s[f"L_le{d0:g}um"] = float(np.sum(d <= d0) * BOUNDARY_STEP_UM) return hist, s
def window(c: Conductors) -> tuple[float, float, float]: """Square raster window around the pocket and signal metal: (x0, y0, side) in µm.""" x0, y0, x1, y1 = shapely.union(c.N, c.S).buffer(0).bounds gx0, gy0, gx1, gy1 = c.pocket.bounds cx, cy = (gx0 + gx1) / 2, (gy0 + gy1) / 2 side = 1.05 * max(gx1 - gx0, gy1 - gy0, x1 - x0, y1 - y0) return cx - side / 2, cy - side / 2, side
def raster(c: Conductors, npx: int = RASTER_PX) -> tuple[dict[str, np.ndarray], float, tuple[float, float]]: wx0, wy0, side = window(c) cx, cy = wx0 + side / 2, wy0 + side / 2 px = side / npx xs = cx - side / 2 + (np.arange(npx) + 0.5) * px ys = cy - side / 2 + (np.arange(npx) + 0.5) * px X, Y = np.meshgrid(xs, ys) masks = {} for k, g in c.metals().items(): shapely.prepare(g) masks[k] = shapely.contains_xy(g, X, Y) return masks, px, (cx - side / 2, cy - side / 2)
def radial_power_spectrum(img: np.ndarray, px: float) -> tuple[np.ndarray, np.ndarray]: n = img.shape[0] F = np.fft.fftshift(np.fft.fft2(img - img.mean())) P = np.abs(F) ** 2 / img.size k = np.fft.fftshift(np.fft.fftfreq(n, d=px)) KX, KY = np.meshgrid(k, k) kr = np.hypot(KX, KY).ravel() edges = np.geomspace(1.0 / (n * px), 0.5 / px, K_BINS + 1) idx = np.digitize(kr, edges) - 1 ok = (idx >= 0) & (idx < K_BINS) s = np.bincount(idx[ok], weights=P.ravel()[ok], minlength=K_BINS) cnt = np.bincount(idx[ok], minlength=K_BINS) return np.sqrt(edges[1:] * edges[:-1]), np.where(cnt > 0, s / np.maximum(cnt, 1), np.nan)
def dirichlet_eigenvalues(mask: np.ndarray, px: float, k: int = N_EIG) -> np.ndarray: """Lowest Dirichlet Laplacian eigenvalues of a pixel mask (Shape-DNA), in um^-2.""" idx = -np.ones(mask.shape, dtype=np.int64) ii, jj = np.nonzero(mask) n = len(ii) if n < 4 * k: return np.full(k, np.nan) idx[ii, jj] = np.arange(n) rows, cols = [np.arange(n)], [np.arange(n)] vals = [np.full(n, 4.0)] for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)): ni, nj = ii + di, jj + dj inside = (ni >= 0) & (ni < mask.shape[0]) & (nj >= 0) & (nj < mask.shape[1]) nb = np.full(n, -1) nb[inside] = idx[ni[inside], nj[inside]] ok = nb >= 0 rows.append(np.arange(n)[ok]) cols.append(nb[ok]) vals.append(-np.ones(ok.sum())) L = sparse.csc_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)) ev = eigsh(L, k=k, sigma=0, which="LM", return_eigenvectors=False) return np.sort(ev) / px**2
def geometry_record(gds_path) -> tuple[dict, dict]: return geometry_record_conductors(load_conductors(gds_path))
def geometry_record_conductors(c: Conductors) -> tuple[dict, dict]: """Descriptors of a (N, S, G) conductor triple; for multi-conductor queries N/S are the queried pair, G the rest.""" scalars, arrays = {}, {} for name, g in (("N", c.N), ("S", c.S), ("pocket", c.pocket)): for k, v in shape_metrics(g).items(): scalars[f"{name}_{k}"] = float(v) arrays[f"fourier_{name}"] = fourier_descriptors(g) scalars["gap_area"] = c.gap.area scalars["chip_w"], scalars["chip_h"] = c.chip.bounds[2] - c.chip.bounds[0], c.chip.bounds[3] - c.chip.bounds[1] scalars["G_area"] = c.G.area
b = boundaries(c) for a, t in (("N", "S"), ("S", "N"), ("N", "G"), ("G", "N"), ("S", "G"), ("G", "S")): hist, s = separation_spectrum(b[a], b[t]) arrays[f"sep_{a}{t}"] = hist scalars.update({f"sep_{a}{t}_{k}": v for k, v in s.items()})
masks, px, origin = raster(c) scalars["raster_px_um"] = px metal = (masks["N"] | masks["S"] | masks["G"]).astype(np.float64) k, P = radial_power_spectrum(metal, px) arrays["psd_k"], arrays["psd_metal"] = k, P arrays["psd_NS"] = radial_power_spectrum(masks["N"].astype(float) - masks["S"].astype(float), px)[1] for name in ("N", "S"): arrays[f"eig_{name}"] = dirichlet_eigenvalues(masks[name], px) scalars[f"{name}_raster_area_err"] = float(masks[name].sum() * px**2 / getattr(c, name).area - 1) arrays["sep_bins_um"] = SEP_BINS_UM return scalars, arrays12345"""Universal GDS Embedding framework: GDS -> scene -> scene graph (+ physics-proxy plugins) -> universal vector / GNN.
The recipe is dataset-agnostic; what a user adapts is (1) the layer map / net naming of their GDS, (2) the physics proxyplugin that fits their observable (capacitance, resonance frequency, kappa, ...), and (3) the target adapter."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526"""Physics-agnostic geometry blocks: node (per conductor), edge (per conductor pair) and global features, all inphysical units (log µm, ratios) so that nothing is fitted to a dataset."""
from __future__ import annotations
import hashlibimport osimport picklefrom collections.abc import Mappingfrom pathlib import Path
import numpy as npimport shapelyfrom scipy.special import ellipkfrom scipy.spatial import cKDTree
from .. import geometry as _geometryfrom ..embed.proxy import _nthreadsfrom ..geometry import fourier_descriptors, sample_boundary, shape_metricsfrom .scene import Scene
GRAN_R_UM = np.geomspace(0.25, 100.0, 16)SEP_EDGES_UM = np.geomspace(0.5, 2000.0, 11)MOMENTS = (0.5, 1.0, 2.0)STEP_UM = 0.25
def _log(x): return float(np.log(max(float(x), 1e-9)))
def region(scene: Scene, i: int): """The shape that carries conductor i's edge: the etched pocket for the ground net, the metal otherwise.""" return scene.pocket if scene.conductors[i].role == "ground" else scene.conductors[i].geom
def granulometry(g) -> np.ndarray: a0 = g.area return np.array([g.buffer(-r, quad_segs=4).area / a0 if a0 > 0 else 0.0 for r in GRAN_R_UM])
def node_features(scene: Scene, i: int) -> dict: g = region(scene, i) m = shape_metrics(g) f = {"role_ground": float(scene.conductors[i].role == "ground"), "log_area": _log(m["area"]), "log_perimeter": _log(m["perimeter"]), "compactness": m["compactness"], "solidity": m["solidity"], "log_min_halfwidth": _log(m["inscribed_radius"]), "log_aspect": abs(_log(m["bbox_w"]) - _log(m["bbox_h"])), "log_elongation": _log(m["elongation"]), "log_Imajor_over_A2": _log(m["I_major"] / max(m["area"], 1e-9) ** 2), "n_holes": float(m["n_holes"]), "log_width": _log(2 * m["area"] / m["perimeter"])} for j, v in enumerate(fourier_descriptors(g)): f[f"fourier_{j:02d}"] = float(np.log1p(50 * v)) for j, v in enumerate(granulometry(g)): f[f"gran_{j:02d}"] = float(v) return f
def _kratio(m): m = np.clip(m, 1e-12, 1 - 1e-12) return ellipk(1 - m) / ellipk(m)
TOKEN_VARIANTS = {"exact": None, "td16": dict(d_far=100.0, k=16), "td64": dict(d_far=100.0, k=64), "tc600": dict(crop=600.0)}TOKEN_VARIANT: dict = {"name": "exact"} # PRIOR_SCHEME.md 14.3; "exact" = the published tokens
def set_token_variant(name: str) -> None: from ..geometry import MIC_TOL
assert name in TOKEN_VARIANTS, name TOKEN_VARIANT["name"] = name MIC_TOL[0] = 0.01 if name == "exact" else 0.1
def _block_distances(pts: np.ndarray, tree) -> tuple: """Distances from the samples of a to b (k-d tree) for the active token variant, with weights (multiples of the sample step): the samples are grouped into consecutive blocks of k; a block whose first sample is farther than d_far from b is represented by that sample with weight = block size, the other blocks sample by sample. crop: blocks whose first sample is farther than the crop distance are dropped (their representatives kept if every block is dropped).""" v = TOKEN_VARIANTS[TOKEN_VARIANT["name"]] k = v.get("k", 64) r = v.get("crop", v.get("d_far")) rep = np.arange(0, len(pts), k) d_rep, _ = tree.query(pts[rep], workers=_nthreads()) size = np.diff(np.r_[rep, len(pts)]) far = d_rep > r near_pts = np.repeat(~far, size) d_near, _ = tree.query(pts[near_pts], workers=_nthreads()) if "crop" in v: if not near_pts.any(): return d_rep, size.astype(float) return d_near, np.ones(len(d_near)) return np.r_[d_rep[far], d_near], np.r_[size[far].astype(float), np.ones(len(d_near))]
def edge_features(scene: Scene, i: int, j: int, bpts: dict, widths: dict) -> dict: """Symmetric pair features: separation spectrum (both directions averaged), minimum gap, coupling moments and the coplanar-strip conformal-map coupling (Gevorgian modulus; the ground net is treated as infinitely wide).""" f = {"is_ground_pair": float("ground" in (scene.conductors[i].role, scene.conductors[j].role))} hist = np.zeros(len(SEP_EDGES_UM) - 1) mom = np.zeros(len(MOMENTS)) cps = 0.0 dmin = np.inf for a, b in ((i, j), (j, i)): if TOKEN_VARIANT["name"] != "exact": # approximate tokens (PRIOR_SCHEME.md 14.3) d, wq = _block_distances(bpts[a], cKDTree(bpts[b])) dmin = min(dmin, d.min()) hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=STEP_UM * wq)[0] dd = np.maximum(d, 0.05) mom += 0.5 * np.array([np.sum(STEP_UM * wq * dd ** (-p)) for p in MOMENTS]) w1, w2 = widths[a], widths[b] if np.isinf(w1) or np.isinf(w2): wf = w2 if np.isinf(w1) else w1 mm = dd / (dd + wf) else: mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) cps += 0.5 * np.sum(STEP_UM * wq * _kratio(mm)) continue d, _ = cKDTree(bpts[b]).query(bpts[a], workers=_nthreads()) dmin = min(dmin, d.min()) hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0] dd = np.maximum(d, 0.05) mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS]) w1, w2 = widths[a], widths[b] if np.isinf(w1) or np.isinf(w2): wf = w2 if np.isinf(w1) else w1 mm = dd / (dd + wf) else: mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) cps += 0.5 * np.sum(STEP_UM * _kratio(mm)) f["log_dmin"] = _log(dmin) for k, v in enumerate(hist): f[f"sep_{k:02d}"] = float(np.log1p(v)) for p, v in zip(MOMENTS, mom): f[f"mom_{p:g}"] = _log(v) f["log_cps"] = _log(cps) f["_cps"] = cps # raw, used for shielding shares return f
TREE_LEAFSIZE = 32 # nearest distances do not depend on the leaf size (cKDTree's own distance arithmetic); 32 is fastestNN_KERNEL: dict = {"on": os.environ.get("TLSQ_NN_KERNEL", "1") == "1"} # numba exact NN (nnk.py), probe-verified
def _tree(P: np.ndarray): """Nearest-sample structure of one conductor: the numba kernel when its probe reproduces cKDTree here, else cKDTree.""" if NN_KERNEL["on"]: try: from . import nnk except ImportError: nnk = None if nnk is not None and nnk.available(): return nnk.Tree(P) return cKDTree(P, leafsize=TREE_LEAFSIZE)
def _dist(tree, X: np.ndarray) -> np.ndarray: return tree.query(X)[0] if isinstance(tree, cKDTree) else tree.dist(X)
_EDGES_HI = np.r_[SEP_EDGES_UM[:-1], np.nextafter(SEP_EDGES_UM[-1], np.inf)] # np.histogram: last bin closed_CHUNK = 1 << 20 # distances per task (rows x samples)
def _dir_stats(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple: """edge_features' per-direction statistics of the samples X of one conductor against each conductor in bs (all signal, or the ground alone): minimum distance, histogram counts, the three moment sums and the conformal sum. The same element-wise operations and pairwise row sums as edge_features (bit-identical).""" nb = len(bs) D = np.empty((nb, len(X))) for r, b in enumerate(bs): D[r] = _dist(trees[b], X) dmin = D.min(1) k = np.searchsorted(_EDGES_HI, D, side="right") k += (12 * np.arange(nb))[:, None] cnt = np.bincount(k.ravel(), minlength=12 * nb).reshape(nb, 12)[:, 1:11] del k dd = np.maximum(D, 0.05, out=D) mom = np.stack([np.sum(STEP_UM * dd ** (-p), axis=1) for p in MOMENTS], 1) w2 = np.array([widths[b] for b in bs])[:, None] if np.isinf(w1): mm = dd / (dd + w2) elif np.isinf(w2).any(): mm = dd / (dd + w1) else: mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) cps = np.sum(STEP_UM * _kratio(mm), axis=1) return dmin, cnt, mom, cps
# "bitwise" (default; training / reproduction): every feature bit-identical to the published code. "numex" (numerically exact;# inference): node features and signal-signal directions computed once per class of translated copies (same shape to 1e-6# um, same offset) and shared; values differ from bitwise in the last bits only (agents/embedspeed/RESULTS.md).EMBED_MODE: dict = {"mode": os.environ.get("TLSQ_EMBED_MODE", "bitwise")}FAR_DECIMATION: dict = {"k": 0, "d_far": 100.0}# Edge storage: False (default; training) = a dict per pair; True (inference) = EdgeTable, one float64 array per key.EDGE_TABLE: dict = {"on": os.environ.get("TLSQ_EDGE_TABLE", "0") == "1"}
class EdgeTable(Mapping): """Read-only complete-graph edges: pairs i < j in combinations order, one float64 column per key (same values as the dict per pair; `npcols` are returned as numpy float64, the others as Python floats). table[(i, j)] builds that pair's dict on request; matrix(keys) gives the (P, len(keys)) array without building any dict."""
def __init__(self, n: int, cols: dict, npcols=()): self.n, self.cols, self.npcols = n, cols, frozenset(npcols)
def _r(self, p) -> int: i, j = int(p[0]), int(p[1]) if not 0 <= i < j < self.n: raise KeyError(p) return i * (2 * self.n - i - 1) // 2 + j - i - 1
def __getitem__(self, p) -> dict: r = self._r(p) return {k: (v[r] if k in self.npcols else float(v[r])) for k, v in self.cols.items()}
def __iter__(self): return ((i, j) for i in range(self.n) for j in range(i + 1, self.n))
def __len__(self) -> int: return self.n * (self.n - 1) // 2
def matrix(self, keys, dtype=np.float32) -> np.ndarray: if not len(self): return np.zeros((0, len(keys)), dtype) return np.stack([self.cols[k] for k in keys], 1).astype(dtype)
def with_cols(self, new: dict, drop=(), npcols=()) -> "EdgeTable": cols = {k: v for k, v in self.cols.items() if k not in drop} return EdgeTable(self.n, {**cols, **new}, (self.npcols | frozenset(npcols)) - frozenset(drop))
def edge_matrix(edges, keys, n: int, dtype=np.float32) -> np.ndarray: """(P, len(keys)) array of the edge features (pairs i < j): the table's columns, or the per-pair dicts as before.""" if isinstance(edges, EdgeTable): return edges.matrix(keys, dtype) pairs = [(i, j) for i in range(n) for j in range(i + 1, n)] return np.array([[edges[p][k] for k in keys] for p in pairs], dtype).reshape(len(pairs), len(keys)) # approximation arm (agents/embedspeed/PROTOCOL.md Part A); k = 0: exact
def _dir_stats_far(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple: """Approximate _dir_stats (block decimation of PRIOR_SCHEME.md 14.3.1): blocks of k consecutive samples of a whose first sample is farther than d_far from b are represented by that sample with weight k (the last block by its size). Distances per row (far representatives, then the near samples), statistics for the whole chunk at once (weighted sums).""" k, r = FAR_DECIMATION["k"], FAR_DECIMATION["d_far"] rep = np.arange(0, len(X), k) size = np.diff(np.r_[rep, len(X)]) nb = len(bs) Xr = X[rep] ds, ws, rows = [], [], [] for row, b in enumerate(bs): d_rep = _dist(trees[b], Xr) far = d_rep > r if far.all(): d, wq = d_rep, size.astype(float) else: near = np.repeat(~far, size) d = np.r_[d_rep[far], _dist(trees[b], X[near])] wq = np.r_[size[far].astype(float), np.ones(int(near.sum()))] ds.append(d) ws.append(wq) rows.append(np.full(len(d), row)) d, wq, rid = np.concatenate(ds), np.concatenate(ws), np.concatenate(rows) starts = np.r_[0, np.cumsum([len(x) for x in ds])[:-1]] dmin = np.minimum.reduceat(d, starts) kb = np.searchsorted(_EDGES_HI, d, side="right") cnt = np.rint(np.bincount(rid * 12 + kb, weights=wq, minlength=12 * nb)).astype(np.int64).reshape(nb, 12)[:, 1:11] dd = np.maximum(d, 0.05) mom = np.stack([np.bincount(rid, weights=STEP_UM * wq * dd ** (-p), minlength=nb) for p in MOMENTS], 1) w2 = np.array([widths[b] for b in bs])[rid] if np.isinf(w1): mm = dd / (dd + w2) elif np.isinf(w2).any(): mm = dd / (dd + w1) else: mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2)) cps = np.bincount(rid, weights=STEP_UM * wq * _kratio(mm), minlength=nb) return dmin, cnt, mom, cps
def _pmap(fn, items: list, threads: int) -> list: if threads < 2 or len(items) < 2: return [fn(x) for x in items] from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(threads, thread_name_prefix="tlsq-edges") as ex: return list(ex.map(fn, items))
# Optional persistent cache (exact): per-body node features and per-direction pair statistics, keyed by the body's region# (WKB) and role, under a key of this code, the parameters and the machine / library versions (a value is reused only where# this machine would recompute it bit for bit). Off unless TLSQ_EMBED_CACHE (or EMBED_CACHE["dir"]) names a directory.EMBED_CACHE: dict = {"dir": os.environ.get("TLSQ_EMBED_CACHE") or None}
def _code_key() -> str: import platform
import scipy
h = hashlib.sha256() for f in (__file__, _geometry.__file__): h.update(Path(f).read_bytes()) h.update(repr((platform.machine(), platform.system(), np.__version__, scipy.__version__, shapely.__version__, STEP_UM, SEP_EDGES_UM.tolist(), MOMENTS, TREE_LEAFSIZE, TOKEN_VARIANT["name"], EMBED_MODE["mode"], NN_KERNEL["on"])).encode()) return h.hexdigest()[:24]
def body_keys(scene: Scene) -> list: return [hashlib.sha256(c.role.encode() + shapely.to_wkb(region(scene, i))).hexdigest()[:32] for i, c in enumerate(scene.conductors)]
class _Cache: def __init__(self, root): self.d = Path(root) / _code_key() for sub in ("dir", "node"): (self.d / sub).mkdir(parents=True, exist_ok=True)
def _put(self, path: Path, write): tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") with open(tmp, "wb") as fh: write(fh) os.replace(tmp, path)
def nodes(self, keys: list) -> dict: out = {} for i, k in enumerate(keys): p = self.d / "node" / f"{k}.pkl" if p.exists(): out[i] = pickle.loads(p.read_bytes()) return out
def put_node(self, key: str, f: dict): self._put(self.d / "node" / f"{key}.pkl", lambda fh: pickle.dump(f, fh, protocol=5))
def rows(self, ka: str): p = self.d / "dir" / f"{ka}.npz" if not p.exists(): return None z = np.load(p) return {str(k): r for r, k in enumerate(z["keys"])}, z["dmin"], z["cnt"], z["mom"], z["cps"]
def put_rows(self, ka: str, keys: list, dmin, cnt, mom, cps): old = self.rows(ka) if old is not None: idx, *arr = old ks = set(keys) extra = [r for k, r in idx.items() if k not in ks] keys = list(keys) + [k for k, r in idx.items() if k not in ks] dmin, cnt, mom, cps = (np.concatenate([x, y[extra]]) for x, y in zip((dmin, cnt, mom, cps), arr)) self._put(self.d / "dir" / f"{ka}.npz", lambda fh: np.savez(fh, keys=np.array(keys), dmin=dmin, cnt=cnt, mom=mom, cps=cps))
def trim(self): """Size bound (TLSQ_EMBED_CACHE_MB): the least recently written entries are removed down to 80 % of the bound.""" mb = os.environ.get("TLSQ_EMBED_CACHE_MB") if not mb: return lim = float(mb) * 2**20 files = [e for sub in ("dir", "node") for e in os.scandir(self.d / sub) if e.is_file()] tot = sum(e.stat().st_size for e in files) if tot <= lim: return for e in sorted(files, key=lambda e: e.stat().st_mtime): if tot <= 0.8 * lim: break try: tot -= e.stat().st_size os.remove(e.path) except OSError: pass
def _cache(): return _Cache(EMBED_CACHE["dir"]) if EMBED_CACHE["dir"] else None
def shape_classes(scene: Scene, bpts: dict | None = None) -> tuple: """Translation classes of the signal bodies (numex mode): class id per conductor (-1 = ground, its own class) from the coordinates relative to the bounding-box corner rounded to 1e-6 um and the ring structure, and, with bpts, from the boundary samples relative to that corner rounded to 1e-9 um (a translated copy can get one sample more or fewer when a ring length is a multiple of the step); integer origins (1e-6 um).""" ids, cid, org = {}, np.full(scene.n, -1), np.zeros((scene.n, 2), np.int64) for i, c in enumerate(scene.conductors): if c.role == "ground": continue g = region(scene, i) o = np.array(g.bounds[:2]) rings = [len(r.coords) for q in getattr(g, "geoms", [g]) for r in (q.exterior, *q.interiors)] h = hashlib.sha1(repr((c.role, g.geom_type, rings)).encode() + (np.round(shapely.get_coordinates(g) - o, 6) + 0.0).tobytes()) if bpts is not None: h.update((np.round(bpts[i] - o, 9) + 0.0).tobytes()) cid[i] = ids.setdefault(h.hexdigest(), len(ids)) org[i] = np.rint(o * 1e6).astype(np.int64) return cid, org
def node_features_all(scene: Scene, keys: list | None = None) -> list: """[node_features(scene, i) for every conductor], threads over the conductors, reusing the persistent cache (numex: once per translation class).""" c = _cache() keys = keys if keys is not None or c is None else body_keys(scene) hit = c.nodes(keys) if c else {} miss = [i for i in range(scene.n) if i not in hit] rep = {} if EMBED_MODE["mode"] == "numex": cid = shape_classes(scene)[0] first = {} rep = {i: first.setdefault(cid[i], i) for i in miss if cid[i] >= 0} rep = {i: r for i, r in rep.items() if r != i} new = dict(zip([i for i in miss if i not in rep], _pmap(lambda i: node_features(scene, i), [i for i in miss if i not in rep], _nthreads()))) new.update({i: dict(new[r]) for i, r in rep.items()}) if c: for i, f in new.items(): c.put_node(keys[i], f) c.trim() return [hit[i] if i in hit else new[i] for i in range(scene.n)]
def edge_features_all(scene: Scene, bpts: dict, widths: dict, keys: list | None = None) -> dict: """{(i, j): edge_features(scene, i, j, bpts, widths)} for every pair i < j, bit-identical, batched: one k-d tree per conductor, every direction a -> b as rows of one distance array per (a, chunk of b), threads over the chunks (the queries and ufuncs release the GIL); directions found in the persistent cache are not recomputed.""" n = scene.n pairs = [(i, j) for i in range(n) for j in range(i + 1, n)] if TOKEN_VARIANT["name"] != "exact" or n < 2: return {(i, j): edge_features(scene, i, j, bpts, widths) for i, j in pairs} th = _nthreads() DM, CP = np.empty((n, n)), np.empty((n, n)) CN, MO = np.empty((n, n, 10), np.int64), np.empty((n, n, len(MOMENTS))) c = _cache() if not FAR_DECIMATION["k"] else None if c and keys is None: keys = body_keys(scene) todo = {a: [b for b in range(n) if b != a] for a in range(n)} if c: for a in range(n): got = c.rows(keys[a]) if got is None: continue idx, dm, cn, mo, cp = got have = [b for b in todo[a] if keys[b] in idx] r = [idx[keys[b]] for b in have] DM[a, have], CN[a, have], MO[a, have], CP[a, have] = dm[r], cn[r], mo[r], cp[r] todo[a] = [b for b in todo[a] if keys[b] not in idx] share = None if EMBED_MODE["mode"] == "numex": cid, org = shape_classes(scene, bpts) A, B = np.nonzero((cid[:, None] >= 0) & (cid[None, :] >= 0) & ~np.eye(n, dtype=bool)) K = np.c_[cid[A], cid[B], org[B] - org[A]] _, first, inv = np.unique(K, axis=0, return_index=True, return_inverse=True) R = first[inv.ravel()] share = (A, B, A[R], B[R]) drop = np.zeros((n, n), bool) drop[A[R != np.arange(len(A))], B[R != np.arange(len(A))]] = True todo = {a: [b for b in bs if not drop[a, b]] for a, bs in todo.items()} tasks = [] for a, bs in todo.items(): sig = [b for b in bs if not np.isinf(widths[b])] tasks += [(a, [b]) for b in bs if np.isinf(widths[b])] step = max(1, _CHUNK // len(bpts[a])) tasks += [(a, sig[k:k + step]) for k in range(0, len(sig), step)] tasks.sort(key=lambda t: -len(t[1]) * len(bpts[t[0]])) need = sorted({b for _, bs in tasks for b in bs}) trees = dict(zip(need, _pmap(lambda i: _tree(bpts[i]), need, th)))
def run(t): a, bs = t f = _dir_stats_far if FAR_DECIMATION["k"] else _dir_stats DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs] = f(bpts[a], trees, bs, widths[a], widths)
_pmap(run, tasks, th) if share is not None: A, B, RA, RB = share DM[A, B], CN[A, B], MO[A, B], CP[A, B] = DM[RA, RB], CN[RA, RB], MO[RA, RB], CP[RA, RB] if c: for a in {t[0] for t in tasks}: bs = [b for b in range(n) if b != a] c.put_rows(keys[a], [keys[b] for b in bs], DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs]) c.trim() return _assemble(scene, DM, CN, MO, CP)
def _assemble(scene: Scene, DM, CN, MO, CP) -> dict: """Pair dicts from the per-direction statistics, in edge_features' operation order and key order.""" n = scene.n I, J = np.triu_indices(n, 1) dmin = np.minimum(DM[I, J], DM[J, I]) hist = 0.5 * (STEP_UM * CN[I, J]) + 0.5 * (STEP_UM * CN[J, I]) mom = 0.5 * MO[I, J] + 0.5 * MO[J, I] cps = 0.5 * CP[I, J] + 0.5 * CP[J, I] gnd = np.array([c.role == "ground" for c in scene.conductors]) cols = {"is_ground_pair": (gnd[I] | gnd[J]).astype(float), "log_dmin": np.log(np.maximum(dmin, 1e-9))} sep = np.log1p(hist) for k in range(sep.shape[1]): cols[f"sep_{k:02d}"] = sep[:, k] lm = np.log(np.maximum(mom, 1e-9)) for k, p in enumerate(MOMENTS): cols[f"mom_{p:g}"] = lm[:, k] cols["log_cps"] = np.log(np.maximum(cps, 1e-9)) if EDGE_TABLE["on"]: return EdgeTable(n, {**cols, "_cps": cps}, ("_cps",)) keys = list(cols) rows = zip(*[cols[k].tolist() for k in keys], list(cps)) return {(i, j): {**dict(zip(keys, r[:-1])), "_cps": r[-1]} for i, j, r in zip(I.tolist(), J.tolist(), rows)}
def global_features(scene: Scene) -> dict: st = scene.stack n_sig = sum(c.role == "signal" for c in scene.conductors) return {"n_metal_layers": float(st["n_metal_layers"]), "log_metal_t": _log(st["metal_thickness_um"]), "log_substrate_t": _log(st["substrate_thickness_um"]), "eps_eff": (st["substrate_eps_r"] + 1) / 2, "n_signal": float(n_sig), "log_chip_area": _log(scene.chip.area), "log_pocket_area": _log(scene.pocket.area)}
def boundary_points(scene: Scene) -> tuple[dict, dict]: def one(i): g = region(scene, i) return sample_boundary(g, STEP_UM), np.inf if scene.conductors[i].role == "ground" else 2 * g.area / g.length
out = _pmap(one, list(range(scene.n)), _nthreads()) return {i: p for i, (p, _) in enumerate(out)}, {i: w for i, (_, w) in enumerate(out)}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Scene graph (nodes = conductors, edges = all conductor pairs) and its permutation-invariant pooled vector."""
from __future__ import annotations
import numpy as np
from .blocks import EdgeTable, _cache, body_keys, boundary_points, edge_features_all, global_features, node_features_allfrom .proxies import Proxyfrom .scene import Scene
def scene_graph(scene: Scene, proxy: Proxy | None = None) -> dict: keys = body_keys(scene) if _cache() else None bpts, widths = boundary_points(scene) nodes = node_features_all(scene, keys) edges = edge_features_all(scene, bpts, widths, keys) # shielding: share of each endpoint's total geometric coupling carried by this edge table = isinstance(edges, EdgeTable) if table: edges = _shares_table(scene.n, edges) if proxy is not None: edges = {p: edges[p] for p in edges} tot = None if table else np.zeros(scene.n) for (i, j), f in (edges.items() if tot is not None else ()): tot[i] += f["_cps"] tot[j] += f["_cps"] for (i, j), f in (edges.items() if tot is not None else ()): si, sj = f["_cps"] / max(tot[i], 1e-12), f["_cps"] / max(tot[j], 1e-12) f["share_mean"], f["share_absdiff"] = 0.5 * (si + sj), abs(si - sj) g = {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges} if proxy is not None: px = proxy.compute(scene, edges) for i, v in px["node"].items(): nodes[i].update({f"proxy_{k}": x for k, x in v.items()}) for e, v in px["edge"].items(): edges[e].update({f"proxy_{k}": x for k, x in v.items()}) g["global"].update({f"proxy_{k}": x for k, x in px["global"].items()}) if "matrix" in px: g["proxy_matrix"] = px["matrix"] for f in (edges.values() if tot is not None else ()): f.pop("_cps") return g
def _shares_table(n: int, E: EdgeTable) -> EdgeTable: """The shares of scene_graph on an EdgeTable: the same additions in the same order (np.add.at is sequential).""" I, J = np.triu_indices(n, 1) cps = E.cols["_cps"] tot = np.zeros(n) np.add.at(tot, np.c_[I, J].ravel(), np.repeat(cps, 2)) si, sj = cps / np.maximum(tot[I], 1e-12), cps / np.maximum(tot[J], 1e-12) return E.with_cols({"share_mean": 0.5 * (si + sj), "share_absdiff": np.abs(si - sj)}, drop=("_cps",), npcols=("share_mean", "share_absdiff"))
def pooled_vector(g: dict) -> dict: """Fixed-length universal vector for any number of conductors: global block, the ground node, sum/mean/max over signal nodes, and sum/mean/max over signal-signal and signal-ground edges.""" out = {f"global.{k}": v for k, v in g["global"].items()} roles = ["ground" if n["role_ground"] else "signal" for n in g["nodes"]] keys = [k for k in g["nodes"][0] if k != "role_ground"] gi = roles.index("ground") out.update({f"ground.{k}": g["nodes"][gi][k] for k in keys}) S = np.array([[n[k] for k in keys] for n, r in zip(g["nodes"], roles) if r == "signal"]) for agg, fn in (("mean", np.mean), ("max", np.max), ("min", np.min)): out.update({f"signal.{agg}.{k}": v for k, v in zip(keys, fn(S, 0))}) ekeys = [k for k in next(iter(g["edges"].values())) if k != "is_ground_pair"] for typ, flag in (("ss", 0.0), ("sg", 1.0)): E = np.array([[f[k] for k in ekeys] for f in g["edges"].values() if f["is_ground_pair"] == flag]) if len(E) == 0: E = np.full((1, len(ekeys)), np.nan) for agg, fn in (("mean", np.nanmean), ("max", np.nanmax), ("min", np.nanmin)): out.update({f"edge_{typ}.{agg}.{k}": v for k, v in zip(ekeys, fn(E, 0))}) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""Local, window-invariant context tokens (PRIOR_SCHEME.md 14.5 E4; replace the chip / pocket areas): for every signalconductor and radius R, the fractions of its surrounding annulus (conductor buffered by R, minus the conductor) that areground metal, other-conductor metal and etched chip; the rest of the annulus lies outside the chip (no metal). Pairtokens = mean over the pair's signal ends (a ground pair: its signal end). Identical copy: tlsq_infer/localtok.py."""
from __future__ import annotations
import numpy as npimport shapely
from ..geometry import sample_boundaryfrom ..embed.proxy import _nthreadsfrom .blocks import MOMENTS, SEP_EDGES_UM, STEP_UM, EdgeTable, _dist, _kratio, _pmap, _tree
RADII_UM = (50.0, 150.0, 400.0)KEYS = [f"lt_{k}{int(r)}" for r in RADII_UM for k in ("g", "o", "e")]
def node_tokens(scene) -> np.ndarray: """(n, len(KEYS)) per conductor (ground row = NaN).""" conds = scene.conductors n = len(conds) G = next(c.geom for c in conds if c.role == "ground") sig = [k for k, c in enumerate(conds) if c.role != "ground"] tree = shapely.STRtree([conds[k].geom for k in sig]) out = np.full((n, len(KEYS)), np.nan)
def one(k): g = conds[k].geom vals = [] for R in RADII_UM: ring = g.buffer(R, quad_segs=4).difference(g) A = ring.area box = ring.bounds gm = shapely.intersection(shapely.clip_by_rect(G, *box), ring).area near = [sig[i] for i in tree.query(ring, predicate="intersects") if sig[i] != k] om = shapely.intersection(shapely.union_all([conds[i].geom for i in near]), ring).area if near else 0.0 inchip = shapely.intersection(scene.chip, ring).area vals += [gm / A, om / A, max(inchip - gm - om, 0.0) / A] return vals
for k, vals in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely releases the GIL out[k] = vals return out
LG_R_UM = 100.0TOK = ["log_dmin"] + [f"sep_{k:02d}" for k in range(10)] + ["mom_0.5", "mom_1", "mom_2", "log_cps"]LG_KEYS = [f"lg_{k}" for k in TOK]
def ground_tokens(scene) -> np.ndarray: """(n, len(LG_KEYS)) per signal conductor: the ground-pair tokens of blocks.edge_features (separation spectrum, minimum gap, coupling moments, coplanar-strip coupling) from the ground-edge samples within LG_R_UM of the conductor only (fixed radius: independent of the ground window).""" conds = scene.conductors out = np.full((len(conds), len(LG_KEYS)), np.nan)
def one(k): g = conds[k].geom b = g.bounds P = shapely.clip_by_rect(scene.pocket, b[0] - LG_R_UM, b[1] - LG_R_UM, b[2] + LG_R_UM, b[3] + LG_R_UM) pj = sample_boundary(g, STEP_UM) pg = sample_boundary(P, STEP_UM) if not P.is_empty else np.zeros((0, 2)) if len(pg): pg = pg[_dist(_tree(pj), pg) < LG_R_UM] # drops the clip-box edges (>= LG_R_UM away) and the far ground if not len(pg): return None wj = 2 * g.area / g.length hist = np.zeros(len(SEP_EDGES_UM) - 1) mom = np.zeros(len(MOMENTS)) cps, dmin = 0.0, np.inf for a_, b_ in ((pj, pg), (pg, pj)): d = _dist(_tree(b_), a_) dmin = min(dmin, d.min()) hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0] dd = np.maximum(d, 0.05) mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS]) cps += 0.5 * np.sum(STEP_UM * _kratio(dd / (dd + wj))) return [np.log(max(dmin, 1e-9))] + list(np.log1p(hist)) + [np.log(max(v, 1e-9)) for v in mom] + [np.log(max(cps, 1e-9))]
sig = [k for k, c in enumerate(conds) if c.role != "ground"] for k, v in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely and the k-d tree queries release the GIL if v is not None: out[k] = v return out
def add_tokens(scene, row: dict) -> dict: """Row (scene graph dict) with the KEYS added to every edge (shallow copy).""" return add_from_tokens(row, node_tokens(scene), ground_tokens(scene), [c.role != "ground" for c in scene.conductors])
def add_from_tokens(row: dict, T: np.ndarray, Lg: np.ndarray, sig) -> dict: """Edges + KEYS (mean over the signal ends) + LG_KEYS (ground pairs: the fixed-radius tokens of the signal end; other pairs: their own tokens, unchanged).""" sig = np.asarray(sig) if isinstance(row["edges"], EdgeTable): return {**row, "edges": _add_table(row["edges"], T, Lg, sig)} edges = {} for (i, j), f in row["edges"].items(): ends = [e for e in (i, j) if sig[e]] new = {k: float(x) for k, x in zip(KEYS, T[ends].mean(0))} if len(ends) == 1 and np.all(np.isfinite(Lg[ends[0]])): new.update({k: float(x) for k, x in zip(LG_KEYS, Lg[ends[0]])}) else: new.update({f"lg_{k}": float(f[k]) for k in TOK}) edges[(i, j)] = {**f, **new} return {**row, "edges": edges}
def _add_table(E: EdgeTable, T: np.ndarray, Lg: np.ndarray, sig: np.ndarray) -> EdgeTable: """add_from_tokens on an EdgeTable, per column with the same arithmetic: the mean over two signal ends is (a + b) / 2 (numpy's mean of two rows), over one end the row itself.""" I, J = np.triu_indices(E.n, 1) sI, sJ = sig[I], sig[J] both, oi, oj = sI & sJ, sI & ~sJ, ~sI & sJ M = np.full((len(I), len(KEYS)), np.nan) M[both] = (T[I[both]] + T[J[both]]) / 2 M[oi], M[oj] = T[I[oi]], T[J[oj]] end = np.where(oi, I, J) use = (oi | oj) & np.isfinite(Lg[end]).all(1) new = {k: M[:, c] for c, k in enumerate(KEYS)} for c, k in enumerate(TOK): new[f"lg_{k}"] = np.where(use, Lg[end][:, c], E.cols[k]) return E.with_cols(new)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341"""Exact nearest-sample distances (agents/embedspeed, CONSULT_HPC 3a): a 2-D k-d tree in numba whose squared distance isthe platform's cKDTree arithmetic (probed at first use against scipy: fma(dy, dy, dx * dx) on the arm64 wheels, plaindx * dx + dy * dy elsewhere), queried in boundary order with a warm-start bound from the previous sample (triangleinequality, inflated), so the minimum over samples, and its sqrt, are the same bits as cKDTree.query. If no variantreproduces cKDTree on the probe, `available()` is False and callers keep cKDTree."""from __future__ import annotations
import osimport threading
import numba as nbimport numpy as npfrom llvmlite import irfrom numba import typesfrom numba.extending import intrinsic
LEAF = 32WARM = 4 # boundary-order neighbours of the previous query's nearest sample evaluated first (an exact upper bound)_STATE: dict = {}
@intrinsicdef _fma(typingctx, a, b, c): sig = types.float64(types.float64, types.float64, types.float64)
def codegen(context, builder, signature, args): d = ir.DoubleType() fn = builder.module.declare_intrinsic("llvm.fma", [d], ir.FunctionType(d, [d, d, d])) return builder.call(fn, args)
return sig, codegen
@nb.njit(cache=True)def _build(P, leaf): """Balanced k-d tree over P (m, 2): permutation, node boxes and ranges; node k has children 2k+1, 2k+2.""" m = P.shape[0] nn = 1 while (m + leaf - 1) // leaf > (nn + 1) // 2: nn = 2 * nn + 1 perm = np.arange(m) lo = np.zeros(nn, np.int64) hi = np.zeros(nn, np.int64) box = np.empty((nn, 4)) lo[0], hi[0] = 0, m for k in range(nn): a, b = lo[k], hi[k] if b > a: x0 = x1 = P[perm[a], 0] y0 = y1 = P[perm[a], 1] for t in range(a + 1, b): x, y = P[perm[t], 0], P[perm[t], 1] x0, x1, y0, y1 = min(x0, x), max(x1, x), min(y0, y), max(y1, y) box[k, 0], box[k, 1], box[k, 2], box[k, 3] = x0, y0, x1, y1 else: box[k, 0] = box[k, 1] = np.inf box[k, 2] = box[k, 3] = -np.inf c = 2 * k + 1 if c < nn: mid = (a + b) // 2 if b - a > 1: d = 0 if box[k, 2] - box[k, 0] >= box[k, 3] - box[k, 1] else 1 sub = perm[a:b].copy() order = np.argsort(P[sub, d], kind="mergesort") perm[a:b] = sub[order] lo[c], hi[c] = a, mid lo[c + 1], hi[c + 1] = mid, b return perm, lo, hi, box
@nb.njit(cache=True, inline="always")def _mind2(box, k, x, y): dx = max(box[k, 0] - x, 0.0, x - box[k, 2]) dy = max(box[k, 1] - y, 0.0, y - box[k, 3]) return dx * dx + dy * dy
@nb.njit(nogil=True, cache=True, inline="always")def _sqd(x, y, P, j, use_fma): dx, dy = x - P[j, 0], y - P[j, 1] return _fma(dy, dy, dx * dx) if use_fma else dx * dx + dy * dy
@nb.njit(nogil=True, cache=True)def _kd(x, y, best, jb, P, perm, lo, hi, box, use_fma, stack): """Exact k-d search below the bound best (a squared distance already attained by sample jb, or inf).""" nn = lo.shape[0] stack[0] = 0 sp = 1 while sp: sp -= 1 k = stack[sp] if lo[k] >= hi[k] or _mind2(box, k, x, y) * (1.0 - 1e-12) > best: continue c = 2 * k + 1 if c >= nn: for t in range(lo[k], hi[k]): j = perm[t] s = _sqd(x, y, P, j, use_fma) if s < best: best, jb = s, j continue d1, d2 = _mind2(box, c, x, y), _mind2(box, c + 1, x, y) if d1 <= d2: stack[sp] = c + 1 stack[sp + 1] = c else: stack[sp] = c stack[sp + 1] = c + 1 sp += 2 return best, jb
@nb.njit(nogil=True, cache=True)def _scan(x, y, best, jb, P, et, ej, a, b, t0, t1, use_fma): """min over the edge-list entries a..b with t in [t0, t1] (t sorted).""" lo_, hi_ = a, b while lo_ < hi_: mid = (lo_ + hi_) // 2 if et[mid] < t0: lo_ = mid + 1 else: hi_ = mid for i in range(lo_, b): if et[i] > t1: break s = _sqd(x, y, P, ej[i], use_fma) if s < best: best, jb = s, ej[i] return best, jb
@nb.njit(nogil=True, cache=True)def _nearest_t(x, y, P, et, ej, a, b, tf, use_fma): """An attained upper bound: the better of the two list entries around t = tf.""" lo_, hi_ = a, b while lo_ < hi_: mid = (lo_ + hi_) // 2 if et[mid] < tf: lo_ = mid + 1 else: hi_ = mid best, jb = np.inf, -1 for i in (lo_ - 1, lo_): if a <= i < b: s = _sqd(x, y, P, ej[i], use_fma) if s < best: best, jb = s, ej[i] return best, jb
@nb.njit(nogil=True, cache=True)def _query(X, P, perm, lo, hi, box, use_fma, warm, H, hv, hx, hy, ux, uy, L, nx, ny, eoff, et, ej, eps, delta): """Distances from every row of X to the nearest sample of P. Far field (H > 0): x outside the hull of P projects to a hull edge or vertex f at distance dH; every sample s satisfies |x - s|^2 >= dH^2 + |f - s|^2 (obtuse angle at f), so once a sample o attains s_o, only samples within rho = sqrt(s_o - dH^2 + slack) of f can be nearer; those lie in the edge's list (samples within delta of it). Otherwise, and whenever rho > delta, the k-d search (warm-started) decides.""" m = X.shape[0] mp = P.shape[0] out = np.empty(m) stack = np.empty(128, np.int64) jp = -1 e = 0 for q in range(m): x, y = X[q, 0], X[q, 1] best = np.inf jb = -1 done = False if H >= 3: reg = -1 vtx = -1 for _ in range(H + 2): t = (x - hx[e]) * ux[e] + (y - hy[e]) * uy[e] if t < 0.0: ep = e - 1 if e > 0 else H - 1 if (x - hx[ep]) * ux[ep] + (y - hy[ep]) * uy[ep] > L[ep]: vtx = e break e = ep continue if t > L[e]: en = e + 1 if e + 1 < H else 0 if (x - hx[en]) * ux[en] + (y - hy[en]) * uy[en] < 0.0: vtx = en break e = en continue if (x - hx[e]) * nx[e] + (y - hy[e]) * ny[e] > 0.0: reg = e break if vtx >= 0: fx, fy = hx[vtx], hy[vtx] dh2 = (x - fx) * (x - fx) + (y - fy) * (y - fy) best = _sqd(x, y, P, hv[vtx], use_fma) jb = hv[vtx] rho2 = best - dh2 + 1e-9 * best + 1e-4 + 4.0 * eps * (np.sqrt(best) + 1.0) if rho2 <= delta * delta: r = np.sqrt(max(rho2, 0.0)) ep = vtx - 1 if vtx > 0 else H - 1 best, jb = _scan(x, y, best, jb, P, et, ej, eoff[vtx], eoff[vtx + 1], -r, r, use_fma) best, jb = _scan(x, y, best, jb, P, et, ej, eoff[ep], eoff[ep + 1], L[ep] - r, L[ep] + r, use_fma) done = True elif reg >= 0: tf = (x - hx[reg]) * ux[reg] + (y - hy[reg]) * uy[reg] pp = (x - hx[reg]) * nx[reg] + (y - hy[reg]) * ny[reg] dh2 = pp * pp best, jb = _nearest_t(x, y, P, et, ej, eoff[reg], eoff[reg + 1], tf, use_fma) if jb >= 0: rho2 = best - dh2 + 1e-9 * best + 1e-4 + 4.0 * eps * (np.sqrt(best) + 1.0) if rho2 <= delta * delta: r = np.sqrt(max(rho2, 0.0)) best, jb = _scan(x, y, best, jb, P, et, ej, eoff[reg], eoff[reg + 1], tf - r, tf + r, use_fma) done = True if not done: if jp >= 0: for j in range(max(0, jp - warm), min(mp, jp + warm + 1)): s = _sqd(x, y, P, j, use_fma) if s < best: best, jb = s, j best, jb = _kd(x, y, best, jb, P, perm, lo, hi, box, use_fma, stack) out[q] = np.sqrt(best) jp = jb return out
@nb.njit(cache=True)def _hull_lists(P, hv, delta): H = hv.shape[0] hx, hy = np.empty(H), np.empty(H) ux, uy, L, nx, ny = np.empty(H), np.empty(H), np.empty(H), np.empty(H), np.empty(H) for i in range(H): hx[i], hy[i] = P[hv[i], 0], P[hv[i], 1] for i in range(H): k = i + 1 if i + 1 < H else 0 dx, dy = hx[k] - hx[i], hy[k] - hy[i] L[i] = np.sqrt(dx * dx + dy * dy) ux[i], uy[i] = dx / L[i], dy / L[i] nx[i], ny[i] = uy[i], -ux[i] # outward for a counter-clockwise hull m = P.shape[0] eps = 0.0 cnt = np.zeros(H + 1, np.int64) db = delta + 0.01 for i in range(H): for j in range(m): ax, ay = P[j, 0] - hx[i], P[j, 1] - hy[i] pp = ax * nx[i] + ay * ny[i] if pp > eps: eps = pp t = ax * ux[i] + ay * uy[i] if -db <= t <= L[i] + db and abs(pp) <= db: cnt[i + 1] += 1 eoff = np.cumsum(cnt) et, ej = np.empty(eoff[H]), np.empty(eoff[H], np.int64) for i in range(H): k = eoff[i] for j in range(m): ax, ay = P[j, 0] - hx[i], P[j, 1] - hy[i] pp = ax * nx[i] + ay * ny[i] t = ax * ux[i] + ay * uy[i] if -db <= t <= L[i] + db and abs(pp) <= db: et[k], ej[k] = t, j k += 1 o = np.argsort(et[eoff[i]:eoff[i + 1]], kind="mergesort") et[eoff[i]:eoff[i + 1]] = et[eoff[i]:eoff[i + 1]][o] ej[eoff[i]:eoff[i + 1]] = ej[eoff[i]:eoff[i + 1]][o] return hx, hy, ux, uy, L, nx, ny, eoff, et, ej, eps
DELTA = 1.0HULL_MAX = 200_000 # targets with more samples (the ground) use the k-d search only_EMPTY = (np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(0), np.zeros(1, np.int64), np.zeros(0), np.zeros(0, np.int64), 0.0)
class Tree: """Drop-in for cKDTree(P).query(X)[0] (distances only)."""
def __init__(self, P: np.ndarray, hull: bool | None = None): self.P = np.ascontiguousarray(P, dtype=np.float64) self.perm, self.lo, self.hi, self.box = _build(self.P, LEAF) self.hv, self.H = np.zeros(0, np.int64), 0 self.hl = _EMPTY if (HULL["on"] if hull is None else hull) and 3 <= len(self.P) <= HULL_MAX: try: from scipy.spatial import ConvexHull hv = ConvexHull(self.P).vertices.astype(np.int64) except Exception: # noqa: BLE001 (degenerate: collinear samples) hv = None if hv is not None and len(hv) >= 3: self.hv, self.H = hv, len(hv) self.hl = _hull_lists(self.P, hv, DELTA)
def dist(self, X: np.ndarray) -> np.ndarray: return _query(np.ascontiguousarray(X, dtype=np.float64), self.P, self.perm, self.lo, self.hi, self.box, _STATE["fma"], WARM, self.H, self.hv, *self.hl, DELTA)
HULL: dict = {"on": os.environ.get("TLSQ_NN_HULL", "1") == "1"} # far-field hull path (exact; off: k-d search only)
def probe(n_targets: int = 40, seed: int = 0) -> dict: """Which arithmetic reproduces this platform's cKDTree bit for bit (random and boundary-like targets, near and far).""" from scipy.spatial import cKDTree
rng = np.random.default_rng(seed) res = {} for name in ("fma", "plain"): bad = tot = 0 for t in range(n_targets): m = int(rng.integers(5, 3000)) if t % 2: th = np.sort(rng.uniform(0, 2 * np.pi, m)) P = np.c_[np.cos(th) * rng.uniform(10, 300), np.sin(th) * rng.uniform(10, 300)] + rng.uniform(-5000, 5000, 2) else: P = rng.uniform(-300, 300, (m, 2)) + rng.uniform(-5000, 5000, 2) X = np.cumsum(rng.normal(0, rng.choice([0.25, 30.0]), (2000, 2)), 0) + P.mean(0) + rng.uniform(-3000, 3000, 2) tr = Tree(P, hull=False) d = _query(np.ascontiguousarray(X), tr.P, tr.perm, tr.lo, tr.hi, tr.box, name == "fma", WARM, 0, tr.hv, *tr.hl, DELTA) ref = cKDTree(P).query(X)[0] bad += int((d != ref).sum()) tot += len(X) res[name] = dict(mismatches=bad, queries=tot) return res
_LOCK = threading.Lock()
def available() -> bool: with _LOCK: return _available()
def _available() -> bool: if "ok" not in _STATE: r = probe() ok = [k for k in ("fma", "plain") if r[k]["mismatches"] == 0] _STATE.update(probe=r, ok=bool(ok), arith=ok[0] if ok else None) _STATE["fma"] = bool(ok) and ok[0] == "fma" return _STATE["ok"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""Physics-proxy plugins. A proxy maps a Scene to extra node / edge / global quantities that are cheap to compute andphysically aligned with the target. Swap the proxy to move the recipe to another observable (e.g. a resonator datasetwould plug in a quasi-TEM transmission-line proxy for f0 and kappa); the rest of the pipeline is unchanged."""
from __future__ import annotations
import numpy as np
from ..embed.proxy import mom_capacitance_gds, mom_capacitance_gds_avg, mom_capacitance_gds_flagship, mom_capacitance_gds_richfrom .scene import Scene
EPS0 = 8.8541878128e-3 # fF/µm
class Proxy: name = "none"
def compute(self, scene: Scene, edges: dict) -> dict: """Return {"node": {i: {...}}, "edge": {(i, j): {...}}, "global": {...}}; `edges` holds the geometry edge features.""" return {"node": {}, "edge": {}, "global": {}}
class NoProxy(Proxy): name = "none"
class ConformalCoupling(Proxy): """Solver-free: per-pair coplanar-strip conformal-map coupling (already a geometry edge feature) turned into a capacitance estimate C_ij ~ eps0 eps_eff * sum L K(k')/K(k), and node totals."""
name = "conformal"
def compute(self, scene, edges): e_eff = (scene.stack["substrate_eps_r"] + 1) / 2 out = {"node": {i: {"log_Cself": -np.inf} for i in range(scene.n)}, "edge": {}, "global": {}} tot = np.zeros(scene.n) for (i, j), f in edges.items(): c = EPS0 * e_eff * f["_cps"] out["edge"][(i, j)] = {"log_C": float(np.log(max(c, 1e-9)))} tot[i] += c tot[j] += c for i in range(scene.n): out["node"][i] = {"log_Cself": float(np.log(max(tot[i], 1e-9)))} return out
class CapacitanceMoM(Proxy): """Thin-film method of moments on the exact polygons (quadtree mesh, whole ground plane): full Maxwell matrix."""
name = "mom"
def __init__(self, max_cells: int = 8000, cells_per_gap: float = 3.0, n_offsets: int = 1, mesh: str = "v2", substrate: str = "slab_open"): self.max_cells, self.cells_per_gap, self.n_offsets, self.mesh = max_cells, cells_per_gap, n_offsets, mesh self.substrate = substrate # MoM Green's function (embed.proxy.SUBSTRATE; PRIOR_SCHEME.md 14.6)
def compute(self, scene, edges): from ..embed.proxy import substrate
with substrate(self.substrate, scene.stack.get("substrate_thickness_um")): return self._compute(scene, edges)
def _compute(self, scene, edges): metals, kw = [c.geom for c in scene.conductors], dict(eps_r=scene.stack["substrate_eps_r"], max_cells=self.max_cells, cells_per_gap=self.cells_per_gap) if self.mesh == "v3-rich": # conductor-anchored mesh, Richardson-extrapolated (gap/3 and gap/6) C, n, hm = mom_capacitance_gds_rich(metals, kw["eps_r"], self.cells_per_gap, self.max_cells, 2 * self.max_cells) elif self.mesh in ("lite", "formula"): # flagship-fast cheap priors (PRIOR_SCHEME.md Part III): micro-MoM at a panel budget / closed form from ..embed.fastprior import formula_prior, micro_mom
if self.mesh == "lite": C, _, info = micro_mom(metals[0], metals[1:], kw["eps_r"], budget=self.max_cells, cells_per_gap=self.cells_per_gap) n, hm = int(sum(info["panels"])), float(min(info["h_um"])) mg = float(info["min_gap_um"]) # the mesh's smallest conductor gap (h = gap / ppg off the floor) else: C, info = formula_prior(metals[0], metals[1:], kw["eps_r"]) n, hm = 0, float(info["min_gap_um"]) elif self.mesh == "flagship": # strip-merged, resolution-controlled Richardson pair, H-matrix solve (PRIOR_SCHEME.md Part II) C, n, hm, _ = mom_capacitance_gds_flagship(metals, kw["eps_r"], self.cells_per_gap, self.max_cells) else: if self.mesh != "v2": kw["mesh"] = self.mesh try: C, n, hm = mom_capacitance_gds_avg(metals, self.n_offsets, **kw) if self.n_offsets > 1 else mom_capacitance_gds(metals, **kw) except np.linalg.LinAlgError: if self.mesh != "v3": raise # v3 single solve: sliver edge panels can make the gap/3 system indefinite (~0.2 % of designs); use gap/6 kw.update(cells_per_gap=2 * self.cells_per_gap, max_cells=2 * self.max_cells) C, n, hm = mom_capacitance_gds(metals, **kw) out = {"node": {i: {"log_Cself": float(np.log(max(C[i, i], 1e-9)))} for i in range(scene.n)}, "edge": {}, "global": {"cells": float(n), "h_min_um": float(hm)}, "matrix": C} if self.mesh != "lite": # every variant records the layout's smallest conductor gap (review W1); lite: the mesh's own from ..embed.fastprior import gap_of mg = float(info["min_gap_um"]) if self.mesh == "formula" else float(gap_of(metals)) out["global"]["min_gap_um"] = mg for (i, j) in edges: out["edge"][(i, j)] = {"log_C": float(np.log(max(-C[i, j], 1e-9)))} return out
PROXIES = {p.name: p for p in (NoProxy, ConformalCoupling, CapacitanceMoM)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Scene: the metal of a layout as a list of conductors (one ground net + any number of signal bodies), plus the stack."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom typing import Callable
import gdstkimport numpy as npimport shapelyfrom shapely.geometry import Polygon
DEFAULT_LAYERS = {"ground": [(1, 0)], "signal": [(1, 10)]}DEFAULT_STACK = {"n_metal_layers": 1, "metal_thickness_um": 0.25, "substrate_thickness_um": 350.0, "substrate_eps_r": 11.45}
@dataclassclass Conductor: name: str role: str # "ground" | "signal" geom: object # shapely (Multi)Polygon, µm
@dataclassclass Scene: conductors: list[Conductor] # index 0 is the ground net chip: Polygon pocket: object # chip minus ground metal: the etched region (its edge is the ground's active edge) stack: dict = field(default_factory=lambda: dict(DEFAULT_STACK)) markers: dict = field(default_factory=dict) # non-metal helper shapes by (layer, datatype), e.g. port stubs; naming only
@property def n(self) -> int: return len(self.conductors)
def names(self) -> list[str]: return [c.name for c in self.conductors]
def _valid(g): g = shapely.make_valid(g) parts = [p for p in getattr(g, "geoms", [g]) if p.geom_type in ("Polygon", "MultiPolygon")] return shapely.union_all(parts)
def scene_from_gds(path, layers: dict = DEFAULT_LAYERS, stack: dict | None = None, namer: Callable[[list, object], list[str]] | None = None) -> Scene: """Read only metal layers. Each signal polygon is one conductor; all ground polygons form one net. `namer(signal_geoms, markers)` returns a name per signal body (dataset convention); default S0, S1, ...""" lib = gdstk.read_gds(str(path)) cell = lib.top_level()[0] u = lib.unit / 1e-6 lay = {k: {tuple(x) for x in v} for k, v in layers.items()} sig, gnd, other = [], [], {} for p in cell.polygons: key = (p.layer, p.datatype) g = Polygon(p.points * u) if key in lay["signal"]: sig.append(g) elif key in lay["ground"]: gnd.append(g) else: other.setdefault(key, []).append(g) G = _valid(shapely.union_all([_valid(g) for g in gnd])) S = [_valid(g) for g in sig] chip = shapely.box(*G.bounds) markers = {k: shapely.union_all(v) for k, v in other.items()} names = namer(S, markers) if namer else [f"S{i}" for i in range(len(S))] conds = [Conductor("G", "ground", G)] + [Conductor(n, "signal", g) for n, g in zip(names, S)] return Scene(conds, chip, chip.difference(G), {**DEFAULT_STACK, **(stack or {})}, markers)
def tlsq_namer(signals: list, markers: dict, n_slots: int = 5) -> list[str]: """This dataset's convention: N = body fed by the north port stub (2,0); S = body fed by the south stub (3,0) if present, else the body containing the origin (star, inner pad); remaining bodies P1, P2, ... ordered by angle.""" north, south = markers.get((2, 0)), markers.get((3, 0)) n = min(range(len(signals)), key=lambda i: signals[i].distance(north)) rest = [i for i in range(len(signals)) if i != n] if south is not None: s = min(rest, key=lambda i: signals[i].distance(south)) else: s = next((i for i in rest if signals[i].contains(shapely.Point(0, 0))), max(rest, key=lambda i: signals[i].area)) names = [""] * len(signals) names[s], names[n] = "S", "N" a0 = np.degrees(np.arctan2(signals[n].centroid.y, signals[n].centroid.x)) for i in rest: if i != s: a = np.degrees(np.arctan2(signals[i].centroid.y, signals[i].centroid.x)) names[i] = f"P{int(round(((a - a0) % 360) / (360 / n_slots))) % n_slots}" return names123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167"""Sign-in, daily limits and the layout-size limit of the public demo (handoff/squadds_integration/PLAN_PUBLIC_SPACE.md, amendment2026-11-14). Served requests only: in-process calls (request None: tests, preload) are not limited.
- Anonymous visitors run the bundled examples only (matched by the file's sha256). Their own GDS needs Hugging Face sign-in.- Signed in = a browser session through Hugging Face OAuth, or an API call with Client(..., oauth_token=<HF token>).- Each signed-in user gets TLSQ_DAILY_PREDICTIONS (10) predictions of their own layouts per UTC day. A repeat answered from the response cache and the bundled examples do not count.- Safety limit per client address: TLSQ_IP_DAILY (50) computed predictions per UTC day, examples included.- Layouts with MAX_NETS (70) or more conductors, ground included, are refused before any solve.Usernames and addresses are held only as keyed hashes (usage.keyed), in memory, and the counters are cleared at the end of the UTC day."""
from __future__ import annotations
import datetime as dtimport hashlibimport htmlimport osimport threadingimport timefrom dataclasses import dataclassfrom pathlib import Path
from tlsq_infer.layout import LayoutError
from .usage import keyed, today
LOCAL_GUIDE = os.environ.get("TLSQ_LOCAL_GUIDE", "https://lfl-lab.github.io/SQuADDS/source/ml_local.html")DAILY = int(os.environ.get("TLSQ_DAILY_PREDICTIONS", 10))IP_DAILY = int(os.environ.get("TLSQ_IP_DAILY", 50))MAX_NETS = 70HEADS = {"auth": "Sign in to use your own layout", "quota": "Daily limit reached", "ip": "Daily limit reached", "size": "Layout too large for the demo"}
class LimitReached(LayoutError): """A limit of the demo (reason: auth, quota, ip, size). str() carries the guide's URL for API users; limit_html links it."""
def __init__(self, reason: str, text: str): self.reason, self.text, self.head = reason, text, HEADS[reason] super().__init__(f"{text} On your own computer there are no limits: {LOCAL_GUIDE}")
@property def limit_html(self) -> str: return (f"{html.escape(self.text)} <a href='{LOCAL_GUIDE}' target='_blank' rel='noopener'>Run the models on your own " "computer</a> to avoid these limits.")
@dataclassclass Who: user: str | None = None # keyed hash of the Hugging Face username ip: str | None = None # keyed hash of the client address served: bool = False # False for in-process calls
_TOKENS: dict = {}_LOCK = threading.Lock()
def _token_user(token: str) -> str | None: """A gradio_client call with Client(..., oauth_token=HF token) (Gradio injects it as gr.OAuthToken): whoami, cached ten minutes by the token's sha256.""" k = hashlib.sha256(token.encode()).hexdigest() with _LOCK: hit = _TOKENS.get(k) if hit and time.monotonic() - hit[1] < 600: return hit[0] try: from huggingface_hub import whoami
user = keyed("user", whoami(token=token)["name"]) except Exception: # noqa: BLE001 user = None with _LOCK: if len(_TOKENS) > 10_000: _TOKENS.clear() _TOKENS[k] = (user, time.monotonic()) return user
def who(profile=None, request=None, token=None) -> Who: """profile: gr.OAuthProfile of a signed-in browser session; token: gr.OAuthToken (an API call's oauth_token); request: gr.Request.""" if request is None: return Who() h = getattr(request, "headers", None) or {} fwd = h.get("x-forwarded-for") or "" ip = fwd.split(",")[0].strip() or getattr(getattr(request, "client", None), "host", None) or "?" user = keyed("user", profile.username) if profile is not None and getattr(profile, "username", None) else None if user is None and getattr(token, "token", None): user = _token_user(token.token) return Who(user=user, ip=keyed("ip", ip), served=True)
_EXAMPLES: set = set()
def register_examples(paths) -> None: _EXAMPLES.update(hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths)
def is_example(path) -> bool: try: return hashlib.sha256(Path(path).read_bytes()).hexdigest() in _EXAMPLES except OSError: return False
def _reset_in() -> str: now = dt.datetime.now(dt.timezone.utc) s = int((dt.datetime.combine(now.date() + dt.timedelta(days=1), dt.time(), dt.timezone.utc) - now).total_seconds()) return f"{s // 3600} h {s % 3600 // 60} min"
def check_file(path, w: Who) -> bool: """True when the file is the user's own layout (not a bundled example); anonymous served calls get examples only.""" own = not is_example(path) if w.served and own and w.user is None: raise LimitReached("auth", "To run your own layout, sign in with Hugging Face using the button at the top. The examples " "run without sign-in.") return own
def check_size(n_conductors: int) -> None: n = int(n_conductors) + 1 if n >= MAX_NETS: raise LimitReached("size", f"This layout has {n} conductors, ground included. The demo takes layouts with fewer than " f"{MAX_NETS}.")
class Quota: def __init__(self): self.lock, self.day, self.users, self.ips = threading.Lock(), None, {}, {}
def _roll(self) -> None: d = today() if d != self.day: self.day, self.users, self.ips = d, {}, {}
def check(self, w: Who, own: bool) -> None: if not w.served: return with self.lock: self._roll() if own and self.users.get(w.user, 0) >= DAILY: raise LimitReached("quota", f"You have used all {DAILY} of today's predictions for your own layouts. The count " f"resets at 00:00 UTC, in {_reset_in()}. The examples, and repeats of a result you " "already have, do not count.") if self.ips.get(w.ip, 0) >= IP_DAILY: raise LimitReached("ip", f"Your network has made {IP_DAILY} predictions today, the most we allow. The count " f"resets at 00:00 UTC, in {_reset_in()}.")
def charge(self, w: Who, own: bool) -> None: if not w.served: return with self.lock: self._roll() if own and w.user: self.users[w.user] = self.users.get(w.user, 0) + 1 self.ips[w.ip] = self.ips.get(w.ip, 0) + 1
def used(self, w: Who) -> int: with self.lock: self._roll() return self.users.get(w.user, 0)
QUOTA = Quota()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536"""Registry-driven GNN prediction for the Space (deploy/registry.yaml: gnn_hub, gnn_models).
predict_gnn(prepared, name) runs the frozen Predictor (geomgnn.infer, FINALIZATION_V1 checkpoints) on the scene built from atlsq_infer PreparedLayout. The steps after the scene are those of infer.Predictor.from_gds, statement for statement;deploy/tests/test_gnn_space.py checks the result against the frozen stage's from_gds on the raw TRAIN GDS files.Entries with `learned_prior` (the fast tier) replace the two field solves by the learned prior surrogate(geomgnn.learned_prior = scripts/learnedprior/lp_bench.py Learned.from_gds); the networks are the same frozen weights."""
from __future__ import annotations
import contextlibimport hashlibimport jsonimport osimport threadingimport timeimport warningsfrom pathlib import Path
import numpy as npimport shapely
from . import __version__from . import infer as Ifrom ._tlsq.embed import fastprior, proxyfrom ._tlsq.uge.graph import scene_graphfrom ._tlsq.uge.scene import DEFAULT_STACK, Conductor, Scenefrom ._tlsq.uge import blocks as _blocks
# Inference default: the numerically exact embedding (translated copies shared; last-bit differences only, agents/embedspeed);# TLSQ_EMBED_MODE=bitwise restores the bit-identical training features._blocks.EMBED_MODE["mode"] = os.environ.get("TLSQ_EMBED_MODE", "numex")_blocks.EDGE_TABLE["on"] = os.environ.get("TLSQ_EDGE_TABLE", "1") == "1" # array edge table (bitwise values; dicts on request)
lt = I.ltEPS_TRAIN, T_TRAIN_UM = 11.45, 350.0# Other substrate stacks (agents/v4stack, author decision 2026-11-03): the physics prior is solved at the requested (eps_r, thickness)# and the frozen networks correct it; the geometric embedding and the global inputs stay at the training stack (Si 11.45, 350 um).# Tested on the 15 held-out DoE designs: Si at 10-1000 um, and eps_r 3.8-24 at 350 um. Learned-prior entries (the Fast tier) cannot# solve a prior: off the stack they keep the (1 + eps_r) / (1 + 11.45) rescaling of their training-stack prediction, with a warning.TESTED_THICKNESS_UM = (10.0, 1000.0)TESTED_EPS_R = (3.8, 24.0)CALIBRATED_ROUTE = "calibrated: physics prior solved at the requested stack, networks and embedding at the training stack"CALIBRATED_CAVEAT = ( "calibrated substrate route: the physics prior is solved at your stack; the networks were trained on Si (eps_r 11.45), 350 um " "only and correct it unchanged. A bounded-error route, not training-stack accuracy: on 15 held-out DoE designs (paper model) " "the mutual entries were 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF) on every tested stack, against 0.23 % (0.080 / " "0.111 fF) on the training stack; self terms 0.96-1.22 % (MAE 0.48-0.79, RMSE 0.52-0.86 fF) at 10-50 um Si and 0.89 % " "(0.92 / 1.07 fF) at 1000 um, against 0.24 % (0.18 / 0.22 fF)")TESTED_RANGE = "Si at 10-1000 µm, or eps_r 3.8-24 at 350 µm"CALIBRATED_SCORE = ("On 15 held-out designs the mutual entries were within 0.21-1.02 % (MAE 0.07-0.33 fF, RMSE 0.09-0.45 fF), against " "0.23 % (MAE 0.080 fF, RMSE 0.111 fF) on the training stack. The self terms were within 1.22 % (MAE up to 0.92 fF, " "RMSE up to 1.07 fF).")FAST_ROUTE = "fast: eps-rescaled training-stack prediction; thickness not modelled"FAST_WARNING = ("QCap-Fast does not solve the prior at your stack. It rescales its 350 µm silicon answer by (1 + eps_r) / (1 + 11.45) and " "ignores thickness. Off the stack we measured a median error of 6.4 % (MAE 1.7 fF, RMSE 2.4 fF), and 13 % (3.4 / 4.7 fF) " "across Si thicknesses of 10-1000 µm. Use QCap for other substrates. It solves the prior at your eps_r and " "thickness and gets 0.48 % (0.13 / 0.18 fF) on the same solves.")
def on_training_stack(eps_r: float, thickness_um: float) -> bool: return abs(float(eps_r) - EPS_TRAIN) <= 1e-9 and abs(float(thickness_um) - T_TRAIN_UM) <= 1e-9
def tested_stack(eps_r: float, thickness_um: float) -> bool: """The (eps_r, thickness) combinations the calibrated route was scored on: Si (11.45) at 10-1000 um, or eps_r 3.8-24 at 350 um.""" e, t = float(eps_r), float(thickness_um) si = abs(e - EPS_TRAIN) <= 1e-9 and TESTED_THICKNESS_UM[0] <= t <= TESTED_THICKNESS_UM[1] return si or (abs(t - T_TRAIN_UM) <= 1e-9 and TESTED_EPS_R[0] <= e <= TESTED_EPS_R[1])
def substrate_route(eps_r: float, thickness_um: float, solves_prior: bool = True) -> tuple[dict, list]: """(substrate record, warnings) of a request. solves_prior=False: a learned-prior entry (the Fast tier), eps-rescaled off the stack.""" e, t = float(eps_r), float(thickness_um) if not (np.isfinite(e) and e >= 1.0): raise ValueError(f"substrate eps_r must be a finite number >= 1 (got {eps_r!r})") if not (np.isfinite(t) and t > 0): raise ValueError(f"substrate thickness must be a finite number > 0 um (got {thickness_um!r})") train = {"eps_r": EPS_TRAIN, "thickness_um": T_TRAIN_UM} rec = {"eps_r": e, "thickness_um": t, "training_stack": train, "embedding_stack": dict(train), "tested": True} if on_training_stack(e, t): rec.update(route="training stack", prior_solved_at=dict(train) if solves_prior else None, eps_rescale_factor=1.0) return rec, [] if not solves_prior: rec.update(route=FAST_ROUTE, prior_solved_at=None, eps_rescale_factor=(1.0 + e) / (1.0 + EPS_TRAIN), tested=False, caveat="eps rescaling of the training-stack prediction, thickness not modelled; on 285 off-stack Q3D solves of 15 " "held-out designs 6.36 % (MAE 1.74 fF, RMSE 2.39 fF): 13.1 % (3.43 / 4.67 fF) across Si thickness 10-1000 um, " "1.44 % (0.51 / 0.73 fF) across eps_r 3.8-24 at 350 um, against 1.29 % (0.48 / 0.71 fF) on the training stack") return rec, [FAST_WARNING] rec.update(route=CALIBRATED_ROUTE, prior_solved_at={"eps_r": e, "thickness_um": t}, eps_rescale_factor=None, tested=tested_stack(e, t), caveat=CALIBRATED_CAVEAT) w = [] if not rec["tested"]: w.append(f"substrate eps_r {e:g}, {t:g} um is outside the tested range of the calibrated route (Si eps_r 11.45 at " f"{TESTED_THICKNESS_UM[0]:g}-{TESTED_THICKNESS_UM[1]:g} um, or eps_r {TESTED_EPS_R[0]:g}-{TESTED_EPS_R[1]:g} at " f"{T_TRAIN_UM:g} um): untested, its error is unknown") return rec, w
def substrate_line(res: dict) -> str: """One Markdown line of a result's substrate route for the Space reports.""" sub = res.get("substrate_route") or {} head = f"Substrate: {res.get('substrate')} (eps_r {res['eps_r']:g}), {res['thickness_um']:g} µm, " r = sub.get("route", "training stack") if r == "training stack": return head + "the training stack" if r == FAST_ROUTE: return head + f"eps-rescaled training-stack prediction (factor (1+eps_r)/(1+11.45) = {sub['eps_rescale_factor']:.4f}), thickness not modelled" return head + "physics prior solved at your stack, networks and embedding at the training stack (calibrated route" + ( "" if sub.get("tested") else ", untested combination") + ")"
PRIOR_IMPLS = ("frozen", "cpu_fast")_HMAT0 = dict(proxy.HMAT)_STATE = {"prior_impl": "frozen", "patches": [], "mode": None, "stack": None}_CACHE: dict = {}
def gnn_names(reg) -> list[str]: return [k for k, v in (reg.data.get("gnn_models") or {}).items() if v.get("status", "available") == "available"]
def set_prior_impl(impl: str) -> None: """frozen: the solver as frozen. cpu_fast: scripts/geomfast/fastmom.py (vectorised H-matrix kernel) with ACA eps 1e-6 and PCG tol 1e-8 (agents/geomfast/FASTPRIOR_STATUS.md); process-wide.""" if impl not in PRIOR_IMPLS: raise ValueError(f"prior_impl {impl!r} not in {PRIOR_IMPLS}") if impl == _STATE["prior_impl"]: return from . import fastmom if impl == "cpu_fast": fastmom.install() proxy.HMAT.update(eps=1e-6, tol=1e-8) else: fastmom.uninstall() proxy.HMAT.clear() proxy.HMAT.update(_HMAT0) _STATE["prior_impl"] = impl
VALUE_PRESERVING = ("rejtail_fv",) # bit-identical priorsVALUE_CHANGING = ("priorv2m_sf", "priorv2m", "priorv2") # change the prior: need prior.value_changing_approved in the registry entry# priorv2.installed() arguments of each value-changing patch: v2m_sf = the corrected prior with substrate far field (default since# 2026-10-20); v2m = the corrected prior with the half-space far field (before 2026-10-20; reproduction); v2 = version 2 (no margin# widening), the prior of the paper's "retrained, version 2" ablation (paper Space only)V2_KWARGS = {"priorv2m_sf": dict(policy="fc", dip=True, margin=True), "priorv2m": dict(policy="fc", dip=True, margin=True), "priorv2": dict(policy="fc", dip=True, margin=False)}# far-pair form on top of the v2 pieces: geomgnn.farfield = scripts/farfield/farfield.py verbatim, arm b of agents/farfield (slab dipole# for signal far pairs in different ground pockets, half-space dipole inside a pocket); adopted by the user 2026-10-20FAR_ARM = {"priorv2m_sf": "b"}# TLSQ_FAR_FIELD=halfspace: serve priorv2m wherever priorv2m_sf is listed (the previous corrected prior, process-wide; reproduction)FAR_FIELD_ENV = "TLSQ_FAR_FIELD"PRIOR_PATCHES = VALUE_PRESERVING + VALUE_CHANGING
def resolve_patches(patches) -> list: """The registry patches with the TLSQ_FAR_FIELD override applied ('halfspace': priorv2m_sf -> priorv2m).""" v = os.environ.get(FAR_FIELD_ENV, "").strip().lower() if v not in ("", "substrate", "halfspace"): raise ValueError(f"{FAR_FIELD_ENV}={v!r}: use 'substrate' (default) or 'halfspace'") return sorted("priorv2m" if (p == "priorv2m_sf" and v == "halfspace") else p for p in (patches or []))
SPEED_MODES = ("exact", "exact_compiled", "certified") # geomgnn.fastprior_pkg modes (agents/fastprior_pkg/RESULTS.md)
def speed_mode(pr: dict): """Solver mode of the prior: TLSQ_GNN_PRIOR_MODE (opt-in override, e.g. 'certified' or 'frozen') else registry prior.mode; None / 'frozen' = the vendor solver as frozen (no fastprior_pkg).""" m = os.environ.get("TLSQ_GNN_PRIOR_MODE") or pr.get("mode") if m in (None, "", "frozen"): return None if m not in SPEED_MODES: raise ValueError(f"prior mode {m!r} not in {SPEED_MODES} (or 'frozen')") return m
def _v2m_value_patch(F, P, FL, patch="priorv2m"): """fastprior_pkg value hook: prior v2m (geomgnn.priorv2 installed(policy='fc', dip=True, margin=True)) on top of the solver components (patch="priorv2": version 2, margin=False); returns the undo callable.""" from . import priorv2 assert priorv2.F is F and priorv2.P is P, "priorv2 and fastprior_pkg must patch the same vendor modules" return _install_v2(priorv2, F, P, patch)
def _install_v2(priorv2, F, P, patch): """priorv2.installed(**V2_KWARGS[patch]) and, for priorv2m_sf, the far-pair arm on top (geomgnn.farfield); returns the undo.""" ctx = priorv2.installed(**V2_KWARGS[patch]) ctx.__enter__() undo_far = None if patch in FAR_ARM: from . import farfield try: undo_far = farfield.install(FAR_ARM[patch], F, P, priorv2) except BaseException: ctx.__exit__(None, None, None) raise
def undo(): if undo_far is not None: undo_far() ctx.__exit__(None, None, None) return undo
def _teardown() -> None: from . import rejtail_fv if _STATE.get("mode"): from . import fastprior_pkg fastprior_pkg.uninstall() # also undoes its value patch elif set(V2_KWARGS) & set(_STATE["patches"]): _STATE.pop("v2undo")() rejtail_fv.uninstall() _STATE.update(patches=[], mode=None, stack=None)
def set_prior_stack(pr: dict, threads: int = 2) -> None: """Process-wide prior stack of a registry prior: patches (rejtail_fv | priorv2m) and the solver mode (fastprior_pkg). rejtail_fv: geomgnn.rejtail_fv (value-preserving rejection-tail fix; fastprior_pkg's fv replaces it, so not with a mode). priorv2m: prior v2m (agents/priorv2/FINALIZATION_V2.json): priorv2.installed(policy='fc', dip=True, margin=True), as fastprior_pkg's value_patch when a mode is set; it replaces _window_solve itself, so never with rejtail_fv. mode: fastprior_pkg.install(mode, cpus=threads, target='geomgnn', value_patch=v2m) + warmup() (numba compile).""" patches = resolve_patches(pr.get("patches")) mode = speed_mode(pr) bad = set(patches) - set(PRIOR_PATCHES) if bad: raise ValueError(f"unknown prior patches {bad}; known: {PRIOR_PATCHES}") v2 = [p for p in patches if p in V2_KWARGS] if v2 and "rejtail_fv" in patches: raise ValueError("priorv2m already contains the rejection-tail handling; do not combine it with rejtail_fv") if len(v2) > 1: raise ValueError(f"one prior version per stack, got {v2}") if mode and "rejtail_fv" in patches: raise ValueError("fastprior_pkg contains fv; list rejtail_fv only without a prior mode") unapproved = [p for p in patches if p in VALUE_CHANGING and not pr.get("value_changing_approved")] if unapproved: raise ValueError(f"value-changing prior patches {unapproved} need prior.value_changing_approved in the registry") key = (tuple(patches), mode, int(threads)) if key == _STATE.get("stack"): return _teardown() if mode: from . import fastprior_pkg as fp fp.install(mode=mode, cpus=int(threads), workers=os.environ.get("TLSQ_PRIOR_WORKERS"), target="geomgnn", blas_threads=int(threads), value_patch=(lambda F, P, FL: _v2m_value_patch(F, P, FL, v2[0])) if v2 else None, warm=False) if mode in ("exact_compiled", "certified"): _STATE["warmup_s"] = fp.warmup() else: from . import priorv2, rejtail_fv if "rejtail_fv" in patches: rejtail_fv.install() if v2: _STATE["v2undo"] = _install_v2(priorv2, fastprior, proxy, v2[0]) _STATE.update(patches=patches, mode=mode, stack=key, pr=dict(pr)) if mode: from . import winpool winpool.install() # macOS: the prior's windows on spawned workers (numerically exact; TLSQ_WINDOW_PROCS=0 turns it off)
def _sha(p) -> str: return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def surrogate_file(reg, name: str, model_dir=None) -> Path | None: """The learned prior checkpoint of an entry (bundle copy named in info.json "surrogate", else the registry path).""" lp = reg["gnn_models"][name].get("learned_prior") if not lp: return None md = os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir if md and (Path(md) / name / "info.json").exists(): info = json.loads((Path(md) / name / "info.json").read_text()) if info.get("surrogate"): return Path(md) / name / info["surrogate"] return reg.root / lp["checkpoint"]["path"]
def checkpoint_files(reg, name: str, model_dir=None) -> list[Path]: """Bundle copies (<model_dir>/<name>/info.json) or the registry's source paths; SHA256 checked against the registry.""" m = reg["gnn_models"][name] md = os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir if md and (Path(md) / name / "info.json").exists(): info = json.loads((Path(md) / name / "info.json").read_text()) files = [Path(md) / name / f for f in info["files"]] else: files = [reg.root / c["path"] for c in m["checkpoints"]] return files
def available(name: str, reg, model_dir=None) -> bool: s = surrogate_file(reg, name, model_dir) return all(f.exists() for f in checkpoint_files(reg, name, model_dir)) and (s is None or s.exists())
def load(name: str, reg, model_dir=None, threads: int | None = None) -> I.Predictor: m = reg["gnn_models"][name] threads = int(threads or os.environ.get("TLSQ_NUM_THREADS") or 2) key = (str(reg.path), name, str(os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir), threads) if key in _CACHE: _apply_prior(m, threads) return _CACHE[key] files = checkpoint_files(reg, name, model_dir) for f, c in zip(files, m["checkpoints"], strict=True): if _sha(f) != c["sha256"]: raise RuntimeError(f"{name}: {f.name} SHA256 differs from the registry (frozen checkpoint {c['sha256'][:12]})") P = I.Predictor(files, threads=threads) if P.arm != m["arm"]: raise RuntimeError(f"{name}: checkpoints are arm {P.arm!r}, registry says {m['arm']!r}") pr = m.get("prior") lpr = m.get("learned_prior") phys = P.models[0][0].get("schema", {}).get("physics", {}) P.surrogate = None if P.direct: if pr or lpr: raise RuntimeError(f"{name}: direct arm has no prior, registry lists one") elif lpr: if pr or P.fast or [float(x) for x in lpr["ppg"]] != [1.5, 3.0]: raise RuntimeError(f"{name}: a learned prior replaces the 1.5 / 3 ppg field solves of a full_gnn arm only ({P.arm}, {lpr})") sf = surrogate_file(reg, name, model_dir) if _sha(sf) != lpr["checkpoint"]["sha256"]: raise RuntimeError(f"{name}: {sf.name} SHA256 differs from the registry (learned prior {lpr['checkpoint']['sha256'][:12]})") from . import learned_prior model, prep, _ = learned_prior.load(sf) prep.floor_ff = lpr.get("floor_ff") P.surrogate = (model, prep) else: if not pr or abs(float(pr["alpha"]) - float(phys.get("alpha"))) > 0 or (pr["method"] == "local_gap") != (phys.get("prior_method") == "local_gap") \ or [float(x) for x in pr["ppg"]] != ([0.75, 1.5] if P.fast else [1.5, 3.0]): raise RuntimeError(f"{name}: registry prior {pr} does not match the checkpoint physics {phys}") _apply_prior(m, threads) _CACHE[key] = P return P
def _apply_prior(m: dict, threads: int = 2) -> None: """Process-wide prior settings of a gnn_models entry (on every load: entries may differ, the patches are global).""" pr = m.get("prior") if pr: set_prior_impl(pr.get("prior_impl", "frozen")) set_prior_stack(pr, threads)
STARTUP: dict = {} # preload record (reported by /models)_TLS = threading.local()
def _thread_limits(threads: int) -> None: """numba and OpenMP thread counts are per thread: apply fastprior_pkg's limits once in every thread that predicts (the preload runs in the main thread, requests in the server's worker threads).""" if not _STATE.get("mode") or getattr(_TLS, "key", None) == (_STATE["stack"], threads): return from . import fastprior_pkg fastprior_pkg._set_threads(int(threads)) _TLS.key = (_STATE["stack"], threads)
def preload(name: str, reg, example=None) -> dict: """Server start: load the default model (SHA check, prior stack, numba warmup) and, if given, predict one small example so the first user request runs at normal speed. Synchronous (about 20-30 s on the 2-vCPU Space), before the queue opens. The learned-prior entries (no prior stack) are loaded and run on the example too.""" t0 = time.perf_counter() load(name, reg) STARTUP.update(model=name, load_and_warmup_s=time.perf_counter() - t0, numba_warmup_s=_STATE.get("warmup_s"), mode=_STATE.get("mode")) also = [k for k in gnn_names(reg) if k != name and reg["gnn_models"][k].get("learned_prior") and available(k, reg)] if example is not None and Path(example).exists(): from tlsq_infer.layout import prepare t = time.perf_counter() predict_gnn(prepare(str(example)), name, reg) STARTUP["example_s"] = time.perf_counter() - t for k in also: t = time.perf_counter() predict_gnn(prepare(str(example)), k, reg) STARTUP.setdefault("also_s", {})[k] = time.perf_counter() - t else: for k in also: load(k, reg) STARTUP["total_s"] = time.perf_counter() - t0 print("preload " + json.dumps({k: (round(v, 2) if isinstance(v, float) else v) for k, v in STARTUP.items()}), flush=True) return dict(STARTUP)
def scene_from_prepared(lay) -> Scene: """The Scene scene_from_gds builds (ground = net 0, signal bodies in file order, chip = ground bounding box, training stack), from the prepared ground and conductor bodies.""" G = lay.ground chip = shapely.box(*G.bounds) conds = [Conductor("G", "ground", G)] + [Conductor(n, "signal", g) for n, g in zip(lay.names, lay.conductors)] return Scene(conds, chip, chip.difference(G), dict(DEFAULT_STACK), {})
def predict_scene(P: I.Predictor, sc: Scene, alpha=None, local_gap=None, stack=None) -> dict: """infer.Predictor.from_gds after the scene (same statements). stack: (eps_r, thickness_um) the prior is solved at (default the scene's, i.e. the training stack); the embedding always uses the scene's stack.""" eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"]) physics = P.models[0][0].get("schema", {}).get("physics", {}) if alpha is None: alpha = physics.get("alpha") if local_gap is None: local_gap = physics.get("prior_method") == "local_gap" proxy.NUM_THREADS = P.threads if set(V2_KWARGS) & set(_STATE["patches"]): from . import priorv2 priorv2.clear() # its per-window traces would otherwise grow for the life of the server start = time.perf_counter() t1 = time.perf_counter() from . import overlap as OV fut = OV.start(sc, P.threads) if (getattr(P, "surrogate", None) is None and not P.direct and local_gap and OV.enabled(sc, P.threads)) else None row = None if fut else lt.add_tokens(sc, scene_graph(sc)) # overlap: the embedding runs in the worker during the priors t2 = time.perf_counter() priors = {} if getattr(P, "surrogate", None) is not None: from . import learned_prior priors = learned_prior.priors(*P.surrogate, row) elif not P.direct: old = fastprior.ALPHA_GAP_SHARE try: if alpha is not None: fastprior.ALPHA_GAP_SHARE = alpha from . import levelpar lvls = [.75, 1.5] if P.fast else [1.5, 3.] if local_gap and levelpar.enabled(sc, lvls, P.threads): # the levels concurrently (spawned workers, same stack and statements) priors.update(levelpar.solve(sc, lvls, P.threads, alpha, (eps_r, t_um))[0]) lvls = [] for p in lvls: if local_gap: from ._tlsq.embed.fastprior_loc import micro_mom_loc with proxy.substrate("slab_open", t_um), _quiet_mixed_cast(): mat, _, _ = micro_mom_loc(sc.conductors[0].geom, [c.geom for c in sc.conductors[1:]], eps_r=eps_r, ppg=p) priors[p] = -mat else: if stack is not None and not on_training_stack(eps_r, t_um): raise ValueError("the off-stack prior needs the local-gap prior method") priors[p] = -I.CapacitanceMoM(max_cells=10**9, mesh="lite", cells_per_gap=p, substrate="slab_open").compute(sc, list(row["edges"]))["matrix"] finally: fastprior.ALPHA_GAP_SHARE = old t3 = time.perf_counter() extra = {} if fut is not None: row, embed_s = fut.result() extra = dict(overlap=True, geometry_worker=embed_s, geometry_wait_after_prior=time.perf_counter() - t3) t3 = time.perf_counter() C = P.from_features(row, priors) t4 = time.perf_counter() return dict(C=C, names=row["names"], timing=dict(scene=t1 - start, geometry=t2 - t1, prior=t3 - t2, network_and_pack=t4 - t3, total=t4 - start, **extra))
@contextlib.contextmanagerdef _quiet_mixed_cast(): """fastprior_pkg's mixed Cholesky casts the system to float32 first; on some windows the cast overflows and numpy warns 'invalid value / overflow encountered in cast' before the package falls back to the float64 solve (expected; the result is checked by iterative refinement). Silence exactly that warning, from that module, during the prior call only.""" with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="(invalid value|overflow) encountered in cast", category=RuntimeWarning, module=r"geomgnn\.fastprior_pkg") yield
def physical_checks(C: np.ndarray) -> dict: n = len(C) off = C[~np.eye(n, dtype=bool)] sig = C[1:, 1:] return {"symmetric_max_abs": float(np.max(np.abs(C - C.T))), "offdiag_all_negative": bool(np.all(off < 0)), "signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if n > 1 else None}
def physical_banner(res: dict) -> list[str]: """Report lines that put a failed physical check first.""" w = next((w for w in res.get("warnings") or [] if w.startswith("physical check failed")), None) return [f"> **Not a physical matrix.** {w}", ""] if w else []
def physical_warning(chk: dict, C: np.ndarray) -> str | None: """Readable warning when the checks of physical_checks fail (None when the matrix passes).""" bad = [] if not chk["symmetric_max_abs"] <= 1e-6 * max(1.0, float(np.abs(C).max())): bad.append(f"not symmetric (max |C - C^T| {chk['symmetric_max_abs']:.3g} fF)") if not chk["offdiag_all_negative"]: bad.append(f"{int(np.sum(C[~np.eye(len(C), dtype=bool)] >= 0))} off-diagonal entries are not negative") if chk["signal_block_min_eig"] is not None and not chk["signal_block_min_eig"] > 0: bad.append(f"the signal block is not positive definite (smallest eigenvalue {chk['signal_block_min_eig']:.4g} fF)") if not bad: return None return ("physical check failed: " + ", ".join(bad) + ". This matrix is not physical, so do not use it. A model that solves the " "physics, such as QCap, is the safer choice, especially outside the trained component families.")
def predict_gnn(prepared, name: str, reg, substrate="Si (cryogenic, training)", thickness_um: float = 350.0, model_dir=None, threads: int | None = None) -> dict: """Full N x N Maxwell matrix (fF; ground row/column 0, self terms learned) of a prepared layout with a gnn_models entry.""" m = reg["gnn_models"][name] eps, t_um = reg.eps_of(substrate), float(thickness_um) sub, sub_w = substrate_route(eps, t_um, solves_prior=not m.get("learned_prior")) stack = None if on_training_stack(eps, t_um) else (eps, t_um) t = time.perf_counter() P = load(name, reg, model_dir, threads) _thread_limits(P.threads) load_s = time.perf_counter() - t sc = scene_from_prepared(prepared) try: r = predict_scene(P, sc, stack=stack if sub["eps_rescale_factor"] is None else None) except AssertionError as e: raise ValueError(f"{name}: the prior or the features of this layout are not finite (no matrix returned): {e}") from e C = np.asarray(r["C"], float) if stack is not None and sub["eps_rescale_factor"] is not None: C = C * sub["eps_rescale_factor"] chk = physical_checks(C) labels = ["G"] + list(prepared.names) pr = m.get("prior") lpr = m.get("learned_prior") warnings = [w for w in prepared.warnings if "beyond the validated range" not in w] if m.get("warning"): warnings.insert(0, m["warning"]) pw = physical_warning(chk, C) if pw: warnings.insert(0, pw) warnings += sub_w tm = r["timing"] return {"names": labels, "matrix_fF": C.tolist(), "units": "fF", "convention": "Maxwell matrix: diagonal = self (learned), off-diagonal = -mutual; row/column 0 = ground", "self_capacitance": "predicted by the network (learned positive row-sum closure; trained). The ground self term is " "trained at low weight and depends on the chip boundary: indicative only", "model": name, "model_title": m.get("title"), "recipe": "GNN", "arm": m["arm"], "role": m.get("role"), "ensemble": m.get("ensemble"), "weights_sha256": [c["sha256"] for c in m["checkpoints"]], "prior": ({**pr, "prior_impl": _STATE["prior_impl"], "patches": _STATE.get("patches", []), "mode": _STATE.get("mode") or "frozen", "numba_warmup_s": _STATE.get("warmup_s")} if pr else None), "learned_prior": ({"name": lpr["name"], "sha256": lpr["checkpoint"]["sha256"], "ppg": lpr["ppg"]} if lpr else None), "package_version": f"geomgnn {__version__}", "registry_version": reg["version"], "substrate": substrate if not isinstance(substrate, (int, float)) else f"custom eps={eps:g}", "eps_r": eps, "thickness_um": t_um, "substrate_route": sub, "training_stack": {"eps_r": EPS_TRAIN, "thickness_um": T_TRAIN_UM}, "timing_s": {"load_s": load_s, "geometry_s": tm["geometry"], "prior_s": tm["prior"], "network_s": tm["network_and_pack"], "total_s": tm["total"], "threads": P.threads}, "accuracy": m.get("accuracy") or {}, "checks": chk, "trust": None, "expected_error": {}, "warnings": warnings, "stored": False}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651"""Gradio front end of the flagship Space (deploy/GNN_SPACE.md "Flagship Space"; registry flagship_hub, flagship_tiers): three models inone selector (QCap default, QCap-Lite, QCap-Fast), served through geomgnn.flagship (= the paper Space's code path). Endpoints and argumentorder as the GNN Space:
/models () -> served models with their reference numbers /inspect (gds file) -> layer table, layer plot /prepare (gds, layers table, crop, margin_gaps, margin_um, select) -> preview, warnings, summary, simplified GDS /predict (gds, layers table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, model) -> matrix, CSV, JSON, report /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, model, ground_pieces "") -> result dict; model = QCap (default) | QCap-Lite | QCap-Fast (any case, "-" or "_"); ground_pieces = e.g. "1,4" when ground and conductors share one layer (default "": detected automatically, see result warnings / layout info)
Every endpoint and the UI share the demo's limits (geomgnn.access): anonymous visitors run the bundled examples only, a signed-in user(Hugging Face OAuth, or Client(..., oauth_token=<HF token>) on gradio_client calls) gets 10 predictions of their own layouts per UTC day, layouts need fewer than70 conductors with the ground. Aggregate daily counts only (geomgnn.usage)."""
from __future__ import annotations
import functoolsimport htmlimport jsonimport threadingimport timefrom pathlib import Path
from tlsq_infer import __version__ as TLSQ_VERSIONimport gradio as grfrom tlsq_infer.app_ui import CUSTOM, HEAVY, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fnfrom tlsq_infer.app_v2 import PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fnfrom tlsq_infer.layout import INK, UNMODELLED_COLOR, WINDOW_COLOR, LayoutError, preparefrom tlsq_infer.predict import matrix_csvfrom tlsq_infer.registry import load_registry
from . import __version__from . import access as ACfrom . import api as Afrom . import bundlefrom . import ground_ui as GUfrom . import flagship as FSfrom . import ui as UIfrom . import usage as U
bundle.install()ORDER = ["accurate", "balanced", "fast"]MIN_THICKNESS_UM = 1.0SI = "Si (cryogenic, training)"READY = threading.Event() # cleared by the Space entry while the tiers load in the background; every predict waits for itREADY.set()
def served(reg=None) -> list[str]: ks = FS.served(reg or load_registry()) return sorted(ks, key=lambda k: ORDER.index(k) if k in ORDER else len(ORDER))
def names(reg) -> list[str]: """The served models' names (QCap, QCap-Lite, QCap-Fast), default first.""" return [FS.name(reg, k) for k in served(reg)]
def resolve(reg, model) -> str: """Tier key of a model name (QCap / QCap-Lite / QCap-Fast, any case; empty = the default).""" if not str(model or "").strip(): return reg["flagship_hub"]["default_arm"] k = FS.key(reg, model) if k not in served(reg): raise ValueError(f"Model {model!r} is not available here. Choose one of {', '.join(names(reg))}.") return k
def tiers_md(reg) -> str: """The tier accordion: one row per served tier with its one fresh check (B5) against the physics alone; the full tables are on the model card.""" rows = [f"| {UI.md(t['title'].split(':')[0])} | {UI.md(t['title'].split(':', 1)[-1].strip())} | " f"{UI.pct(t['b5']) if t.get('b5') else 'n/a'} | {UI.pct(t['b5_physics']) if t.get('b5_physics') else 'n/a'} |" for t in (FS.tiers(reg)[k] for k in served(reg))] sid = reg["flagship_hub"]["space"] return "\n".join(["| model | method | error on 39 new layouts | physics alone |", "|---|---|---|---|", *rows, "", f"We trained these networks on all {int(reg['flagship_hub']['training_layouts']):,} Q3D layouts of the training " "stack, so their one held-out check is 39 layouts of a generated family with 3-4 conductors, none of them seen in " "training. The error is the median relative error over the mutual entries against Q3D, averaged over the layouts. " f"The [model card](https://huggingface.co/spaces/{sid}/blob/main/README.md) has the in-sample fits, the held-out " "numbers from the paper and the timings."])
def expected(reg, k) -> str | None: b5 = FS.tiers(reg)[k].get("b5") return f"Expect an error of {UI.pct(b5)} on a new design of a trained family. We measured this on 39 layouts the model never saw." if b5 else None
def check_thickness(thickness_um) -> float: t = float(thickness_um) if not t >= MIN_THICKNESS_UM: raise ValueError(f"The substrate must be at least {MIN_THICKNESS_UM:g} µm thick (got {thickness_um!r} µm). The models are " "tested on substrates of 10-1000 µm.") return t
def settings(reg, name, substrate, thickness_um) -> tuple: """The response-cache settings of a request (with the prepared layout, the cache key).""" return ("qcap", FS.name(reg, name), str(substrate), float(thickness_um), reg["version"])
def _predict(lay, model, substrate, thickness_um, w=None, own=False): from . import respcache READY.wait() reg = load_registry() name = resolve(reg, model) check_thickness(thickness_um) AC.check_size(lay.n_conductors) fn = lambda: FS.predict(lay, name, reg, substrate=substrate, thickness_um=thickness_um) # noqa: E731 if lay.n_conductors > 8: fn0 = fn
def fn(): with HEAVY: return fn0() w = w or AC.Who() st = settings(reg, name, substrate, thickness_um) if not respcache.has(lay, st): AC.QUOTA.check(w, own) res = respcache.cached(lay, st, fn) if not res["timing_s"].get("response_cache_hit"): AC.QUOTA.charge(w, own) return res
_USAGE = []
def usage_stats() -> U.Usage: if not _USAGE: _USAGE.append(U.Usage("demo")) return _USAGE[0]
def bucket(n_with_ground: int) -> str: return next(b for top, b in ((3, "2-3"), (9, "4-9"), (19, "10-19"), (69, "20-69"), (10**9, "70+")) if n_with_ground <= top)
def _served(w, f, prep, model, substrate, thickness_um): """Every predict path (UI Predict, /predict, /predict_gds): sign-in, limits, the prediction and the aggregate counters.""" t = time.perf_counter() us = usage_stats() if w.served else None if us: us.seen("distinct_users" if w.user else "distinct_anonymous", w.user or w.ip) try: own = AC.check_file(_path(f), w) lay = prep() res = _predict(lay, model, substrate, thickness_um, w, own) except AC.LimitReached as e: if us: us.inc("refusals", e.reason) raise except (LayoutError, ValueError, KeyError, FileNotFoundError): if us: us.inc("refusals", "invalid_input") raise except Exception: if us: us.inc("errors") raise if us: us.inc("runs_by_tier", res["tier"]) us.inc("runs_by_conductors", bucket(lay.n_conductors + 1)) us.inc("runs_by_source", "upload" if own else "example") if res["timing_s"].get("response_cache_hit"): us.inc("cache_hits") us.latency(time.perf_counter() - t) return lay, res
def report_md(res: dict, reg) -> str: """Run details under the matrix. The physical checks, the off-stack route and the expected error are in the callout above the matrix and the ground-self-term flag in the matrix note, so they are not repeated here.""" t = res["timing_s"] st = res.get("prior_stack") lv = res.get("levels_ppg") or [] sub = (res.get("substrate_route") or {}).get("route", "training stack") lines = [f"- Model: {UI.md(res['tier_title'].split(':')[0])} ({res['package_version']}, registry v{res['registry_version']})", "- Physics: " + (f"thin-film solves at {' and '.join(f'{p:g}' for p in lv)} panels per gap" if st else "a learned surrogate of the physics prior, with no field solve")] if sub == "training stack": lines.append("- " + A.substrate_line(res)) lines.append("- Time: " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float)) + f" ({t.get('threads')} threads)") ws = [w for w in res["warnings"] if not (w.startswith("physical check failed") or w == A.FAST_WARNING or w.startswith("substrate eps_r "))] if ws: lines += ["", "Warnings:", ""] + [f"- {UI.md(w)}" for w in ws] return "\n".join(lines)
def predict_fn(f, table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model, gstate=None, profile: gr.OAuthProfile | None = None, oauth_token: gr.OAuthToken | None = None, request: gr.Request = None): reg = load_registry() lay, res = _served(AC.who(profile, request, oauth_token), f, lambda: _prepare(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate)), model, _eps(substrate, custom_eps), float(thickness)) res["ground_detection"] = lay.info.get("ground_detection") d = _outdir() (d / "capacitance_fF.csv").write_text(matrix_csv(res, corner="fF")) (d / "capacitance.json").write_text(json.dumps(res, indent=1, default=float)) return UI.matrix_view(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res
def prepare_gfn(f, table, crop, margin_gaps, margin_um, select, gstate=None, profile: gr.OAuthProfile | None = None, oauth_token: gr.OAuthToken | None = None, request: gr.Request = None): AC.check_file(_path(f), AC.who(profile, request, oauth_token)) return prepare_fn(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate))
def inspect_gfn(f, profile: gr.OAuthProfile | None = None, oauth_token: gr.OAuthToken | None = None, request: gr.Request = None): AC.check_file(_path(f), AC.who(profile, request, oauth_token)) return inspect_fn(f)
def _api_layout(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, ground_pieces=""): return prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers), margin_gaps=_margin_api(margin_gaps), max_conductors=LIMITS["max_conductors"], ground_pieces=str(ground_pieces or "").strip() or None)
def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate=SI, custom_eps=11.45, thickness_um=350.0, model="QCap", ground_pieces="", profile: gr.OAuthProfile | None = None, oauth_token: gr.OAuthToken | None = None, request: gr.Request = None): t = time.perf_counter() lay, res = _served(AC.who(profile, request, oauth_token), f, lambda: _api_layout(f, ground_layers, conductor_layers, margin_gaps, ground_pieces), model, _eps(substrate, custom_eps), float(thickness_um)) res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t res["ground_detection"] = lay.info.get("ground_detection") return res
def bake(examples_dir, path) -> dict: """Image build: every bundled example x model on the training stack, through /predict_gds and the UI Predict path (an example click), into the response cache, pickled to path. Both paths prepare the same layout, so they share one entry per example and tier.""" from . import respcache reg = load_registry() t = time.perf_counter() for f in sorted(Path(examples_dir).glob("*.gds")): table = inspect_fn(str(f))[0] gstate = GU.check_fn(str(f), table)[4] for m in names(reg): api_predict_gds(str(f), model=m) predict_fn(str(f), table, False, 0, None, "", SI, 11.45, 350, m, gstate) out = {"entries": respcache.dump(path), "s": round(time.perf_counter() - t, 1)} print("bake " + json.dumps(out), flush=True) return out
def _same(a: dict, b: dict) -> bool: return {k: v for k, v in a.items() if k != "timing_s"} == {k: v for k, v in b.items() if k != "timing_s"}
def load_bake(path, examples_dir) -> dict: """Server start: the baked example results join the response cache only if this machine recomputes the interdigital example bit for bit on every tier (same packages, CPU code paths and threads as the image build); otherwise they are dropped.""" from . import respcache reg = load_registry() t = time.perf_counter() items = respcache.load_items(path) baked = dict(items) for tier in served(reg): lay = _api_layout(str(Path(examples_dir) / "interdigital.gds")) old = baked.get(respcache.key(lay, *settings(reg, tier, SI, 350.0)), (None,))[0] if old is None or not _same(old, FS.predict(lay, tier, reg, substrate=SI, thickness_um=350.0)): out = {"bake": "dropped", "reason": f"interdigital / {FS.name(reg, tier)} differs from the baked result", "s": time.perf_counter() - t} break else: out = {"bake": "loaded", "entries": len(items), "cache_entries": respcache.put_many(items), "s": time.perf_counter() - t} print("bake " + json.dumps(out, default=float), flush=True) return out
def models_fn(): reg = load_registry() h = reg["flagship_hub"] out = [] for k in served(reg): t = FS.tiers(reg)[k] out.append({"id": t["paper_name"], "title": t["title"], "summary": t.get("summary"), "warning": t.get("warning"), "own": t.get("own") or {}, "b5": t.get("b5"), "b5_physics": t.get("b5_physics"), "time_space": t.get("time_space"), "time_x86": t.get("time_x86"), "stack": t.get("stack"), "levels_ppg": [float(p) for p in t.get("ppg") or []], "default": k == h["default_arm"], "max_conductors": int(h["max_conductors"]), "limits": limits()}) from . import paper as PA return out + [{"geomgnn_version": __version__, "tlsq_infer_version": TLSQ_VERSION, "registry_version": reg["version"], "training_layouts": h.get("training_layouts"), "startup": dict(PA.STARTUP, **({"default": FS.name(reg, PA.STARTUP["default"])} if PA.STARTUP.get("default") in FS.tiers(reg) else {})), "packages": packages()}]
def packages() -> dict: """Versions of the main packages (the image's full list: IMAGE_FREEZE.txt next to app.py, Docker variant).""" from importlib.metadata import PackageNotFoundError, version out = {} for p in ("torch", "numpy", "scipy", "numba", "shapely", "gdstk", "gradio"): try: out[p] = version(p) except PackageNotFoundError: out[p] = None return out
def limits() -> dict: return {"anonymous": "bundled examples only", "predictions_per_user_per_utc_day": AC.DAILY, "max_conductors_with_ground": AC.MAX_NETS - 1, "free": "repeats answered from the cache and the examples", "local_guide": AC.LOCAL_GUIDE}
LEDE = "Upload the GDS of a planar superconducting layout and get its full Maxwell capacitance matrix in fF."LIMITS_MD = (f"The examples run without sign-in. To run your own layout, sign in with Hugging Face. You get {AC.DAILY} predictions per day " f"(UTC) for layouts with fewer than {AC.MAX_NETS} conductors, ground included. Asking again for a result you already have " "does not count.")PRIVACY_MD = ("We process uploaded layouts in memory and keep them there only while the Space runs, to answer repeat requests. Nothing " "is written to permanent storage, and we never log or keep file names or geometry. To enforce the daily limit, we turn your " "Hugging Face username and your network address into keyed hashes, which stay in memory and are cleared at the end of the " "UTC day. They are never stored or logged. We keep only daily totals (runs per model and per layout size, refusals by " "reason, errors, response times and the number of distinct users that day) to see how the demo is used. Hugging Face keeps " "ordinary web access logs under its own policy.")VIEWS = ["Layers", "Nets"]EXAMPLE_NAMES = {"interdigital.gds": "interdigital capacitor", "lattice_1q.gds": "one-qubit grid", "lattice_5q.gds": "five-qubit grid", "shielded_concentric.gds": "shielded concentric", "transmon_pocket.gds": "TransmonPocket", "xmon.gds": "Xmon"}EXAMPLE_NOTES = {"lattice_1q.gds": "≈20 s on QCap", "lattice_5q.gds": "≈20 s on QCap"}LAYER_HELP = ("Set the role of each layer by picking it from the list or clicking its row. Use `ground` for the ground plane (one net), " "`conductor` for metal islands (each connected body is one net, C1, C2, …), `ground+conductor` when both are on one layer " "(we then find the ground) and `ignore` for markers, junctions and labels. By default 1/0 is ground and 1/10 is conductor.")
def about_md(reg) -> str: h = reg["flagship_hub"]
return f"""The models handle planar layouts only, i.e., one metal layer of zero thickness on a dielectric substrate. Each model computes a thin-film physics prior (QCap-Fast learns it instead) and corrects it with networks trained on Q3D simulations.
{LIMITS_MD} Files can be up to {LIMITS['max_file_mb']:g} MB and {LIMITS['max_polygons']:,} polygons, and the Space answers one request at a time. These limits come from the server, not from the models. To go past them, [run the models on your own computer]({AC.LOCAL_GUIDE}).
You can also call the demo from Python with gradio_client. "Use via API" at the bottom of the page lists every endpoint.
```pythonfrom gradio_client import Client, handle_filec = Client("{h['space']}", oauth_token=HF_TOKEN) # oauth_token signs you in (your own layouts)r = c.predict(handle_file("layout.gds"), "1/0", "1/10", 0, "Si (cryogenic, training)", 11.45, 350, "{FS.name(reg, h['default_arm'])}", api_name="/predict_gds")r["names"], r["matrix_fF"]```
The arguments are, in order, the GDS file, the ground layers, the conductor layers, the crop margin in gaps (0 keeps the training geometry), the substrate, eps_r (for a custom substrate), the thickness in µm, the model ({', '.join(names(reg))}, in any case) and the ground pieces ("" picks them automatically when ground and conductors share a layer).
{PRIVACY_MD}
<small>geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}, registry v{reg['version']}.</small>"""
def _stem(f) -> str: return Path(_path(f)).stem
def _roles_label(table) -> str: rows = UI._rows(table) s = [f"{UI._key(r)} {r[2]}" for r in rows] return "Layers: " + " · ".join(s[:4]) + (f" · {len(s) - 4} more" if len(s) > 4 else "")
def _default_layers(table) -> bool: """True when the file has the convention's 1/0 ground and 1/10 conductors, or one shared layer (the ground check covers it).""" rows = UI._rows(table) roles = {UI._key(r): str(r[2]) for r in rows} return (roles.get("1/0") == "ground" and roles.get("1/10") == "conductor") or any("+" in v for v in roles.values())
def layers_view(f): table, fig = inspect_fn(f) return table, UI.fig_files(fig, _outdir(), f"{_stem(f)}_layers")
def _size(b) -> str: return f"{b[2] - b[0]:,.0f} × {b[3] - b[1]:,.0f} µm"
def _names(names) -> str: return ", ".join(names) if len(names) <= 6 else f"{names[0]} … {names[-1]}"
def nets_caption(lay, full_ground=None, select="") -> str: """What Predict will model: the nets, the ground extent (before / after the crop) and the subset.""" n_all = int(lay.info.get("n_bodies_total") or lay.n_conductors) lines = [f"Nets numbered as in the matrix: G and {_names(lay.names)}."] if lay.window is not None and full_ground and _size(full_ground) == _size(lay.ground.bounds): lines.append(f"The crop window (dashed, margin {lay.info['margin_um']:,.0f} µm) holds the whole ground plane, " f"{_size(full_ground)}, so nothing is cut.") elif lay.window is not None: lines.append(f"Ground cropped from {_size(full_ground)} to {_size(lay.ground.bounds)} (dashed window, margin " f"{lay.info['margin_um']:,.0f} µm). This is no longer the training geometry." if full_ground else f"Ground cropped to {_size(lay.ground.bounds)} (dashed window).") else: lines.append(f"Full ground plane, {_size(lay.ground.bounds)} (the training geometry).") if lay.n_conductors < n_all: sel = ", ".join(f"C{x.strip()}" for x in str(select).split(",") if x.strip()) lines.append(f"Modelling {lay.n_conductors} of {n_all} conductors ({sel}, shown as {_names(lay.names)} in the matrix). " "Hatched shapes are not modelled.") return "".join(f"<p class='tl-note'>{html.escape(x)}</p>" for x in lines)
def nets_view(f, table, crop, margin_gaps, margin_um, select, gstate): """The extracted nets, labelled as the matrix: G (ground, or G #k pieces on a shared layer) and C1, C2, ...; the crop window and the unmodelled bodies when cropped or a subset is selected. Returns ((png, svg), warnings, caption, prepared-layout key).""" import matplotlib matplotlib.use("Agg") from matplotlib.lines import Line2D from matplotlib.patches import Patch
from . import respcache pieces = GU.pieces_of(gstate) lay = _prepare(f, table, crop, margin_gaps, margin_um, select, pieces) full = _prepare(f, table, False, 0, None, select, pieces).ground.bounds if lay.window is not None else None fig = lay.render(compact=lay.n_conductors > 12) ax = fig.axes[0] if not lay.info.get("ground_detection") and not lay.ground.is_empty: q = lay.ground.representative_point() ax.annotate("G", (q.x, q.y), ha="center", va="center", fontsize=11, weight="bold", color=INK, bbox=dict(boxstyle="round,pad=0.2", fc="#e5e7eb", ec="#374151", lw=0.6)) keys = [Patch(fc="none", ec=UNMODELLED_COLOR, hatch="///", label="not modelled")] if lay.extra_metal else [] if lay.window is not None: keys.append(Line2D([], [], ls="--", color=WINDOW_COLOR, lw=1.0, label="crop window")) if keys: ax.legend(handles=keys, loc="upper center", bbox_to_anchor=(0.5, -0.11), ncol=len(keys), frameon=False, fontsize=9) fig.tight_layout() return (UI.fig_files(fig, _outdir(), f"{_stem(f)}_nets"), list(lay.warnings), nets_caption(lay, full, select), respcache.key(lay))
def _alive(pair) -> bool: return bool(pair) and all(Path(x).exists() for x in pair[:2])
def show_view(mode, vst, f, table, crop, margin_gaps, margin_um, select, gstate): """(image, SVG button, message, state) for the chosen view; Nets runs the prepare step when its picture is missing or stale.""" vst = dict(vst or {}) if f is None: return None, gr.update(visible=False, value=None), "", vst try: if mode == "Nets": if not _alive(vst.get("nets")): pair, warns, cap, key = nets_view(f, table, crop, margin_gaps, margin_um, select, gstate) vst["nets"], vst["nets_key"] = [*pair, warns, cap], key pair = vst["nets"] msg = pair[3] + (UI.callout("warn", "Layout warnings", [html.escape(w) for w in pair[2]]) if pair[2] else "") else: if not _alive(vst.get("layers")): vst["layers"] = list(layers_view(f)[1]) pair, msg = vst["layers"], "" except Exception as e: # noqa: BLE001 vst["nets_key"] = None return None, gr.update(visible=False, value=None), UI.error_html(e, "Could not extract the nets" if mode == "Nets" else "Could not draw the layers"), vst return pair[0], gr.update(visible=True, value=pair[1]), msg, vst
def refresh_view(mode, vst, *a): """An input of the extraction changed: forget the Nets picture; redraw it when it is on screen.""" vst = dict(vst or {}, nets=None, nets_key=None) if mode != "Nets": return gr.update(), gr.update(), gr.update(), vst return show_view(mode, vst, *a)
def preview_fn(mode, vst, f, *a): """Options changed (crop, margins, subset): switch to the Nets view of exactly the layout Predict will model (≈0.1 s on the examples, so it runs live).""" if f is None: return gr.update(), gr.update(), gr.update(), gr.update(), vst return ("Nets", *refresh_view("Nets", vst, f, *a))
def upload_fn(f, mode, profile: gr.OAuthProfile | None = None, oauth_token: gr.OAuthToken | None = None, request: gr.Request = None): """File change (upload, example, clear): layer table and roles, the Layers picture, the viewer bar. Anonymous visitors get a sign-in message for their own files (the examples stay open).""" none = gr.update(choices=[], value=None) off = gr.update(visible=False) if f is None: return [], off, off, "", none, gr.update(value=None), None, gr.update(visible=False, value=None), off, {}, "" try: AC.check_file(_path(f), AC.who(profile, request, oauth_token)) table, pair = layers_view(f) except Exception as e: # noqa: BLE001 return ([], off, off, UI.error_html(e, "Could not read this file"), none, gr.update(value=None), None, gr.update(visible=False, value=None), off, {}, "") keys = [UI._key(r) for r in table] odd = not _default_layers(table) lay_mode = mode != "Nets" return (table, gr.update(visible=True, open=odd, label=_roles_label(table)), gr.update(visible=odd), "", gr.update(choices=keys, value=keys[0] if keys else None), gr.update(value=table[0][2] if table else None), pair[0] if lay_mode else gr.update(), gr.update(visible=True, value=pair[1]) if lay_mode else gr.update(), gr.update(visible=True), {"layers": list(pair), "nets": None}, "")
def stack_note(reg, substrate, custom_eps, thickness) -> str: try: eps = float(custom_eps) if substrate == CUSTOM else float(reg.substrates()[substrate]) on = A.on_training_stack(eps, float(thickness)) except (TypeError, ValueError, KeyError): return "" if on: return "" return UI.callout("warn", "Off the training stack (Si, eps_r 11.45, 350 µm)", [ f"QCap and QCap-Lite solve the physics prior at your stack, and the networks correct it unchanged. We tested this on " f"{A.TESTED_RANGE}. QCap-Fast only rescales its prediction, and it tells you so."])
def _api(fn, n_out): """_safe(fn) with fn's signature, so Gradio injects the OAuth profile and the request.""" return functools.wraps(fn)(_safe(fn, n_out))
def build_app(title: str, examples_dir=None): reg = load_registry() subs = list(reg.substrates()) + [CUSTOM] ms = served(reg) default = FS.name(reg, reg["flagship_hub"]["default_arm"]) ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else [] AC.register_examples(ex) usage_stats() label = {"accurate": "QCap (≈1 s, default)", "balanced": "QCap-Lite (≈0.5 s)", "fast": "QCap-Fast (≈0.1 s, trained families only)"} with UI.blocks(title, delete_cache=(60, PURGE_AGE_S), head=UI.favicon_head()) as demo: gr.HTML(UI.header(reg["flagship_hub"]["title"], LEDE, product="qcap"), container=False, padding=False, elem_classes="tl-flush") with gr.Row(): with gr.Column(scale=1): with gr.Row(elem_classes="tl-login"): gr.LoginButton(size="sm", scale=0, min_width=220) gr.Markdown(f"Sign in to run your own layout, with {AC.DAILY} predictions per day for layouts with fewer than " f"{AC.MAX_NETS} conductors including ground. The examples run without sign-in. " f"[On your own computer there are no limits]({AC.LOCAL_GUIDE}).", elem_classes="tl-note") gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"]) if ex: demo.tl_examples = UI.examples(gds, ex, label="Examples", example_labels=[ EXAMPLE_NAMES.get(p.name, p.stem) + (f" ({EXAMPLE_NOTES[p.name]})" if p.name in EXAMPLE_NOTES else "") for p in ex]) upload_msg = gr.HTML(elem_classes="tl-flush") with gr.Accordion("Layers", open=False, visible=False) as layer_acc: layer_help = gr.Markdown(LAYER_HELP, visible=False) layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"], value=None, label="Layers in the file", show_label=False, interactive=False) pick, role = UI.layer_editor() with gr.Accordion("Options: model a subset or crop the ground", open=False): select = gr.Textbox(label="Conductors to model, e.g. 1,2,3 (leave empty for all)", value="") crop = gr.Checkbox(False, label="Crop the ground plane around the conductors (no longer the training geometry)", elem_classes="tl-check") with gr.Row(visible=False) as crop_row: margin = gr.Slider(0, 300, value=0, step=1, label="Margin in conductor-to-ground gaps (0 sets the window automatically)") margin_um = gr.Number(value=None, label="Or a margin in µm, which overrides the slider") with gr.Column(scale=1): with gr.Row(visible=False, elem_classes="tl-viewbar") as viewbar: view = gr.Radio(VIEWS, value=VIEWS[0], show_label=False, container=False, elem_id="tl-view", label="view", scale=0, min_width=180) svg_btn = gr.DownloadButton("Download SVG", value=None, size="sm", variant="secondary", visible=False, scale=0, min_width=130) img = gr.Image(type="filepath", interactive=False, show_label=False, label="layout", elem_id="tl-viewer", buttons=["download", "fullscreen"], height=440, alt_text="The uploaded layout, shown by layer (Layers) or as the extracted nets G, C1, " "C2, … numbered as in the matrix (Nets).") view_msg = gr.HTML(elem_classes="tl-flush") gparts = GU.build() gst = gparts[0] with gr.Row(equal_height=False): model = gr.Radio([(label.get(k, FS.name(reg, k)), FS.name(reg, k)) for k in ms], value=default, label="Model", interactive=True, elem_id="tl-tier", scale=3, min_width=300) substrate = gr.Dropdown(subs, value=subs[0], label="Substrate", scale=2, min_width=220) custom_eps = gr.Number(value=11.45, label="eps_r", visible=False, scale=1, min_width=110) thickness = gr.Number(value=350, label="Thickness (µm)", scale=1, min_width=120) sub_note = gr.HTML(elem_classes="tl-flush") with gr.Accordion("Models and their accuracy", open=False): gr.Markdown(tiers_md(reg)) if "fast" in ms: gr.Markdown("Use QCap-Fast only for quick screening of the component families it was trained on. On new designs it did " "worse than the physics alone (see the table above), so use QCap for anything that matters.") pred_btn = gr.Button("Predict", variant="primary") status = gr.HTML(elem_classes="tl-flush") with gr.Column(visible=False) as result_box, gr.Row(): with gr.Column(scale=2): mat = gr.Dataframe(label="Maxwell matrix (fF)", interactive=False, elem_classes=UI.MAT, pinned_columns=1, buttons=["copy", "fullscreen"]) mat_note = gr.HTML(container=False, padding=False, elem_classes="tl-flush") with gr.Column(): csv_f = gr.File(label="CSV (fF, full precision)") json_f = gr.File(label="JSON (matrix and metadata)") with result_box: report = gr.Markdown() with gr.Accordion("About", open=False): gr.Markdown(about_md(reg)) with gr.Accordion("Cite", open=False): gr.Markdown(UI.CITE_MD) gr.HTML(UI.footer(), container=False, padding=False, elem_classes="tl-flush") res_state = gr.State(None) vst = gr.State({}) with gr.Row(visible=False): a_g = gr.Textbox("1/0") a_c = gr.Textbox("1/10") a_m = gr.Number(0) a_gp = gr.Textbox("") a_model = gr.Textbox(default) # API model argument: any case of QCap / QCap-Lite / QCap-Fast (a Radio takes exact choices only) a_out = gr.JSON() a_btn = gr.Button("api") m_btn = gr.Button("models") m_out = gr.JSON() i_btn = gr.Button("inspect") p_btn = gr.Button("predict") r_btn = gr.Button("prepare") layer_plot = gr.Plot() prep_plot = gr.Plot() warn_md = gr.Markdown() summary = gr.JSON() prepared_gds = gr.File() pins = [gds, layers, crop, margin, margin_um, select, substrate, custom_eps, thickness, model, gst] pouts = [mat, csv_f, json_f, report, res_state] api_pins = [a_model if x is model else x for x in pins] vin = [view, vst, gds, layers, crop, margin, margin_um, select, gst] vout = [img, svg_btn, view_msg, vst] ui_predict = functools.wraps(predict_fn)(UI.predict_ui(predict_fn, lambda r: expected(reg, FS.key(reg, r["tier"])), note=True)) ui_predict.__name__ = "predict_fn_ui" uouts = pouts + [status, result_box, mat_note] light = dict(concurrency_id="light", concurrency_limit=1) # previews and file handling: never queued behind a solve solve = dict(concurrency_id="predict", concurrency_limit=1) # every predict path: one at a time (process-global prior stack) hidden = dict(api_visibility="private", show_progress="hidden", **light) substrate.change(lambda s: gr.update(visible=s == CUSTOM), substrate, custom_eps, **hidden) for ev in (substrate.change, custom_eps.change, thickness.change): ev(lambda s, e, t: stack_note(reg, s, e, t), [substrate, custom_eps, thickness], sub_note, **hidden) crop.change(lambda c: gr.update(visible=bool(c)), crop, crop_row, **hidden) up = gds.change(upload_fn, [gds, view], [layers, layer_acc, layer_help, upload_msg, pick, role, img, svg_btn, viewbar, vst, view_msg], api_visibility="private", **light) view.input(show_view, vin, vout, api_visibility="private", **light) i_btn.click(_api(inspect_gfn, 2), gds, [layers, layer_plot], api_name="inspect", **light) edit = UI.wire_editor(layers, pick, role) edit.then(lambda t: gr.update(label=_roles_label(t)), layers, layer_acc, **hidden) r_btn.click(_api(prepare_gfn, 4), [gds, layers, crop, margin, margin_um, select, gst], [prep_plot, warn_md, summary, prepared_gds], api_name="prepare", **light) after = lambda ev: ev.then(refresh_view, vin, vout, **hidden) # noqa: E731 GU.wire(gds, layers, pred_btn, gparts, [up, edit], after=after).then(ui_predict, pins, uouts, api_visibility="private", **solve) for ev in (crop.change, margin.change, margin_um.change, select.change): ev(preview_fn, vin, [view] + vout, trigger_mode="always_last", **hidden) pred_btn.click(ui_predict, pins, uouts, api_visibility="private", **solve) p_btn.click(_api(predict_fn, 5), api_pins, pouts, api_name="predict", **solve) UI.mark_stale(res_state, status, mat, report, [gds.change, model.change, substrate.change, custom_eps.change, thickness.change, select.change, crop.change, margin.change, margin_um.change, edit.then]) a_btn.click(_api(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, a_model, a_gp], a_out, api_name="predict_gds", **solve) m_btn.click(models_fn, None, m_out, api_name="models", **light) return demo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314"""Gradio front end of the GNN Space (deploy/GNN_SPACE.md): the paper-models Space (tlsq_infer.app_v2) with the geomfast GNN(geomgnn.api, registry gnn_models) in two tiers, accurate (default, field-solve prior) and fast (learned prior), and E3 / C0(tlsq_infer.final, registry final_models) kept for comparison.Same endpoints and argument order as app_v2:
/models () -> served models: id, title, recipe, role, accuracy /inspect (gds file) -> layer table, layer plot /prepare (gds, layers table, crop, margin_gaps, margin_um, select) -> preview, warnings, summary, simplified GDS /predict (gds, layers table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, model, self_from_rows, trust_rule) -> matrix table, CSV, JSON, report /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, model, self_from_rows, trust_rule) -> result dict. model: "GNN" (accurate, default), "GNN-LP" (fast), "E3", "C0" (the server's radio accepts these ids only; in process also "accurate" / "gnn" / "fast" / "model" / "physics"). GNN models: training stack only (Si 11.45, 350 um); self_from_rows and trust_rule apply to E3 / C0 only."""
from __future__ import annotations
import jsonimport timefrom pathlib import Path
from tlsq_infer import __version__ as TLSQ_VERSIONfrom tlsq_infer import final as Ffrom tlsq_infer.app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn, matrix_tablefrom tlsq_infer.app_v2 import NETWORK_CAP, PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fnfrom tlsq_infer.app_v2 import report_md as report_md_v2from tlsq_infer.layout import LayoutError, preparefrom tlsq_infer.predict import matrix_csvfrom tlsq_infer.registry import load_registry
from . import __version__from . import api as Afrom . import ui as UI
ALIASES = {"gnn": "GNN", "accurate": "GNN", "fast": "GNN-LP", "gnn-lp": "GNN-LP", "learned prior": "GNN-LP", "model": "E3", "physics": "C0", "physics only": "C0"}
def compare_names(reg) -> list[str]: return [k for k in (reg["gnn_hub"].get("compare_models") or []) if k in (reg.data.get("final_models") or {})]
def served(reg=None) -> list[str]: reg = reg or load_registry() return [k for k in A.gnn_names(reg) if A.available(k, reg)] + [k for k in compare_names(reg) if F.available(k, reg)]
def resolve(reg, model) -> str: m = str(model or reg["gnn_hub"]["default_model"]).strip() m = ALIASES.get(m.lower(), m) if m not in served(reg): old = (reg.data.get("gnn_models") or {}).get(m) or {} why = f" ({m} is retired: {old['retired']})" if old.get("retired") else "" raise ValueError(f"model {model!r} is not served here{why}; choose one of {served(reg)} (or accurate / fast / model / physics)") return m
def is_gnn(reg, name) -> bool: return name in (reg.data.get("gnn_models") or {})
def _predict(lay, model, substrate, thickness_um, self_from_rows=True, trust_rule=None): reg = load_registry() name = resolve(reg, model) if lay.n_conductors > NETWORK_CAP and (is_gnn(reg, name) or F.load_model(name, reg).recipe == "E3"): raise LayoutError(f"{lay.n_conductors} conductors: the network models are capped at {NETWORK_CAP} on this server; use the " "physics-only C0 recipe, or run the package locally") if is_gnn(reg, name): fn = lambda: A.predict_gnn(lay, name, reg, substrate=substrate, thickness_um=thickness_um) # noqa: E731 else: tr = bool(reg["final_defaults"].get("trust_rule", True)) if trust_rule is None else bool(trust_rule) fn = lambda: F.predict_final(lay, name, substrate=substrate, thickness_um=thickness_um, # noqa: E731 self_from_rows=bool(self_from_rows), trust_rule=tr) if lay.n_conductors <= 8: return fn() with HEAVY: return fn()
def _fmt(x, nd=3) -> str: return "n/a" if x is None else (f"{x:.{nd}f}" if abs(x) < 100 else f"{x:.1f}")
DEFAULT_ACC_NOTE = ("paper_v4 Table 2: layout-mean median relative error, MAE and RMSE over mutual entries, 0.1 fF floor; frozen " "before any test set was read and scored once.")
def acc_note(m: dict) -> str: return m.get("accuracy_note") or DEFAULT_ACC_NOTE
def extra_acc(m: dict) -> list[str]: """Signal-self rows, test cohorts, held-out-family rows and the prior-v1 test cohorts of an entry, when the registry has them.""" out = [] if m.get("accuracy_signal_self"): out += ["", "Signal self terms:", ""] + acc_lines({"accuracy": m["accuracy_signal_self"]}) if m.get("accuracy_test"): out += ["", m.get("accuracy_test_note", ""), ""] + acc_lines({"accuracy": m["accuracy_test"]}) if m.get("accuracy_lofo"): out += ["", m.get("accuracy_lofo_note", ""), ""] + acc_lines({"accuracy": m["accuracy_lofo"]}) if m.get("accuracy_test_prior_v1") and not m.get("accuracy_test"): out += ["", m.get("accuracy_test_prior_v1_note", ""), ""] + acc_lines({"accuracy": m["accuracy_test_prior_v1"]}) return out
def acc_lines(m: dict) -> list[str]: acc = m.get("accuracy") or {} if not acc: return ["No test number applies to this model."] rows = ["| test cohort | layouts | median % | MAE (fF) | RMSE (fF) |", "|---|---|---|---|---|"] rows += [f"| {v['set']} | {v.get('layouts', '')} | {_fmt(v['median_pct'])} | {_fmt(v['mae_ff'], 4)} | {_fmt(v['rmse_ff'], 4)} |" for v in acc.values()] return rows
def lat_test_lines(m: dict) -> list[str]: lat = m.get("latency_test") or {} if not lat: return [] rows = ["| test latency | layouts | median (s) | p90 (s) | sum (s) |", "|---|---|---|---|---|"] rows += [f"| {v['set']} | {v['layouts']} | {_fmt(v.get('median_s'))} | {_fmt(v.get('p90_s'), 2)} | {_fmt(v.get('sum_s'), 0)} |" for v in lat.values()] return rows + ["", m.get("latency_test_note", "")]
def lat_lines(m: dict) -> list[str]: lat = m.get("latency") or {} if not lat: return [] rows = ["| latency set | layouts | total median (s) | total p95 (s) | geometry (s) | prior (s) | network (s) |", "|---|---|---|---|---|---|---|"] rows += [f"| {v['set']} | {v['layouts']} | {v['total_median_s']:.3f} | {v['total_p95_s']:.2f} | {v['geometry_median_s']:.3f} | " f"{v['prior_median_s']:.3f} | {v['network_median_s']:.4f} |" for v in lat.values()] machine = next(iter(lat.values())).get("machine", "") return rows + ["", f"Wall time from the layout file to the matrix, median over layouts; {machine}."]
def report_md(res: dict, reg) -> str: if not is_gnn(reg, res["model"]): return report_md_v2(res, reg) m = reg["gnn_models"][res["model"]] t = res["timing_s"] pr = res.get("prior") lp = res.get("learned_prior") lines = [f"**Model** `{res['model']}`: {res['model_title']} ({res['role']}), {res['package_version']}, registry v{res['registry_version']}", "**Prior** " + (f"{pr['method']} micro-MoM at {pr['ppg'][0]:g} and {pr['ppg'][1]:g} panels per gap, alpha {pr['alpha']}, " f"implementation `{pr['prior_impl']}`, patches {pr.get('patches') or 'none'}, solver mode `{pr.get('mode')}`" if pr else f"learned prior `{lp['name']}` (no field solve; predicts the 1.5 and 3 panels-per-gap priors)" if lp else "none (solver-free)"), A.substrate_line(res), "**Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float)) + f" ({t.get('threads')} threads)", f"**Physical checks** symmetric (max |C - Cᵀ| {res['checks']['symmetric_max_abs']:.2g} fF), off-diagonals negative: " f"{res['checks']['offdiag_all_negative']}, smallest eigenvalue of the signal block {res['checks']['signal_block_min_eig']:.4g} fF", "", f"**Accuracy of this model.** {acc_note(m)}", ""] + acc_lines(m) + extra_acc(m) if res["warnings"]: lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]] lines += ["", f"Self capacitance: {res['self_capacitance']}.", "Planar single-layer layouts only (zero-thickness metal). Nothing you upload is stored: result files are deleted " f"within {PURGE_AGE_S // 60} minutes."] return "\n".join(lines)
def predict_fn(f, table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model, self_rows, trust_rule=True): reg = load_registry() lay = _prepare(f, table, crop, margin_gaps, margin_um, select) res = _predict(lay, model, _eps(substrate, custom_eps), float(thickness), self_from_rows=bool(self_rows), trust_rule=trust_rule) d = _outdir() (d / "capacitance_fF.csv").write_text(matrix_csv(res)) (d / "capacitance.json").write_text(json.dumps(res, indent=1)) return matrix_table(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res
def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate="Si (cryogenic, training)", custom_eps=11.45, thickness_um=350.0, model="GNN", self_from_rows=True, trust_rule=True): t = time.perf_counter() lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers), margin_gaps=_margin_api(margin_gaps), max_conductors=LIMITS["max_conductors"]) res = _predict(lay, model, _eps(substrate, custom_eps), float(thickness_um), self_from_rows=bool(self_from_rows), trust_rule=trust_rule) res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t return res
def _entry(reg, k) -> dict: return reg["gnn_models"][k] if is_gnn(reg, k) else reg["final_models"][k]
def _lp_public(lp): """The learned prior without its file path (a {"path": ...} dict would be read as a file by gradio clients).""" return None if not lp else {"name": lp["name"], "sha256": lp["checkpoint"]["sha256"], "ppg": lp.get("ppg"), "training": lp.get("training")}
def models_fn(): reg = load_registry() out = [] for k in served(reg): m = _entry(reg, k) d = {"id": k, "title": m["title"], "recipe": "GNN" if is_gnn(reg, k) else m["recipe"], "role": m.get("role"), "accuracy": m.get("accuracy") or {}, "warning": m.get("warning"), "default": k == reg["gnn_hub"]["default_model"]} if is_gnn(reg, k): d |= {"arm": m["arm"], "prior": m.get("prior"), "learned_prior": _lp_public(m.get("learned_prior")), "accuracy_test": m.get("accuracy_test") or {}, "latency": m.get("latency") or {}, "ensemble": m.get("ensemble"), "substrate": (A.FAST_ROUTE if m.get("learned_prior") else A.CALIBRATED_ROUTE) + " off the training stack (Si 11.45, 350 um)"} else: d["ledger_id"] = m.get("ledger_id") out.append(d) return out + [{"geomgnn_version": __version__, "tlsq_infer_version": TLSQ_VERSION, "registry_version": reg["version"], "startup": dict(A.STARTUP)}]
def _model_md(reg, k) -> str: m = _entry(reg, k) if not is_gnn(reg, k): acc = (m.get("accuracy") or {}).values() rows = ["| test set | median % | MAE (fF) | RMSE (fF) |", "|---|---|---|---|"] rows += [f"| {v['set']} | {v['median_pct']:.3f} | {v['mae_ff']:.3f} | {v['rmse_ff']:.3f} |" for v in acc] return "\n".join([f"**{m['title']}** ({m.get('role')}; for comparison). {m.get('summary', '')}", "", "Test results as reported in paper_v3 (pooled over entries; not the paired paper_v4 cohorts of the GNN rows):", ""] + (rows if acc else ["n/a"])) return "\n".join([f"**{m['title']}** ({m.get('role')}). {m.get('summary', '')}"] + ([f"\n> **Warning.** {m['warning']}"] if m.get("warning") else []) + ["", acc_note(m), "", *acc_lines(m), *extra_acc(m), "", *lat_lines(m)] + ([m["latency_note"]] if m.get("latency_note") else []) + ["", *lat_test_lines(m)])
def header(reg) -> str: h = reg["gnn_hub"] return (f"Zero-shot **Maxwell capacitance matrix** of a planar superconducting layout from its GDS. The geomfast GNN, a " f"message-passing network on the full geometric embedding that corrects a two-resolution thin-film MoM prior and predicts " f"the complete N x N matrix (self terms included), in two tiers: **Accurate** (default) solves the prior, **Fast** predicts " f"it with a learned surrogate (no field solve: 6-10x faster, 3.6x the median error in family). **Use Fast only for the " f"component families it was trained on** (listed under the model); on a component family it never saw it is worse than " f"the physics prior alone, so **for a new component type use Accurate** (numbers under each model). " f"{h.get('comparison_note', '')} **Private preview** (paper in preparation).")
def build_app(title: str, examples_dir=None): import gradio as gr
reg = load_registry() subs = list(reg.substrates()) + [CUSTOM] ms = served(reg) default = reg["gnn_hub"]["default_model"] ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else [] with gr.Blocks(title=title, delete_cache=(60, PURGE_AGE_S)) as demo: gr.Markdown(f"# {title}\n{header(reg)}") with gr.Accordion("Planar circuits and the layer convention", open=False): gr.Markdown(INTRO.replace("A thin-film method-of-moments solve\nprovides a physics prior and a graph network trained on 40,153 Q3D simulations corrects it.", "See the model descriptions below.")) gr.Markdown("## Model") model = gr.Radio([(_entry(reg, k)["title"], k) for k in ms], value=default, label="model") model_info = gr.Markdown(_model_md(reg, default)) model.change(lambda k: _model_md(reg, k), model, model_info, api_visibility="private") gr.Markdown("## 1. Upload a GDS and assign layer roles") with gr.Row(): with gr.Column(scale=1): gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"]) if ex: UI.examples(gds, ex, label="or start from an example") layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"], label="detected layers: edit 'role' (ground / conductor / ignore)", interactive=True, value=[[1, 0, "ground", 0, 0, ""], [1, 10, "conductor", 0, 0, ""]]) layer_plot = gr.Plot(label="layers") gr.Markdown("## 2. Prepare: extract the nets (full ground, as in training)") with gr.Row(): with gr.Column(scale=1): select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="") with gr.Accordion("Advanced: crop the ground (not the training geometry)", open=False): crop = gr.Checkbox(False, label="crop the ground plane around the conductors") margin = gr.Slider(0, 300, value=0, step=1, label="margin in conductor-ground gaps (0 = auto window)") margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider") prep_btn = gr.Button("Prepare", variant="secondary") warn_md = gr.Markdown() summary = gr.JSON(label="prepared layout") prepared_gds = gr.File(label="simplified GDS (1/0 ground, 1/10 conductors)") prep_plot = gr.Plot(label="prepared layout") gr.Markdown("## 3. Substrate\nTraining stack: Si, eps_r 11.45, 350 µm. On other substrates the physics prior is solved at your " "eps_r and thickness and the networks correct it unchanged (calibrated route; tested on Si at 10-1000 µm and eps_r 3.8-24 " "at 350 µm: 0.21-1.02 % (MAE 0.07-0.33, RMSE 0.09-0.45 fF) on 15 held-out designs, against 0.23 % (0.080 / 0.111 fF) " "on the training stack). The learned-prior model does not solve a prior: it rescales by (1+eps)/(1+11.45) and warns.") with gr.Row(): substrate = gr.Dropdown(subs, value=subs[0], label="substrate") custom_eps = gr.Number(value=11.45, label="custom eps_r (when 'custom')") thickness = gr.Number(value=350, label="substrate thickness (µm)") self_rows = gr.Checkbox(True, label="E3 / C0: self-capacitance from row sums (the GNN predicts its self terms)") trust_cb = gr.Checkbox(bool(reg["final_defaults"].get("trust_rule", True)), label="E3: apply the trust rule (default on: fall back to physics-only C0 when the networks disagree)") pred_btn = gr.Button("Predict", variant="primary") gr.Markdown("## 4. Maxwell capacitance matrix (fF)") with gr.Row(): with gr.Column(scale=2): mat = gr.Dataframe(label="Maxwell matrix (fF): diagonal = self, off-diagonal = -mutual", interactive=False) with gr.Column(): csv_f = gr.File(label="CSV") json_f = gr.File(label="JSON (matrix + metadata)") report = gr.Markdown() res_state = gr.State(None) with gr.Row(visible=False): a_g = gr.Textbox("1/0") a_c = gr.Textbox("1/10") a_m = gr.Number(0) a_out = gr.JSON() a_btn = gr.Button("api") m_btn = gr.Button("models") m_out = gr.JSON() gds.upload(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect") prep_btn.click(_safe(prepare_fn, 4), [gds, layers, crop, margin, margin_um, select], [prep_plot, warn_md, summary, prepared_gds], api_name="prepare") pred_btn.click(_safe(predict_fn, 5), [gds, layers, crop, margin, margin_um, select, substrate, custom_eps, thickness, model, self_rows, trust_cb], [mat, csv_f, json_f, report, res_state], api_name="predict") a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows, trust_cb], a_out, api_name="predict_gds") m_btn.click(models_fn, None, m_out, api_name="models") gr.Markdown(f"<small>geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}. Demo-server caps (not limits of the models): " f"{LIMITS['max_file_mb']:g} MB per file, {LIMITS['max_polygons']:,} polygons, {LIMITS['max_conductors']} conductors + " f"ground, {NETWORK_CAP} for the network models (GNN, E3).</small>") return demo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325"""Gradio front end of the paper Space (deploy/GNN_SPACE.md "Paper Space"; registry paper_hub, paper_arms): one selector over everyarm of the paper's ladder and routes tables that runs on a CPU (geomgnn.paper). Same endpoints and argument order as the GNN Space:
/models () -> served arms: id, paper name, route, numbers /inspect (gds file) -> layer table, layer plot /prepare (gds, layers table, crop, margin_gaps, margin_um, select) -> preview, warnings, summary, simplified GDS /predict (gds, layers table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness_um, arm, self_from_rows, trust_rule) -> matrix table, CSV, JSON, report /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps, substrate, custom_eps, thickness_um, arm, self_from_rows, trust_rule, ground_pieces "") -> result dict; arm = an id of /models (default "model"); ground_pieces = e.g. "1,4" when ground and conductors share one layer (default "": detected automatically)"""
from __future__ import annotations
import jsonimport timefrom pathlib import Path
from tlsq_infer import __version__ as TLSQ_VERSIONimport gradio as grfrom tlsq_infer.app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fnfrom tlsq_infer.app_v2 import NETWORK_CAP, PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fnfrom tlsq_infer.app_v2 import report_md as report_md_v2from tlsq_infer.layout import LayoutError, preparefrom tlsq_infer.predict import matrix_csvfrom tlsq_infer.registry import load_registry
from . import __version__from . import api as Afrom . import ground_ui as GUfrom . import paper as PAfrom . import ui as UI
ROUTES = ["(d) good physics", "(c) cheap physics", "(b) learned physics", "(a) no physics", "baseline"]
def served(reg=None) -> list[str]: reg = reg or load_registry() ks = [k for k in PA.live(reg) if PA.available(k, reg)] return sorted(ks, key=lambda k: (ROUTES.index(PA.arms(reg)[k].get("route", "baseline")), list(PA.arms(reg)).index(k)))
def resolve(reg, arm) -> str: a = str(arm or reg["paper_hub"]["default_arm"]).strip() if a not in served(reg): raise ValueError(f"arm {arm!r} is not served here; choose one of {served(reg)}") return a
def cap(reg, a) -> int: """Signal conductors per layout on this Space: the prior-generation network keeps the GNN Space's network cap (dense pair tensors); every other arm runs up to paper_hub.max_conductors (the nine-qubit lattice of the paper).""" return NETWORK_CAP if (a.get("kind") == "final" and a.get("final_model") == "E3") else int(reg["paper_hub"]["max_conductors"])
def _predict(lay, arm, substrate, thickness_um, self_from_rows=True, trust_rule=None): reg = load_registry() name = resolve(reg, arm) a = PA.arms(reg)[name] if lay.n_conductors > cap(reg, a): raise LayoutError(f"{lay.n_conductors} conductors: the arm '{name}' is capped at {cap(reg, a)} on this server; run the package " "locally for larger layouts") from . import respcache fn = lambda: PA.predict(lay, name, reg, substrate=substrate, thickness_um=thickness_um, self_from_rows=self_from_rows, # noqa: E731 trust_rule=trust_rule) if lay.n_conductors > 8: fn0 = fn
def fn(): with HEAVY: return fn0() return respcache.cached(lay, ("paper", name, str(substrate), float(thickness_um), bool(self_from_rows), trust_rule, reg["version"]), fn)
def pct(e) -> str: """'0.177 % (0.0203 / 0.0250 fF)': every % with its MAE / RMSE.""" return "n/a" if not e else f"{e['median_pct']:g} % ({e['mae_ff']:g} / {e['rmse_ff']:g} fF)"
def numbers(a) -> list[str]: p = a.get("paper") or {} rows = [("validation (4,608 layouts)", p.get("val")), ("test, in family (4,009)", p.get("test_infamily")), ("test, zero-shot macro (1,878)", p.get("test_zeroshot")), ("held-out family (4,071 validation layouts)", p.get("heldout_family"))] out = [f"| {k} | {pct(v)}{' — ' + v['note'] if v and v.get('note') else ''} |" for k, v in rows if v] if p.get("time"): out.append(f"| time per layout (median / 90th percentile) | {p['time']} |") if p.get("note"): out.append(f"| note | {p['note']} |") return (["| paper | layout-mean median % (MAE / RMSE fF) |", "|---|---|"] + out) if out else []
def arm_md(reg, k) -> str: a = PA.arms(reg)[k] tabs = ", ".join((a.get("paper") or {}).get("tables") or []) lines = [f"**{UI.md(a['paper_name'])}** ({a.get('route')}; paper: {tabs}). {UI.md(a.get('summary', ''))}"] if a.get("warning"): lines.append(f"\n> **Warning.** {UI.md(a['warning'])}") lines += ["", *numbers(a), "", "Layout-mean median relative error over mutual entries against Q3D, 0.1 fF floor; MAE / RMSE in fF. " "Test = the paper's test benchmark, read once; validation = development data."] if a["kind"] == "final": m = reg["final_models"][a["final_model"]] acc = (m.get("accuracy") or {}).values() if acc: lines += ["", "Prior-generation evaluation (pooled over entries, not the layout-mean of the table above):", "", "| set | median % | MAE (fF) | RMSE (fF) |", "|---|---|---|---|"] lines += [f"| {v['set']} | {v['median_pct']:.3f} | {v['mae_ff']:.3f} | {v['rmse_ff']:.3f} |" for v in acc] return "\n".join(lines)
def expected(reg, k) -> str | None: p = PA.arms(reg)[k].get("paper") or {} for key, lab in (("test_zeroshot", "the paper's zero-shot test (1,878 layouts)"), ("heldout_family", "a held-out family (4,071 layouts)"), ("val", "the paper's validation set (4,608 layouts)")): if p.get(key): return f"Expected error on a new design: {UI.pct(p[key])}, from {lab}." return None
def arm_line(reg, k) -> str: a = PA.arms(reg)[k] e = expected(reg, k) return f"**{UI.md(a['paper_name'])}**, route {a.get('route')}." + (f" {e}" if e else "")
def report_md(res: dict, reg) -> str: a = PA.arms(reg)[res["arm"]] if a["kind"] == "final": return UI.md(report_md_v2(res, reg)) t = res["timing_s"] st = res.get("prior_stack") lv = res.get("levels_ppg") or [] c = res["checks"] lines = [f"- **Arm** `{res['arm']}`: {UI.md(res['paper_name'])}, route {res['route']}; {res['package_version']}, registry v{res['registry_version']}", "- **Physics** " + (f"thin-film solves at {', '.join(f'{p:g}' for p in lv)} panels per gap, prior `{st['name']}` " f"(patches {', '.join(st['patches'] or []) or 'none'}, solver `{st['mode']}`)" if st else "learned prior surrogate (no field solve)" if res.get("learned_prior_sha256") else "none (solver-free)"), "- " + A.substrate_line(res), "- **Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float)) + f" ({t.get('threads')} threads)", f"- **Physical checks** max |C - Cᵀ| {c['symmetric_max_abs']:.2g} fF, off-diagonals negative: " f"{'yes' if c['offdiag_all_negative'] else 'no'}, smallest eigenvalue of the signal block " + (f"{c['signal_block_min_eig']:.4g} fF" if c.get("signal_block_min_eig") is not None else "n/a")] if res["warnings"]: lines += ["", "**Warnings**", ""] + [f"- {UI.md(w)}" for w in res["warnings"]] lines += ["", f"Self capacitance: {res['self_capacitance']}.", "", "This arm's paper numbers: *How accurate is this arm?* in step 2. Planar single-layer layouts only (zero-thickness metal). " "Uploads are held in memory only while the Space is running, to speed up repeat requests; nothing is written to " "permanent storage."] return "\n".join(lines)
def predict_fn(f, table, crop, margin_gaps, margin_um, select, substrate, custom_eps, thickness, arm, self_rows, trust_rule=True, gstate=None): reg = load_registry() lay = _prepare(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate)) res = _predict(lay, arm, _eps(substrate, custom_eps), float(thickness), self_from_rows=bool(self_rows), trust_rule=trust_rule) res["ground_detection"] = lay.info.get("ground_detection") d = _outdir() (d / "capacitance_fF.csv").write_text(matrix_csv(res, corner="fF")) (d / "capacitance.json").write_text(json.dumps(res, indent=1, default=float)) return UI.matrix_view(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res
def prepare_gfn(f, table, crop, margin_gaps, margin_um, select, gstate=None): return prepare_fn(f, table, crop, margin_gaps, margin_um, select, GU.pieces_of(gstate))
def api_predict_gds(f, ground_layers="1/0", conductor_layers="1/10", margin_gaps=0.0, substrate="Si (cryogenic, training)", custom_eps=11.45, thickness_um=350.0, arm="model", self_from_rows=True, trust_rule=True, ground_pieces=""): t = time.perf_counter() lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers), margin_gaps=_margin_api(margin_gaps), max_conductors=LIMITS["max_conductors"], ground_pieces=str(ground_pieces or "").strip() or None) res = _predict(lay, arm, _eps(substrate, custom_eps), float(thickness_um), self_from_rows=bool(self_from_rows), trust_rule=trust_rule) res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t res["ground_detection"] = lay.info.get("ground_detection") return res
def models_fn(): reg = load_registry() out = [] for k in served(reg): a = PA.arms(reg)[k] out.append({"id": k, "paper_name": a["paper_name"], "title": a["title"], "route": a.get("route"), "kind": a["kind"], "summary": a.get("summary"), "warning": a.get("warning"), "paper": a.get("paper") or {}, "stack": a.get("stack"), "levels_ppg": PA.levels_of(a), "default": k == reg["paper_hub"]["default_arm"], "max_conductors": cap(reg, a)}) return out + [{"geomgnn_version": __version__, "tlsq_infer_version": TLSQ_VERSION, "registry_version": reg["version"], "checkpoints_repo": reg["paper_hub"].get("checkpoints_repo"), "startup": dict(PA.STARTUP)}]
LEDE = ("Run every route of the paper that works on a CPU on your own planar layout and get its full Maxwell capacitance matrix in " "fF. Start with <strong>the model</strong> (the default arm); each arm's paper numbers are under <em>How accurate is this " "arm?</em>")
def header(reg) -> str: h = reg["paper_hub"] return UI.header(h["title"], LEDE, "Private preview (paper in preparation). Programmatic use: <code>/predict_gds</code> through " "gradio_client (\"Use via API\" below).")
def routes_md(reg) -> str: ck = reg["paper_hub"].get("checkpoints_repo") return ("The arms: the model, the fast model, the solver-free network, the cheap-physics networks, the mesh ladder of single solves " "and Richardson pairs, the extrapolated physics alone, the ablations and controls, the solver modes and the prior-generation " "baseline. Every other checkpoint the paper reports (k-curves, learning curves, leave-one-family-out folds, the solver-free " f"series, ...) with its training and scoring scripts is in the model repository [{ck}](https://huggingface.co/{ck}).")
def intro(reg) -> str: return INTRO.replace("A thin-film method-of-moments solve\nprovides a physics prior and a graph network trained on 40,153 Q3D " "simulations corrects it.", "Each arm is one route of the paper; most correct thin-film physics with networks " "trained on Q3D.").replace( "Any number of conductors (this free demo accepts up to 30; the models are validated up to 7 including ground, and larger " "layouts get a warning).", f"This server takes up to {reg['paper_hub']['max_conductors']} conductors + ground " f"({NETWORK_CAP} for the prior-generation network).")
SUBSTRATE_MD = ("Training stack: Si, eps_r 11.45, 350 µm. On other substrates the arms that solve physics solve it at your stack and the " f"networks correct it unchanged (calibrated route), tested on {A.TESTED_RANGE}. Learned-prior arms rescale and warn; " "the solver-free arm refuses other substrates.")
def build_app(title: str, examples_dir=None): reg = load_registry() subs = list(reg.substrates()) + [CUSTOM] ms = served(reg) default = reg["paper_hub"]["default_arm"] ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else [] choices = [(f"{PA.arms(reg)[k].get('route')}: {PA.arms(reg)[k]['paper_name']}", k) for k in ms] with UI.blocks(title, delete_cache=(60, PURGE_AGE_S)) as demo: gr.HTML(header(reg), container=False, padding=False, elem_classes="tl-flush") gr.Markdown("## 1. Upload a GDS") with gr.Row(): with gr.Column(scale=1): gds = gr.File(label="GDS file", file_types=[".gds", ".gds2", ".gdsii"]) if ex: UI.examples(gds, ex, label="or start from an example (the lattices are the paper's 1-, 5- and 9-qubit layouts)") upload_msg = gr.HTML(elem_classes="tl-flush") layers = gr.Dataframe(headers=LAYER_COLS, datatype=["number", "number", "str", "number", "number", "str"], value=None, label="detected layers (choose each layer's role below, or click its row)", interactive=False) pick, role = UI.layer_editor() with gr.Accordion("Planar circuits and the layer convention", open=False): gr.Markdown(intro(reg)) layer_plot = gr.Plot(label="layers") gparts = GU.build() gst = gparts[0] with gr.Accordion("Optional: preview the extracted nets, model a subset, crop the ground", open=False): with gr.Row(): with gr.Column(scale=1): select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="") with gr.Accordion("Advanced: crop the ground (not the training geometry)", open=False): crop = gr.Checkbox(False, label="crop the ground plane around the conductors", elem_classes="tl-check") margin = gr.Slider(0, 300, value=0, step=1, label="margin in conductor-ground gaps (0 = auto window)") margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider") prep_btn = gr.Button("Preview the nets", variant="secondary") warn_md = gr.Markdown() summary = gr.JSON(label="extracted nets (summary)") prepared_gds = gr.File(label="simplified GDS (1/0 ground, 1/10 conductors)") prep_plot = gr.Plot(label="extracted nets: grey = ground, colours = conductors") gr.Markdown("## 2. Arm and substrate") model = gr.Dropdown(choices, value=default, label="Arm (route of the paper)", interactive=True) model_info = gr.Markdown(arm_line(reg, default)) with gr.Accordion("How accurate is this arm?", open=False): arm_info = gr.Markdown(arm_md(reg, default)) gr.Markdown(routes_md(reg)) gr.Markdown(SUBSTRATE_MD) with gr.Row(): substrate = gr.Dropdown(subs, value=subs[0], label="substrate", min_width=300) custom_eps = gr.Number(value=11.45, label="eps_r (custom substrate)", interactive=False, min_width=160) thickness = gr.Number(value=350, label="substrate thickness (µm)", min_width=160) with gr.Accordion("Options of the prior-generation arms", open=False): self_rows = gr.Checkbox(True, label="prior-generation baseline: self-capacitance from row sums", elem_classes="tl-check") trust_cb = gr.Checkbox(bool(reg["final_defaults"].get("trust_rule", True)), elem_classes="tl-check", label="prior-generation model: apply its trust rule (default on)") pred_btn = gr.Button("Predict", variant="primary") gr.Markdown("## 3. Maxwell capacitance matrix") status = gr.HTML(UI.EMPTY, elem_classes="tl-flush") with gr.Column(visible=False) as result_box, gr.Row(): with gr.Column(scale=2): mat = gr.Dataframe(label="Maxwell matrix (fF)", interactive=False, elem_classes=UI.MAT, pinned_columns=1, buttons=["copy", "fullscreen"]) gr.HTML(UI.MATRIX_NOTE, container=False, padding=False, elem_classes="tl-flush") with gr.Column(): csv_f = gr.File(label="CSV (fF, full precision)") json_f = gr.File(label="JSON (matrix + metadata)") with result_box: report = gr.Markdown() res_state = gr.State(None) with gr.Row(visible=False): a_g = gr.Textbox("1/0") a_c = gr.Textbox("1/10") a_m = gr.Number(0) a_gp = gr.Textbox("") a_out = gr.JSON() a_btn = gr.Button("api") m_btn = gr.Button("models") m_out = gr.JSON() i_btn = gr.Button("inspect") p_btn = gr.Button("predict") pins = [gds, layers, crop, margin, margin_um, select, substrate, custom_eps, thickness, model, self_rows, trust_cb, gst] pouts = [mat, csv_f, json_f, report, res_state] ui_predict = UI.predict_ui(predict_fn, lambda r: expected(reg, r["arm"])) model.change(lambda k: (arm_line(reg, k), arm_md(reg, k)), model, [model_info, arm_info], api_visibility="private", show_progress="hidden") substrate.change(lambda s: gr.update(interactive=s == CUSTOM), substrate, custom_eps, api_visibility="private", show_progress="hidden") up = gds.change(UI.inspect_ui(inspect_fn), gds, [layers, layer_plot, upload_msg, pick, role], api_visibility="private") i_btn.click(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect") edit = UI.wire_editor(layers, pick, role) prep_btn.click(_safe(prepare_gfn, 4), [gds, layers, crop, margin, margin_um, select, gst], [prep_plot, warn_md, summary, prepared_gds], api_name="prepare") GU.wire(gds, layers, pred_btn, gparts, [up, edit]).then(ui_predict, pins, pouts + [status, result_box], api_visibility="private") pred_btn.click(ui_predict, pins, pouts + [status, result_box], api_visibility="private") p_btn.click(_safe(predict_fn, 5), pins, pouts, api_name="predict") UI.mark_stale(res_state, status, mat, report, [gds.change, model.change, substrate.change, custom_eps.change, thickness.change, select.change, self_rows.change, trust_cb.change, edit.then]) a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows, trust_cb, a_gp], a_out, api_name="predict_gds") m_btn.click(models_fn, None, m_out, api_name="models") gr.Markdown(f"<small>geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}. Demo-server caps (not limits of the models): " f"{LIMITS['max_file_mb']:g} MB per file, {LIMITS['max_polygons']:,} polygons, {reg['paper_hub']['max_conductors']} conductors " f"+ ground ({NETWORK_CAP} for the prior-generation network). One request runs at a time; the nine-qubit lattice takes minutes " "on the accurate arms.</small>") return demo123456789101112131415161718192021222324252627282930313233"""Integrity check of a Space bundle's checkpoint copies. deploy/sync.py --flagship ships each checkpoint without its train_keys (unused atinference) and records both hashes in models/<tier>/info.json: <key>_sha256 = the published checkpoint (= registry, the provenance) and<key>_bundle_sha256 = the shipped copy. install() makes geomgnn.paper check the copy against the latter; folders without*_bundle_sha256 and the registry's source paths keep the registry check unchanged."""from __future__ import annotations
import jsonfrom pathlib import Path
from . import paper as PA
_REGISTRY_CHECK = PA._check
def _check(reg, name, model_dir=None): md = PA._model_dir(model_dir) info = Path(md) / name / "info.json" if md else None z = json.loads(info.read_text()) if info is not None and info.exists() else {} if "checkpoints_bundle_sha256" not in z: return _REGISTRY_CHECK(reg, name, model_dir) a = PA.arms(reg)[name] for key in ("checkpoints", "surrogate"): fs, hs = PA.files(reg, name, key, model_dir), z.get(key + "_bundle_sha256") or [] if z.get(key + "_sha256", []) != PA._hashes(a, key) or len(fs) != len(hs): raise RuntimeError(f"{name}: {info} does not list the registry's {key} (sha256)") for f, h in zip(fs, hs): if PA._sha(f) != h: raise RuntimeError(f"{name}: {f.name} SHA256 differs from the bundle manifest ({h[:12]})") return a
def install() -> None: PA._check = _check12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""farfield arms (agents/farfield/PROTOCOL.md sec. 2): the far-pair dipole form, installed on top of an installed v2mprior (priorv2.installed(policy='fc', dip=True, margin=True)). install(arm, F, P, PV) patches the bound vendor modulesF (fastprior) / P (proxy) through PV (the priorv2 module patching them) and returns the undo callable. a: half-space dipole for every far pair (v2m as deployed; values bit-identical, only timed) b: slab dipole for signal-signal pairs of micro_mom's cross-pocket call; same-pocket and ground far pairs half-space c: slab dipole for every far pairSlab factor (1 + eps_r R(d)) / (1 + eps_r), R = PV.slab_R at the substrate thickness of P.SUBSTRATE, d = centroiddistance: PV.dipole_far_slab's expression, applied per pair."""import time
import numpy as npimport shapely
STATS = dict(cross_calls=0, cross_pairs=0, same_calls=0, same_pairs=0, slab_pairs=0, fill_s=0.0)MODES = {'a': ('half', 'half'), 'b': ('slab_sig', 'half'), 'c': ('slab_all', 'slab_all')}
def reset(): for k in STATS: STATS[k] = 0.0 if k == 'fill_s' else 0
def _dip(mode, frozen, P, PV, tag): def dip(G, conds, pairs, eps_r=11.45, gap=None): t = time.perf_counter() v = frozen(G, conds, pairs, eps_r, gap) pairs = np.asarray(pairs, int).reshape(-1, 2) if mode != 'half': cen = shapely.get_coordinates(shapely.centroid(np.array([G] + list(conds), dtype=object))) d = np.hypot(*(cen[pairs[:, 0]] - cen[pairs[:, 1]]).T) s = v * (1 + eps_r * PV.slab_R(d, float(P.SUBSTRATE["t_um"]), eps_r)) / (1 + eps_r) use = np.ones(len(pairs), bool) if mode == 'slab_all' else (pairs > 0).all(1) v = np.where(use, s, v) STATS['slab_pairs'] += int(use.sum()) STATS[f'{tag}_calls'] += 1 STATS[f'{tag}_pairs'] += len(pairs) STATS['fill_s'] += time.perf_counter() - t return v return dip
def install(arm, F, P, PV): assert F.formula_prior is PV.formula_as_dipole and F._window_solve is not None, 'v2m fill must be installed first' frozen = PV._FROZEN['dipole_far'] assert F.dipole_far is frozen, 'dipole_far must be the vendor function under v2m' saved = (F.dipole_far, F.formula_prior) cross, same = (_dip(m, frozen, P, PV, t) for m, t in zip(MODES[arm], ('cross', 'same')))
def formula(G, conds, eps_r=11.45, step_um=None, R_gaps=None, pairs=None, gap=None, screen_um=None, workers=1, max_core=8): F.dipole_far = same try: return PV.formula_as_dipole(G, conds, eps_r, step_um, R_gaps, pairs, gap, screen_um, workers, max_core) finally: F.dipole_far = cross
F.dipole_far, F.formula_prior = cross, formula
def undo(): F.dipole_far, F.formula_prior = saved return undo
def install_sentinel(F): """G4: any far-fill call raises.""" saved = (F.dipole_far, F.formula_prior)
def boom(*a, **k): raise RuntimeError('far fill called') F.dipole_far = F.formula_prior = boom
def undo(): F.dipole_far, F.formula_prior = saved return undo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Vectorised drop-in replacements for the H-matrix kernel of tlsq.embed.proxy (same mathematics, no per-row scipysparse slicing, no Python loop over image charges or ACA ranks). install() patches the loaded module in place."""import numpy as np
from ._tlsq.embed import proxy as P
_orig = {}
def _images(eps_r): P._image_correction(np.zeros(1), eps_r) key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) w, D = P._IMG_CACHE[key][2:] return np.asarray(w, float), np.asarray(D, float) ** 2
def _kernel_init(self, c, wh, eps_r, perm): _orig["Kernel.__init__"](self, c, wh, eps_r, perm) N = self.N.tocsr() N.sort_indices() self.indptr, self.indices, self.data = N.indptr, N.indices, N.data self.w, self.D2 = _images(eps_r) if self.img else (None, None)
def _corr(self, d): return np.sqrt((d * d)[..., None] + self.D2) ** -1 @ self.w
def _row(self, i, b0, b1): d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2) r = 1.0 / d if self.img: r += _corr(self, d) s, e = self.indptr[i], self.indptr[i + 1] if e > s: ix = self.indices[s:e] lo, hi = np.searchsorted(ix, (b0, b1)) if hi > lo: r[ix[lo:hi] - b0] += self.data[s + lo:s + hi] return r / self.k
def _block(self, a0, a1, b0, b1): 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) corr = _corr(self, d) if self.img else None if a0 == b0: d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0 A = 1.0 / d if corr is not None: A += corr s, e = self.indptr[a0], self.indptr[a1] if e > s: ix = self.indices[s:e] rr = np.repeat(np.arange(a1 - a0), np.diff(self.indptr[a0:a1 + 1])) m = (ix >= b0) & (ix < b1) np.add.at(A, (rr[m], ix[m] - b0), self.data[s:e][m]) return A / self.k
def _aca(K, a0, a1, b0, b1, eps, max_rank): m, n = a1 - a0, b1 - b0 R = min(m, n, max_rank) U, V = np.empty((m, R)), np.empty((n, R)) used_r, used_c = np.zeros(m, bool), np.zeros(n, bool) i, norm2, k = 0, 0.0, 0 for _ in range(R): r = K.row(a0 + i, b0, b1) if k: r -= V[:, :k] @ U[i, :k] rm = np.where(used_c, 0.0, np.abs(r)) j = int(np.argmax(rm)) if rm[j] == 0.0: break v = r / r[j] u = K.row(b0 + j, a0, a1) if k: u -= U[:, :k] @ V[j, :k] used_r[i], used_c[j] = True, True nu, nv = float(u @ u), float(v @ v) norm2 += nu * nv + (2 * float((U[:, :k].T @ u) @ (V[:, :k].T @ v)) if k else 0.0) U[:, k], V[:, k] = u, v k += 1 if nu * nv <= eps**2 * norm2: break um = np.where(used_r, 0.0, np.abs(u)) i = int(np.argmax(um)) if um[i] == 0.0: break else: return None return U[:, :k].copy(), V[:, :k].copy()
def _image_correction(d, eps_r, exact=False): if exact or P.SUBSTRATE["model"] == "halfspace": return _orig["image"](d, eps_r, exact) _orig["image"](np.zeros(1), eps_r) key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) du, T = P._IMG_CACHE[key][:2] u = np.asarray(d, float) / du j = np.minimum(u.astype(np.int64), len(T) - 2) f = u - j t0 = T[j] return t0 + f * (T[j + 1] - t0)
REFINE = dict(steps=6, tol=1e-13)
def _chol_solve(A, B): from scipy.linalg import cho_factor, cho_solve from scipy.linalg.blas import dsymm
try: cf = cho_factor(A.astype(np.float32, order="F"), lower=True, overwrite_a=True, check_finite=False) except np.linalg.LinAlgError: return _orig["chol_solve"](A, B) B = np.asfortranarray(B, dtype=float) X = cho_solve(cf, B.astype(np.float32), check_finite=False).astype(float) bn = np.linalg.norm(B, axis=0) for _ in range(REFINE["steps"]): R = B - dsymm(1.0, A, X, side=0, lower=1) if (np.linalg.norm(R, axis=0) <= REFINE["tol"] * bn).all(): return X X += cho_solve(cf, R.astype(np.float32), check_finite=False) return _orig["chol_solve"](A, B)
def install(dense_max=None, mixed=False): if not _orig: _orig["Kernel.__init__"] = P._Kernel.__init__ _orig.update(row=P._Kernel.row, block=P._Kernel.block, aca=P._aca, dense_max=P.DENSE_MAX, image=P._image_correction, chol_solve=P._chol_solve) P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = _kernel_init, _row, _block, _aca P._image_correction = _image_correction P._chol_solve = _chol_solve if mixed else _orig["chol_solve"] if dense_max is not None: P.DENSE_MAX = dense_max
def uninstall(): if _orig: P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = (_orig["Kernel.__init__"], _orig["row"], _orig["block"], _orig["aca"]) P._image_correction, P._chol_solve = _orig["image"], _orig["chol_solve"] P.DENSE_MAX = _orig["dense_max"] _orig.clear()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297"""fastprior_pkg: switchable speed components for the FROZEN physical prior of the P2d GNN (micro_mom_loc at ppg 1.5and 3, alpha 0.49685219816506904), installed by monkeypatching the loaded frozen vendor modules (never edited).
import fastprior_pkg as fp fp.install(mode="exact") # fv + parallel + hmat_vec (+ gpu if CUDA) (+ mixed if gated) fp.install(mode="exact_compiled") # exact + numba H-matrix operator (closer to the dense solve; VAL-tested, A5) fp.install(mode="certified") # exact + compiled + Rayleigh-Ritz solves with an error estimate (fp.certificates()) fp.install(components=["fv", "compiled"]) # explicit set fp.uninstall()
Components (protocol and gates: agents/fastprior_pkg/PROTOCOL.md; sources cited per section, code reused verbatimwhere possible, only module bindings changed): fv value-preserving rejection-tail fix of the windowed solve (rejtail; bit-identical) parallel forked window workers (the vendor's micro_mom(workers=k)); threads per worker limited (bit-identical) hmat_vec the frozen H-matrix PCG (> 12,000 panels) with a vectorised kernel, frozen tolerances (<= 1e-6) compiled numba H-matrix operator for the H-matrix PCG path: closer to the exact dense solve than the frozen H-matrix, but up to 1.4e-5 from it (fails strict parity; opt-in, used by certified) gpu dense assembly + Cholesky on CUDA (only when torch.cuda is available) mixed float32 Cholesky + float64 iterative refinement (only if gated, see MIXED_GATED) ritz Rayleigh-Ritz window / local solves (template start, tau 1e-3, dense <= 3,000 panels), certifiedParallel windows fork (the vendor's pool); on macOS they are always off (Accelerate is not fork-safe) and the priorruns serially. Environment: TLSQ_PRIOR_CPUS (CPUs; default cgroup / affinity aware), TLSQ_PRIOR_WORKERS (window workers; default =CPUs), TLSQ_PRIOR_MODE (default mode of install() without arguments).Value hook: install(..., value_patch=fn) with fn(F, P, FL) -> undo callable (e.g. a prior-v2 patch once it passes)."""from __future__ import annotations
import contextlibimport inspectimport jsonimport osimport sysimport tempfileimport time
import numpy as npfrom scipy.linalg import cho_factor, cho_solve, eigh
FROZEN_DENSE_MAX = 12000 # the frozen proxy.DENSE_MAX: decides which attempts the frozen code could not solve (fv)RITZ_CAL = 1.825367354114339 # varritz S0 calibration of the block-Jacobi estimate (s0_choice.json)MIXED_GATED = True # PROTOCOL.md G3 passed on Discovery x86 (A5): prior <= 4.4e-10, final matrix <= 4.5e-7COMPONENTS = ("fv", "parallel", "hmat_vec", "compiled", "gpu", "mixed", "ritz")CFG = dict(device="cuda", gpu_min=2000, gpu_dense_max=60000, rows=4096, ritz_tau=1e-3, ritz_maxit=12, ritz_dense_n=3000, ritz_start="tmpl", refine_steps=6, refine_tol=1e-13)STATE = dict(mode=None, components=(), cpus=1, workers=1, gpu=False, value_patch=None, target=None, parallel_off=None)F = P = FL = None # bound vendor modules: fastprior, proxy, fastprior_loc_ORIG: dict = {}_UNDO: list = []_PARENT = [0]_CHILD = [False]_TP: list = []STATS = dict(compiled_calls=0) # per-process countersLOG: list = [] # Ritz / exact solve records of the running prior call (certified mode)CERTS: list = [] # one certificate per micro_mom_loc call (certified mode)_CERT_FILE = [None]
# ------------------------------------------------------------------------------------------------ binding / CPUs
def bind(target="auto"): """Bind the frozen vendor modules: 'stage' (tlsq.embed of the geomfast stage), 'geomgnn' (the GNN Space bundle, geomgnn._tlsq.embed), or a tuple (fastprior, proxy, fastprior_loc). 'auto': whichever is loaded, else stage.""" global F, P, FL if isinstance(target, tuple): F, P, FL = target STATE["target"] = "modules" return F, P, FL if target == "auto": target = "geomgnn" if "geomgnn._tlsq.embed.fastprior" in sys.modules else "stage" if target == "stage" and "tlsq.embed.fastprior" not in sys.modules: try: import tlsq.embed.fastprior # noqa: F401 except ImportError: target = "geomgnn" if target == "geomgnn": from geomgnn._tlsq.embed import fastprior as F_, fastprior_loc as FL_, proxy as P_ else: from tlsq.embed import fastprior as F_, fastprior_loc as FL_, proxy as P_ F, P, FL = F_, P_, FL_ STATE["target"] = target return F, P, FL
def _cgroup_cpus(): """CPU quota of this process's cgroup (v2 cpu.max along the cgroup path, or v1 cfs quota / period); None if none.""" best = None try: lines = open("/proc/self/cgroup").read().splitlines() except OSError: lines = [] paths = [] for ln in lines: parts = ln.split(":", 2) if len(parts) == 3 and parts[0] == "0" and parts[1] == "": rel = parts[2].strip("/") segs = rel.split("/") if rel else [] for k in range(len(segs), -1, -1): paths.append(os.path.join("/sys/fs/cgroup", *segs[:k], "cpu.max")) paths.append("/sys/fs/cgroup/cpu.max") for p in paths: try: q, per = open(p).read().split()[:2] except (OSError, ValueError): continue if q != "max" and float(per) > 0: v = float(q) / float(per) best = v if best is None else min(best, v) for d in ("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpu,cpuacct"): try: q = int(open(f"{d}/cpu.cfs_quota_us").read()) per = int(open(f"{d}/cpu.cfs_period_us").read()) except (OSError, ValueError): continue if q > 0 and per > 0: best = q / per if best is None else min(best, q / per) return best
def detect_cpus() -> int: """CPUs this process may use: TLSQ_PRIOR_CPUS, else min(cgroup quota, affinity, os.cpu_count()).""" env = os.environ.get("TLSQ_PRIOR_CPUS") if env: return max(1, int(env)) cands = [os.cpu_count() or 1] q = _cgroup_cpus() if q: cands.append(max(1, int(q))) if hasattr(os, "sched_getaffinity"): cands.append(len(os.sched_getaffinity(0))) return max(1, min(cands))
def _set_threads(n: int) -> None: """Limit BLAS / OpenMP (threadpoolctl), numba and the vendor's thread pool to n threads in this process.""" try: from threadpoolctl import threadpool_limits _TP[:] = [threadpool_limits(n)] except Exception: # noqa: BLE001 (no threadpoolctl / Accelerate: env vars at process start decide) pass if P is not None: P.NUM_THREADS = n try: import numba numba.set_num_threads(max(1, min(n, numba.config.NUMBA_NUM_THREADS))) except Exception: # noqa: BLE001 pass
# ------------------------------------------------------------------------------------------------ fv# deploy/geomgnn/src/geomgnn/rejtail_fv.py (= scripts/rejtail/rt.py policy fv), keep_last_solved=True (frozen stage),# with the "doomed" test on the frozen DENSE_MAX (a GPU-raised DENSE_MAX must not change which attempts solve).
def _fv_solve(c, wh, o, metals, cols, eps_r): t = time.perf_counter() t_asm = 0.0 if len(c) <= P.DENSE_MAX: A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) t_asm = time.perf_counter() - t Bm = (o[:, None] == cols[None, :]).astype(float) Q = F._sym_solve(A, Bm) else: Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols] return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1), t_asm
def fv_window_solve(metals, n_core, h, budget, eps_r, all_rhs, levels=()): if all_rhs: return _ORIG["window_solve"](metals, n_core, h, budget, eps_r, all_rhs, levels) cols = np.arange(1, 1 + n_core) t_mesh = t_asm = t_sol = 0.0 hh, cap, refined, majority = h, budget, 0, False hist = [] while True: t = time.perf_counter() if not refined: c, wh, o, hh, n_raw = F._lite_mesh(metals, hh, cap, n_core, levels) elif levels: c, wh, o, hh, n_raw = F._graded_mesh(metals, n_core, hh, levels, majority) else: c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority) t_mesh += time.perf_counter() - t if not np.all(np.bincount(o, minlength=len(metals)) > 0): hist.append(("doomed",) if len(c) > FROZEN_DENSE_MAX else ("mesh", c, wh, o)) ok = False else: t = time.perf_counter() try: R, ta = _fv_solve(c, wh, o, metals, cols, eps_r) t_asm += ta hist.append(("R", R)) ok = True except np.linalg.LinAlgError: hist.append(("err",)) ok = False t_sol += time.perf_counter() - t if ok or majority: break if refined < F.LITE_REFINE: hh, cap, refined = hh / 2, np.inf, refined + 1 else: majority = True if ok: R = hist[-1][1] else: R = None t = time.perf_counter() for e in reversed(hist): if e[0] == "R": R = e[1] break if e[0] == "mesh": try: R = _fv_solve(e[1], e[2], e[3], metals, cols, eps_r)[0] break except np.linalg.LinAlgError: continue t_sol += time.perf_counter() - t assert R is not None, "no attempt solved (the frozen code raises here too)" return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, "assemble_s": t_asm, "solve_s": t_sol}
# ------------------------------------------------------------------------------------------------ parallel windows# The vendor's micro_mom(workers=k) (ProcessPoolExecutor, fork); windows inherit the layout through fastprior._LITE.
def _micro_mom(*args, **kw): ba = _ORIG["micro_mom_sig"].bind(*args, **kw) if sys.platform == "darwin": # never fork on macOS, whatever the caller asked for ba.arguments["workers"] = 1 if STATE["workers"] > 1 and ba.arguments.get("workers", 1) <= 1: ba.arguments["workers"] = STATE["workers"] _PARENT[0] = os.getpid() return _ORIG["micro_mom"](*ba.args, **ba.kwargs)
def _child_setup(): """First window job in a forked worker: threads per worker = CPUs // workers; CUDA is never used after fork.""" if _CHILD[0] or os.getpid() == _PARENT[0]: return _CHILD[0] = True nw = max(1, min(STATE["workers"], len(F._LITE.get("cores", [0])))) _set_threads(max(1, STATE["cpus"] // nw)) if STATE["gpu"]: STATE["gpu"] = False P.DENSE_MAX = FROZEN_DENSE_MAX
def _lite_job(k): _child_setup() if _CHILD[0] and _CERT_FILE[0]: i0 = len(LOG) out = _ORIG["lite_job"](k) recs = LOG[i0:] for r in recs: r["window"] = int(k) with open(_CERT_FILE[0], "a") as f: f.write("".join(json.dumps(_jsonable(r)) + "\n" for r in recs)) return out i0 = len(LOG) out = _ORIG["lite_job"](k) for r in LOG[i0:]: r["window"] = int(k) return out
def _jsonable(r): return {k: (v.tolist() if isinstance(v, np.ndarray) else (float(v) if isinstance(v, np.floating) else v)) for k, v in r.items()}
# ------------------------------------------------------------------------------------------------ compiled operator# scripts/varritz/hmat.py and scripts/varritz/fastop.py (numba H-matrix of the far kernel, exact near field, FFT image# term, block-Jacobi leaf factors on the frozen cluster tree); bodies verbatim, `P` bound late.
os.environ.setdefault("NUMBA_THREADING_LAYER", "workqueue") # fork-safe; GNU OpenMP aborts in forked window workerstry: import numba as nb nb.config.THREADING_LAYER = os.environ["NUMBA_THREADING_LAYER"]except ImportError: # compiled / ritz unavailable without numba nb = None
if nb is not None: @nb.njit(fastmath=True, cache=True) def _krow(x, y, i, b0, b1, out): for j in range(b0, b1): dx, dy = x[i] - x[j], y[i] - y[j] r2 = dx * dx + dy * dy out[j - b0] = 1.0 / np.sqrt(r2) if r2 > 0 else 0.0
@nb.njit(fastmath=True, cache=True) def _aca(x, y, a0, a1, b0, b1, eps, kmax, U, V): m, n = a1 - a0, b1 - b0 used_r = np.zeros(m, np.bool_) used_c = np.zeros(n, np.bool_) r = np.empty(n) u = np.empty(m) norm2 = 0.0 i = 0 k = 0 while k < min(m, n, kmax): _krow(x, y, a0 + i, b0, b1, r) for q in range(k): ui = U[i, q] for j in range(n): r[j] -= ui * V[j, q] used_r[i] = True jbest, vbest = -1, 0.0 for j in range(n): if not used_c[j] and abs(r[j]) > vbest: vbest, jbest = abs(r[j]), j if jbest < 0 or vbest == 0.0: return k piv = r[jbest] for j in range(n): V[j, k] = r[j] / piv _krow(x, y, b0 + jbest, a0, a1, u) for q in range(k): vj = V[jbest, q] for ii in range(m): u[ii] -= vj * U[ii, q] for ii in range(m): U[ii, k] = u[ii] used_c[jbest] = True nu, nv = 0.0, 0.0 for ii in range(m): nu += u[ii] * u[ii] for j in range(n): nv += V[j, k] * V[j, k] cross = 0.0 for q in range(k): su, sv = 0.0, 0.0 for ii in range(m): su += u[ii] * U[ii, q] for j in range(n): sv += V[j, k] * V[j, q] cross += su * sv norm2 += nu * nv + 2.0 * cross k += 1 if nu * nv <= eps * eps * norm2: return k ibest, ub = -1, 0.0 for ii in range(m): if not used_r[ii] and abs(u[ii]) > ub: ub, ibest = abs(u[ii]), ii if ibest < 0: return k i = ibest return -1 if k >= kmax and k < min(m, n) else k
@nb.njit(parallel=True, cache=True) def _build(x, y, lows, eps, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata): nl = lows.shape[0] for b in nb.prange(nl): a0, a1, b0, b1 = lows[b, 0], lows[b, 1], lows[b, 2], lows[b, 3] m, n = a1 - a0, b1 - b0 U = Ubuf[uoff[b]:uoff[b] + m * kmax].reshape(m, kmax) V = Vbuf[voff[b]:voff[b] + n * kmax].reshape(n, kmax) ranks[b] = _aca(x, y, a0, a1, b0, b1, eps, kmax, U, V) nd = dense.shape[0] for b in nb.prange(nd): a0, a1, b0, b1 = dense[b, 0], dense[b, 1], dense[b, 2], dense[b, 3] n = b1 - b0 row = np.empty(n) for i in range(a0, a1): _krow(x, y, i, b0, b1, row) ddata[doff[b] + (i - a0) * n:doff[b] + (i - a0 + 1) * n] = row
@nb.njit(parallel=True, cache=True) def _apply(X, lows, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata, nthr, Y): n, mc = X.shape buf = np.zeros((nthr, n, mc)) nl = lows.shape[0] nd = dense.shape[0] tot = nl + nd for t in nb.prange(nthr): B = buf[t] for b in range(t, tot, nthr): if b < nl: a0, a1, b0, b1 = lows[b, 0], lows[b, 1], lows[b, 2], lows[b, 3] m, nn = a1 - a0, b1 - b0 k = ranks[b] U = Ubuf[uoff[b]:uoff[b] + m * kmax].reshape(m, kmax)[:, :k] V = Vbuf[voff[b]:voff[b] + nn * kmax].reshape(nn, kmax)[:, :k] B[a0:a1] += U @ (V.T @ X[b0:b1]) B[b0:b1] += V @ (U.T @ X[a0:a1]) else: q = b - nl a0, a1, b0, b1 = dense[q, 0], dense[q, 1], dense[q, 2], dense[q, 3] D = ddata[doff[q]:doff[q] + (a1 - a0) * (b1 - b0)].reshape(a1 - a0, b1 - b0) B[a0:a1] += D @ X[b0:b1] if a0 != b0: B[b0:b1] += D.T @ X[a0:a1] for i in nb.prange(n): for c in range(mc): s = 0.0 for t in range(nthr): s += buf[t, i, c] Y[i, c] = s
@nb.njit(parallel=True, fastmath=True, cache=True) def _far(x, y, Xt, Y, T=64): m, n = Xt.shape nt = (n + T - 1) // T for it in nb.prange(nt): r = np.empty(n) for i in range(it * T, min(n, it * T + T)): xi, yi = x[i], y[i] for j in range(n): dx, dy = xi - x[j], yi - y[j] r[j] = dx * dx + dy * dy r[i] = 1.0 for j in range(n): r[j] = 1.0 / np.sqrt(r[j]) r[i] = 0.0 for k in range(m): s = 0.0 for j in range(n): s += r[j] * Xt[k, j] Y[i, k] = s
def _numba(): if nb is None: raise ImportError("numba is required for the compiled / ritz components") return dict(nb=nb, build=_build, apply=_apply, far=_far)
class HFar: """Far kernel sum_{j != i} x_j / d_ij as an H-matrix (frozen block plan: leaf 128, eta 2). (varritz/hmat.py)"""
def __init__(self, c, leaf=128, eta=2.0, eps=1e-7, kmax=48, nthr=None): K = _numba() self.perm, nodes = P._cluster_tree(c, leaf) self.x, self.y = np.ascontiguousarray(c[self.perm, 0]), np.ascontiguousarray(c[self.perm, 1]) plan_l, plan_d = [], []
def leafq(k): return nodes[k][4] < 0
def rec(s, t): a0, a1, lo_s, hi_s, sl, sr = nodes[s] b0, b1, lo_t, hi_t, tl, tr = nodes[t] if s == t: if leafq(s): plan_d.append((a0, a1, a0, a1)) else: rec(sl, sl), rec(sr, sr), rec(sl, sr) return gap = np.maximum(0.0, np.maximum(lo_s - hi_t, lo_t - hi_s)) diam = min(np.sqrt(((hi_s - lo_s) ** 2).sum()), np.sqrt(((hi_t - lo_t) ** 2).sum())) if diam <= eta * np.sqrt((gap**2).sum()): plan_l.append((a0, a1, b0, b1)) elif leafq(s) and leafq(t): plan_d.append((a0, a1, b0, b1)) elif leafq(s): rec(s, tl), rec(s, tr) elif leafq(t): rec(sl, t), rec(sr, t) else: for u in (sl, sr): for v in (tl, tr): rec(u, v)
rec(0, 0) lows = np.array(plan_l, np.int64).reshape(-1, 4) dense = np.array(plan_d, np.int64).reshape(-1, 4) m = lows[:, 1] - lows[:, 0] nn = lows[:, 3] - lows[:, 2] uoff = np.r_[0, np.cumsum(m * kmax)][:-1] voff = np.r_[0, np.cumsum(nn * kmax)][:-1] Ubuf, Vbuf = np.zeros(int((m * kmax).sum())), np.zeros(int((nn * kmax).sum())) dsz = (dense[:, 1] - dense[:, 0]) * (dense[:, 3] - dense[:, 2]) doff = np.r_[0, np.cumsum(dsz)][:-1] ddata = np.zeros(int(dsz.sum())) ranks = np.zeros(len(lows), np.int64) K["build"](self.x, self.y, lows, eps, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata) bad = ranks < 0 if bad.any(): # rank above kmax: these blocks become dense extra = lows[bad] lows = lows[~bad] keep_u, keep_v = uoff[~bad], voff[~bad] ranks = ranks[~bad] uoff, voff = keep_u, keep_v esz = (extra[:, 1] - extra[:, 0]) * (extra[:, 3] - extra[:, 2]) eoff = np.r_[0, np.cumsum(esz)][:-1] edata = np.zeros(int(esz.sum())) K["build"](self.x, self.y, np.zeros((0, 4), np.int64), eps, kmax, Ubuf, Vbuf, uoff[:0], voff[:0], ranks[:0], extra, eoff, edata) doff = np.r_[doff, eoff + len(ddata)] ddata = np.r_[ddata, edata] dense = np.r_[dense, extra] self.args = (lows, kmax, Ubuf, Vbuf, uoff, voff, ranks, dense, doff, ddata) self.nthr = nthr or K["nb"].get_num_threads() self.n_low, self.n_dense, self.mean_rank = len(lows), len(dense), float(ranks.mean()) if len(ranks) else 0.0 self.n_converted = int(bad.sum())
def __call__(self, X): Xp = np.ascontiguousarray(X[self.perm]) Yp = np.empty_like(Xp) _numba()["apply"](Xp, *self.args, self.nthr, Yp) Y = np.empty_like(Yp) Y[self.perm] = Yp return Y
def _lagrange(u, q): i0 = np.floor(u).astype(np.int64) - (q // 2 - 1) t = u - i0 w = np.ones((len(u), q)) for a in range(q): for b in range(q): if a != b: w[:, a] *= (t - b) / (a - b) return i0, w
class ImageConv: """Smooth finite-substrate image kernel (proxy._image_correction, exact series) by grid convolution. (fastop.py)"""
def __init__(self, c, eps_r, spacing_frac=1 / 16, q=6): from scipy.sparse import csr_matrix P._image_correction(np.zeros(1), eps_r) key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) _, _, w, D = P._IMG_CACHE[key] self.w, self.D = w, D h = spacing_frac * D.min() lo = c.min(0) - (q // 2 + 1) * h u = (c - lo) / h ix0, wx = _lagrange(u[:, 0], q) iy0, wy = _lagrange(u[:, 1], q) nx, ny = int(ix0.max()) + q + 1, int(iy0.max()) + q + 1 rows = np.repeat(np.arange(len(c)), q * q) gx = (ix0[:, None, None] + np.arange(q)[None, :, None]) * np.ones((1, 1, q), np.int64) gy = (iy0[:, None, None] + np.arange(q)[None, None, :]) * np.ones((1, q, 1), np.int64) vals = (wx[:, :, None] * wy[:, None, :]).ravel() self.W = csr_matrix((vals, (rows, (gx * ny + gy).ravel())), shape=(len(c), nx * ny)) self.nx, self.ny = nx, ny Lx, Ly = 2 * nx, 2 * ny ax = np.minimum(np.arange(Lx), Lx - np.arange(Lx)) * h ay = np.minimum(np.arange(Ly), Ly - np.arange(Ly)) * h rho = np.sqrt(ax[:, None] ** 2 + ay[None, :] ** 2) Kk = sum(wn / np.sqrt(rho**2 + Dn * Dn) for wn, Dn in zip(w, D)) self.Kf = np.fft.rfft2(Kk) self.L = (Lx, Ly)
def __call__(self, X): G = (self.W.T @ X).reshape(self.nx, self.ny, -1) out = np.empty((self.nx * self.ny, X.shape[1])) for k in range(X.shape[1]): f = np.fft.irfft2(np.fft.rfft2(G[:, :, k], s=self.L) * self.Kf, s=self.L)[: self.nx, : self.ny] out[:, k] = f.ravel() return self.W @ out
class FastOp: """The frozen panel operator, matrix-free; bj(): block-Jacobi on the frozen cluster tree's leaves. (fastop.py)"""
def __init__(self, c, wh, o, eps_r, M, leaf=128, h_min_n=4000, h_eps=1e-8): from scipy.sparse import csr_matrix t = time.perf_counter() self.H = None if len(c) >= h_min_n: self.H = HFar(c, eps=h_eps) self.t_hmat = time.perf_counter() - t t = time.perf_counter() self.c, self.wh, self.o, self.n, self.M = c, wh, o, len(c), M self.B = (o[:, None] == np.arange(M)[None]).astype(float) self.k = 4 * np.pi * P.EPS0_FF_PER_UM * (eps_r + 1) / 2 self.x, self.y = np.ascontiguousarray(c[:, 0]), np.ascontiguousarray(c[:, 1]) ii, jj = P._near_pairs(c, wh.max(1)) d = np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)) near = 0.5 * (P.rect_potential(c[ii], c[jj], wh[jj]) + P.rect_potential(c[jj], c[ii], wh[ii])) - 1.0 / d dg = P.rect_self(wh[:, 0], wh[:, 1]) n = self.n self.N = csr_matrix((np.r_[near, near, dg], (np.r_[ii, jj, np.arange(n)], np.r_[jj, ii, np.arange(n)])), shape=(n, n)) self.t_near = time.perf_counter() - t t = time.perf_counter() self.img = ImageConv(c, eps_r) if P._image_correction(np.zeros(1), eps_r) is not None else None self.t_img = time.perf_counter() - t t = time.perf_counter() perm, nodes = P._cluster_tree(c, leaf) self.leaves = [] img0 = P._image_correction for a0, a1, lo, hi, l, r in nodes: if l >= 0: continue ix = np.sort(perm[a0:a1]) cc = c[ix] dd = np.sqrt(((cc[:, None] - cc[None]) ** 2).sum(-1)) np.fill_diagonal(dd, 1.0) A = 1.0 / dd np.fill_diagonal(A, 0.0) A += self.N[ix][:, ix].toarray() if self.img is not None: np.fill_diagonal(dd, 0.0) A += img0(dd, eps_r, exact=True) self.leaves.append((ix, cho_factor(A / self.k, lower=True))) self.t_blocks = time.perf_counter() - t
def matvec(self, X): X = np.ascontiguousarray(X, dtype=np.float64) if self.H is not None: Y = self.H(X) else: Y = np.empty_like(X) _numba()["far"](self.x, self.y, np.ascontiguousarray(X.T), Y) Y += self.N @ X if self.img is not None: Y += self.img(X) return Y / self.k
def bj(self, R): Z = np.zeros_like(R) for ix, cf in self.leaves: Z[ix] = cho_solve(cf, R[ix], check_finite=False) return Z
def compiled_pcg(c, wh, o, n_metals, eps_r): """Panel charges (n, n_metals) by the frozen block-Jacobi PCG (proxy._HMatrix.pcg: all columns, stop when every column's relative residual < HMAT tol, LinAlgError after maxit) on the compiled operator. A zero right-hand-side column (a metal without panels) gives residual 0/0 = NaN forever, so it raises at once instead of after maxit.""" STATS["compiled_calls"] += 1 B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float) bn = np.sqrt((B * B).sum(0)) if not np.all(bn > 0): raise np.linalg.LinAlgError("H-matrix PCG: a metal without panels (zero right-hand side; frozen: NaN residual)") op = FastOp(c, wh, o, eps_r, n_metals, h_eps=P.HMAT["eps"]) tol, maxit = P.HMAT["tol"], P.HMAT["maxit"] X, R = np.zeros_like(B), B.copy() Z = op.bj(R) Pd, rz = Z.copy(), (R * Z).sum(0) res = np.inf for it in range(maxit): AP = op.matvec(Pd) al = rz / (Pd * AP).sum(0) X += al * Pd R -= al * AP res = (np.sqrt((R * R).sum(0)) / bn).max() if res < tol: return X if not np.isfinite(res): break Z = op.bj(R) rzn = (R * Z).sum(0) Pd = Z + (rzn / rz) * Pd rz = rzn raise np.linalg.LinAlgError(f"compiled H-matrix PCG did not converge (residual {res:.1e})")
def _mom_solve_fast(c, wh, o, n_metals, eps_r=11.45, dense_max=None): n = len(c) if n <= (P.DENSE_MAX if dense_max is None else dense_max) or "compiled" not in STATE["components"]: return _ORIG["mom_solve_fast"](c, wh, o, n_metals, eps_r, dense_max) return compiled_pcg(c, wh, o, n_metals, eps_r)
# ------------------------------------------------------------------------------------------------ hmat_vec (fastmom.py)# scripts/geomfast/fastmom.py: the frozen H-matrix (same cluster tree, ACA, block-Jacobi PCG, FROZEN tolerances) with a# vectorised kernel (no per-row scipy sparse slicing, no Python loop over image charges or ACA ranks). Only the H-matrix# kernel is patched (proxy._image_correction and the dense path are untouched).
def _hv_images(eps_r): P._image_correction(np.zeros(1), eps_r) key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) w, D = P._IMG_CACHE[key][2:] return np.asarray(w, float), np.asarray(D, float) ** 2
def _hv_kernel_init(self, c, wh, eps_r, perm): _ORIG["Kernel.__init__"](self, c, wh, eps_r, perm) N = self.N.tocsr() N.sort_indices() self.indptr, self.indices, self.data = N.indptr, N.indices, N.data self.w, self.D2 = _hv_images(eps_r) if self.img else (None, None)
def _hv_corr(self, d): return np.sqrt((d * d)[..., None] + self.D2) ** -1 @ self.w
def _hv_row(self, i, b0, b1): d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2) r = 1.0 / d if self.img: r += _hv_corr(self, d) s, e = self.indptr[i], self.indptr[i + 1] if e > s: ix = self.indices[s:e] lo, hi = np.searchsorted(ix, (b0, b1)) if hi > lo: r[ix[lo:hi] - b0] += self.data[s + lo:s + hi] return r / self.k
def _hv_block(self, a0, a1, b0, b1): 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) corr = _hv_corr(self, d) if self.img else None if a0 == b0: d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0 A = 1.0 / d if corr is not None: A += corr s, e = self.indptr[a0], self.indptr[a1] if e > s: ix = self.indices[s:e] rr = np.repeat(np.arange(a1 - a0), np.diff(self.indptr[a0:a1 + 1])) m = (ix >= b0) & (ix < b1) np.add.at(A, (rr[m], ix[m] - b0), self.data[s:e][m]) return A / self.k
def _hv_aca(K, a0, a1, b0, b1, eps, max_rank): m, n = a1 - a0, b1 - b0 R = min(m, n, max_rank) U, V = np.empty((m, R)), np.empty((n, R)) used_r, used_c = np.zeros(m, bool), np.zeros(n, bool) i, norm2, k = 0, 0.0, 0 for _ in range(R): r = K.row(a0 + i, b0, b1) if k: r -= V[:, :k] @ U[i, :k] rm = np.where(used_c, 0.0, np.abs(r)) j = int(np.argmax(rm)) if rm[j] == 0.0: break v = r / r[j] u = K.row(b0 + j, a0, a1) if k: u -= U[:, :k] @ V[j, :k] used_r[i], used_c[j] = True, True nu, nv = float(u @ u), float(v @ v) norm2 += nu * nv + (2 * float((U[:, :k].T @ u) @ (V[:, :k].T @ v)) if k else 0.0) U[:, k], V[:, k] = u, v k += 1 if nu * nv <= eps**2 * norm2: break um = np.where(used_r, 0.0, np.abs(u)) i = int(np.argmax(um)) if um[i] == 0.0: break else: return None return U[:, :k].copy(), V[:, :k].copy()
def _hv_mom_solve_fast(c, wh, o, n_metals, eps_r=11.45, dense_max=None): """The frozen mom_solve_fast (vectorised kernel); a zero right-hand-side column raises at once (frozen: after maxit).""" if len(c) > (P.DENSE_MAX if dense_max is None else dense_max) and not np.all(np.bincount(o, minlength=n_metals) > 0): raise np.linalg.LinAlgError("H-matrix PCG: a metal without panels (zero right-hand side; frozen: NaN residual)") return _ORIG["mom_solve_fast"](c, wh, o, n_metals, eps_r, dense_max)
# ------------------------------------------------------------------------------------------------ gpu (fastgpu.py)
class _Dev: def __init__(self, t): self.t = t
def _gpu_assemble(c, wh, diag, eps_r, near): n = len(c) if not STATE["gpu"] or n < CFG["gpu_min"]: return _ORIG["assemble"](c, wh, diag, eps_r, near) import torch dev = CFG["device"] k = 4 * np.pi * P.EPS0_FF_PER_UM * (eps_r + 1) / 2 img = P._image_correction(np.zeros(1), eps_r) is not None if img: key = (P.SUBSTRATE["model"], float(P.SUBSTRATE["t_um"]), float(eps_r)) du, T = P._IMG_CACHE[key][:2] T = torch.as_tensor(T, dtype=torch.float64, device=dev) x = torch.as_tensor(c[:, 0], dtype=torch.float64, device=dev) y = torch.as_tensor(c[:, 1], dtype=torch.float64, device=dev) A = torch.empty((n, n), dtype=torch.float64, device=dev) for r0 in range(0, n, CFG["rows"]): r1 = min(r0 + CFG["rows"], n) d = torch.sqrt((x[r0:r1, None] - x[None, :]) ** 2 + (y[r0:r1, None] - y[None, :]) ** 2) if img: u = d / du j = torch.clamp(u.floor().long(), 0, len(T) - 2) f = u - j corr = T[j] + f * (T[j + 1] - T[j]) d[torch.arange(r1 - r0, device=dev), torch.arange(r0, r1, device=dev)] = 1.0 blk = 1.0 / d if img: blk += corr A[r0:r1] = blk / k ii, jj = P._near_pairs(c, wh.max(1)) if len(ii): v = 0.5 * (near(c[ii], c[jj], wh[jj]) + near(c[jj], c[ii], wh[ii])) / k if img: v = v + P._image_correction(np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)), eps_r) / k vi = torch.as_tensor(v, dtype=torch.float64, device=dev) ti, tj = torch.as_tensor(ii, device=dev), torch.as_tensor(jj, device=dev) A[ti, tj] = vi A[tj, ti] = vi dg = diag / k if not img else (diag + P._image_correction(np.zeros(1), eps_r)[0]) / k A[torch.arange(n, device=dev), torch.arange(n, device=dev)] = torch.as_tensor(dg, dtype=torch.float64, device=dev) return _Dev(A)
def _gpu_chol(A, B): import torch L, info = torch.linalg.cholesky_ex(A.t) if int(info) > 0: raise np.linalg.LinAlgError("not positive definite (device Cholesky)") Bt = torch.as_tensor(np.ascontiguousarray(B), dtype=torch.float64, device=A.t.device) X = torch.cholesky_solve(Bt, L).cpu().numpy() A.t = None # the matrix is not used after a successful solve: release it and the allocator cache (shared GPU) del L, Bt torch.cuda.empty_cache() return X
# ------------------------------------------------------------------------------------------------ mixed (fastmom.py)
def _mixed_chol(A, B): from scipy.linalg.blas import dsymm try: cf = cho_factor(A.astype(np.float32, order="F"), lower=True, overwrite_a=True, check_finite=False) except np.linalg.LinAlgError: return _ORIG["chol_solve"](A.copy(order="F"), B) B = np.asfortranarray(B, dtype=float) X = cho_solve(cf, B.astype(np.float32), check_finite=False).astype(float) bn = np.linalg.norm(B, axis=0) for _ in range(CFG["refine_steps"]): R = B - dsymm(1.0, A, X, side=0, lower=1) if (np.linalg.norm(R, axis=0) <= CFG["refine_tol"] * bn).all(): return X X += cho_solve(cf, R.astype(np.float32), check_finite=False) return _ORIG["chol_solve"](A.copy(order="F"), B)
def _chol_solve(A, B): if isinstance(A, _Dev): return _gpu_chol(A, B) if "mixed" in STATE["components"]: return _mixed_chol(A, B) return _ORIG["chol_solve"](A, B)
def _sym_solve(A, B): if not isinstance(A, _Dev): if "mixed" not in STATE["components"]: return _ORIG["sym_solve"](A, B) try: # = _ORIG["sym_solve"] without its copy of A: _mixed_chol only reads A (its float64 fallbacks copy it) return _mixed_chol(A, B) except np.linalg.LinAlgError: from scipy.linalg import solve return solve(A, B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False) if A.t.shape[0] > FROZEN_DENSE_MAX: return _gpu_chol(A, B) try: return _gpu_chol(A, B) except np.linalg.LinAlgError: from scipy.linalg import solve return solve(A.t.cpu().numpy(), B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False)
# ------------------------------------------------------------------------------------------------ ritz (certified)# scripts/varritz/vr.py (templates, Ritz) and scripts/varritz/ritzprior.py (window / local loops, A5 dense dispatch).
def edge_geometry(metals, c, wh, o): import shapely n, M = len(c), len(metals) d, a, g = np.zeros(n), np.zeros(n), np.zeros(n) D = np.zeros((n, M)) pts = shapely.points(c) for k in range(M): ix = np.nonzero(o == k)[0] if not len(ix): continue bd = metals[k].boundary shapely.prepare(bd) ln = shapely.shortest_line(pts[ix], bd) xy = shapely.get_coordinates(ln).reshape(-1, 2, 2) v = xy[:, 0] - xy[:, 1] dk = np.sqrt((v**2).sum(1)) nv = np.where(dk[:, None] > 0, v / np.maximum(dk, 1e-300)[:, None], 0.7071) d[ix], a[ix] = dk, np.abs(nv[:, 0]) * wh[ix, 0] + np.abs(nv[:, 1]) * wh[ix, 1] others = shapely.union_all([metals[j] for j in range(M) if j != k]) shapely.prepare(others) g[ix] = shapely.distance(shapely.points(xy[:, 1]), others) for j in range(M): shapely.prepare(metals[j]) D[:, j] = shapely.distance(pts, metals[j]) return d, a, np.maximum(g, 1e-9), D
def templates(d, a, g): lo, hi = np.maximum(d - a / 2, 0.0), d + a / 2 w = np.maximum(hi - lo, 1e-12) s = 2 * (np.sqrt(hi) - np.sqrt(lo)) / w gg = 2 * (np.arcsinh(np.sqrt(hi / g)) - np.arcsinh(np.sqrt(lo / g))) / w return {"u": np.ones_like(d), "s": s, "g": gg}
def _orth_blocks(V, o, M): out = [] for k in range(M): ix = np.nonzero(o == k)[0] cols = np.nonzero(np.abs(V[ix]).sum(0) > 0)[0] if not len(cols): continue Vk = V[np.ix_(ix, cols)] Vk = Vk / np.maximum(np.linalg.norm(Vk, axis=0), 1e-300) U, s, _ = np.linalg.svd(Vk, full_matrices=False) keep = s > 1e-10 * s[0] W = np.zeros((len(o), int(keep.sum()))) W[ix] = U[:, keep] out.append(W) return np.hstack(out)
def ritz(V, PV, B): G = V.T @ PV G = 0.5 * (G + G.T) Fm = V.T @ B try: Y = cho_solve(cho_factor(G, lower=True), Fm) except np.linalg.LinAlgError: lam, U = eigh(G) keep = lam > 1e-13 * lam.max() Y = U[:, keep] @ ((U[:, keep].T @ Fm) / lam[keep, None]) CV = Fm.T @ Y return 0.5 * (CV + CV.T), Y, B - PV @ Y
def start_basis(metals, c, wh, o, kind, op, B): M = len(metals) if kind == "pcg": Z = op.bj(B) return Z / np.maximum(np.linalg.norm(Z, axis=0), 1e-300) area = wh[:, 0] * wh[:, 1] d, a, g, _ = edge_geometry(metals, c, wh, o) T = templates(d, a, g) return _orth_blocks(np.hstack([np.where((o == k)[:, None], (T[nm] * area)[:, None], 0.0) for k in range(M) for nm in "usg"]), o, M)
def criterion(CV, est, floor=0.1): e = np.sqrt(np.maximum(np.diag(est), 0.0)) return float(np.max(np.outer(e, e) / np.maximum(np.abs(CV), floor)))
def ritz_solve(metals, c, wh, o, eps_r, cols): tau, start, maxit = CFG["ritz_tau"], CFG["ritz_start"], CFG["ritz_maxit"] t0 = time.perf_counter() op = FastOp(c, wh, o, eps_r, len(metals)) B = op.B V = start_basis(metals, c, wh, o, start, op, B) PV = op.matvec(V) for m in range(maxit + 1): CV, Y, R = ritz(V, PV, B) est = R.T @ op.bj(R) rel = criterion(CV, est) if rel <= tau or m == maxit: break Z = op.bj(R) Z /= np.maximum(np.linalg.norm(Z, axis=0), 1e-300) V, PV = np.hstack([V, Z]), np.hstack([PV, op.matvec(Z)]) info = dict(n=len(c), steps=m, converged=rel <= tau, est_rel=rel, est_diag=np.diag(est).tolist(), k=V.shape[1], t=time.perf_counter() - t0) return (V @ Y)[:, np.asarray(cols)], info
def _frozen_solve(c, wh, o, eps_r, cols, all_rhs, n_metals): if len(c) <= P.DENSE_MAX: A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) Bm = (o[:, None] == cols[None, :]).astype(float) return P._chol_solve(A, Bm) if all_rhs else F._sym_solve(A, Bm) return P.mom_solve_fast(c, wh, o, n_metals, eps_r)[:, cols]
def _ritz_dense_n(): return max(CFG["ritz_dense_n"], CFG["gpu_dense_max"] if STATE["gpu"] else 0)
def _solve_mesh(metals, c, wh, o, eps_r, cols, all_rhs, kind): if len(c) <= _ritz_dense_n(): # A5 (and the GPU): exact solve, estimate 0 Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) LOG.append(dict(kind=kind, ritz=None, exact=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) try: Q, info = ritz_solve(metals, c, wh, o, eps_r, cols) rec = dict(kind=kind, ritz=bool(info["converged"]), exact=False, **info) if not info["converged"]: raise np.linalg.LinAlgError("ritz not converged") except np.linalg.LinAlgError: LOG.append(dict(kind=kind, ritz=False, exact=True, fallback=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) LOG.append(rec) return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1)
def _last_good(R, ok, skipped, metals, eps_r, cols, all_rhs): if R is not None and (ok or not np.isnan(R).any()): return R for c, wh, o in reversed(skipped): try: Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) LOG.append(dict(kind="last_good", ritz=None, exact=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1) except np.linalg.LinAlgError: continue raise np.linalg.LinAlgError("no successful solve in the refinement sequence")
def _final_unpanelled(metals, c, wh, o, eps_r, cols, all_rhs): """Final majority mesh still missing a metal: the frozen solve (doomed above the frozen DENSE_MAX: it raises).""" if len(c) > FROZEN_DENSE_MAX: raise np.linalg.LinAlgError("final mesh misses a metal above DENSE_MAX (frozen: NaN PCG)") Q = _frozen_solve(c, wh, o, eps_r, cols, all_rhs, len(metals)) LOG.append(dict(kind="window", ritz=None, exact=True, steps=0, n=len(c), est_rel=0.0, est_diag=[0.0] * len(metals))) return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1)
def ritz_window_solve(metals, n_core, h, budget, eps_r, all_rhs, levels=()): cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core) t_mesh = t_sol = 0.0 hh, cap, refined, majority = h, budget, 0, False skipped, R = [], None while True: t = time.perf_counter() if not refined: c, wh, o, hh, n_raw = F._lite_mesh(metals, hh, cap, n_core, levels) elif levels: c, wh, o, hh, n_raw = F._graded_mesh(metals, n_core, hh, levels, majority) else: c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority) t_mesh += time.perf_counter() - t t = time.perf_counter() full = bool(np.all(np.bincount(o, minlength=len(metals)) > 0)) if not full and not majority: skipped.append((c, wh, o)) if refined < F.LITE_REFINE: hh, cap, refined = hh / 2, np.inf, refined + 1 else: majority = True continue try: if not full: R = _final_unpanelled(metals, c, wh, o, eps_r, cols, all_rhs) else: R = _solve_mesh(metals, c, wh, o, eps_r, cols, all_rhs, "window") off = np.ones(R.shape, bool) off[np.arange(len(cols)), cols] = False ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0))) except np.linalg.LinAlgError: ok = False t_sol += time.perf_counter() - t if LOG: LOG[-1].update(accepted=ok, refined=refined) if ok or majority: break if refined < F.LITE_REFINE: hh, cap, refined = hh / 2, np.inf, refined + 1 else: majority = True R = _last_good(R, ok, skipped, metals, eps_r, cols, all_rhs) return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, "assemble_s": 0.0, "solve_s": t_sol}
def ritz_loc_solve(metals, H, h_floor, ppg, eps_r): t_mesh = t_sol = 0.0 cols = np.arange(len(metals)) refined, majority = 0, False skipped, R = [], None while True: t = time.perf_counter() c, wh, o, n_raw = FL.mesh_local(metals, H, h_floor, ppg, majority) t_mesh += time.perf_counter() - t t = time.perf_counter() full = bool(np.all(np.bincount(o, minlength=len(metals)) > 0)) if not full and not majority: skipped.append((c, wh, o)) if refined < F.LITE_REFINE: H, h_floor, refined = H / 2, h_floor / 2, refined + 1 else: majority = True continue try: if not full: R = _final_unpanelled(metals, c, wh, o, eps_r, cols, True) else: R = _solve_mesh(metals, c, wh, o, eps_r, cols, True, "local") off = ~np.eye(len(metals), dtype=bool) ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and np.all(R[off] < 0)) except np.linalg.LinAlgError: ok = False t_sol += time.perf_counter() - t if LOG: LOG[-1].update(accepted=ok, refined=refined) if ok or majority: break if refined < F.LITE_REFINE: H, h_floor, refined = H / 2, h_floor / 2, refined + 1 else: majority = True R = _last_good(R, ok, skipped, metals, eps_r, cols, True) return R, {"H_um": H, "h_floor_um": h_floor, "h_min_um": float(wh.min()), "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, "solve_s": t_sol}
def _micro_mom_loc(G, conds, eps_r=11.45, ppg=3.0, *args, **kw): """micro_mom_loc + a certificate (certified mode). Window records of forked workers come back through a file.""" LOG.clear() fd, path = tempfile.mkstemp(prefix="fp_cert_", suffix=".jsonl") os.close(fd) _CERT_FILE[0] = path try: out = _ORIG["micro_mom_loc"](G, conds, eps_r, ppg, *args, **kw) with open(path) as f: LOG.extend(json.loads(ln) for ln in f if ln.strip()) finally: _CERT_FILE[0] = None os.unlink(path) CERTS.append(_certificate(G, conds, out[0], list(LOG), ppg)) return out
def _certificate(G, conds, C, recs, ppg): """Calibrated estimate (c = RITZ_CAL) of the prior's solver error: max relative entry error (0.1 fF floor) over the accepted solves; per-entry fF estimates c sqrt(e_i e_j) for a single-window single-frame layout (input order). Self entries of Ritz solves are lower bounds of the exact ones.""" acc = [r for r in recs if r.get("accepted", True) and "est_rel" in r] cert = dict(ppg=ppg, n_solves=len(recs), n_ritz=sum(bool(r.get("ritz")) for r in recs), n_exact=sum(bool(r.get("exact")) for r in recs), n_fallback=sum(bool(r.get("fallback")) for r in recs), max_rel_est=RITZ_CAL * max((r["est_rel"] for r in acc), default=0.0), calibration=RITZ_CAL, windows=[dict(window=r.get("window"), n=r["n"], ritz=bool(r.get("ritz")), max_rel_est=RITZ_CAL * r["est_rel"]) for r in acc], entry_est_fF=None) if len(acc) == 1 and len(conds) <= 8: frames = F.canonical_frames(G, conds) e = np.maximum(np.asarray(acc[0]["est_diag"], float), 0.0) if len(frames) == 1 and len(e) == len(conds) + 1: inv = np.r_[0, np.argsort(frames[0][2]) + 1] ei = e[inv] cert["entry_est_fF"] = (RITZ_CAL * np.sqrt(np.outer(ei, ei))).tolist() return cert
def certificates(clear=True) -> list: out = list(CERTS) if clear: CERTS.clear() return out
# ------------------------------------------------------------------------------------------------ install
def _gpu_available() -> bool: try: import torch return bool(torch.cuda.is_available()) except Exception: # noqa: BLE001 return False
def resolve(mode=None, components=None) -> tuple: if components is not None: bad = set(components) - set(COMPONENTS) if bad: raise ValueError(f"unknown components {sorted(bad)}; known {COMPONENTS}") return tuple(c for c in COMPONENTS if c in components) mode = mode or os.environ.get("TLSQ_PRIOR_MODE", "exact") if mode not in ("exact", "exact_compiled", "certified", "frozen"): raise ValueError(f"mode {mode!r}") if mode == "frozen": return () comps = ["fv", "parallel", "hmat_vec"] if _gpu_available(): comps.append("gpu") if MIXED_GATED: comps.append("mixed") if mode in ("exact_compiled", "certified"): comps.append("compiled") if mode == "certified": comps.append("ritz") return tuple(c for c in COMPONENTS if c in comps)
def install(mode=None, components=None, workers=None, cpus=None, target="auto", blas_threads="auto", value_patch=None, warm=True, **cfg): """Install the components (mode 'exact' / 'certified' / 'frozen', or an explicit component list) on the frozen vendor modules. workers: window workers (default TLSQ_PRIOR_WORKERS, else CPUs); cpus: default detect_cpus(); blas_threads='auto': this process's BLAS / numba / pool threads = CPUs (None leaves them alone).""" uninstall() bind(target) CFG.update(cfg) comps = resolve(mode, components) STATE["mode"] = mode or ("explicit" if components is not None else os.environ.get("TLSQ_PRIOR_MODE", "exact")) STATE["components"] = comps STATE["cpus"] = int(cpus) if cpus else detect_cpus() w = workers if workers is not None else os.environ.get("TLSQ_PRIOR_WORKERS") # default (A5): serial windows with all threads; forked windows only for certified (measured faster there) STATE["workers"] = max(1, int(w)) if w is not None else (STATE["cpus"] if "ritz" in comps else 1) if "parallel" not in comps: STATE["workers"] = 1 if sys.platform == "darwin" and STATE["workers"] > 1: # Accelerate (BLAS) crashes in forked children: never fork on macOS STATE["workers"] = 1 STATE["parallel_off"] = "darwin: the vendor's window pool forks and Accelerate is not fork-safe" STATE["gpu"] = "gpu" in comps _ORIG.update(window_solve=F._window_solve, loc_solve=FL._solve, micro_mom=F.micro_mom, lite_job=F._lite_job, micro_mom_loc=FL.micro_mom_loc, mom_solve_fast=P.mom_solve_fast, assemble=P._assemble, chol_solve=P._chol_solve, sym_solve=F._sym_solve, dense_max=P.DENSE_MAX, num_threads=P.NUM_THREADS) _ORIG["micro_mom_sig"] = inspect.signature(F.micro_mom) if blas_threads == "auto": _set_threads(STATE["cpus"]) elif blas_threads: _set_threads(int(blas_threads)) if "fv" in comps: F._window_solve = fv_window_solve F.micro_mom = _micro_mom F._lite_job = _lite_job _PARENT[0] = os.getpid() _CHILD[0] = False if "hmat_vec" in comps: _ORIG.update({"Kernel.__init__": P._Kernel.__init__, "Kernel.row": P._Kernel.row, "Kernel.block": P._Kernel.block, "aca": P._aca}) P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = _hv_kernel_init, _hv_row, _hv_block, _hv_aca P.mom_solve_fast = _hv_mom_solve_fast if "compiled" in comps: P.mom_solve_fast = _mom_solve_fast if warm: warmup() if "gpu" in comps: P._assemble = _gpu_assemble P.DENSE_MAX = CFG["gpu_dense_max"] if "gpu" in comps or "mixed" in comps: P._chol_solve = _chol_solve F._sym_solve = _sym_solve if "ritz" in comps: F._window_solve = ritz_window_solve FL._solve = ritz_loc_solve FL.micro_mom_loc = _micro_mom_loc if warm: warmup() if value_patch is not None: _UNDO.append(value_patch(F, P, FL)) STATE["value_patch"] = getattr(value_patch, "__name__", str(value_patch)) return dict(STATE)
def uninstall() -> None: for u in reversed(_UNDO): if callable(u): u() _UNDO.clear() if _ORIG: F._window_solve, FL._solve, F.micro_mom, F._lite_job = (_ORIG["window_solve"], _ORIG["loc_solve"], _ORIG["micro_mom"], _ORIG["lite_job"]) FL.micro_mom_loc, P.mom_solve_fast, P._assemble = _ORIG["micro_mom_loc"], _ORIG["mom_solve_fast"], _ORIG["assemble"] P._chol_solve, F._sym_solve, P.DENSE_MAX = _ORIG["chol_solve"], _ORIG["sym_solve"], _ORIG["dense_max"] P.NUM_THREADS = _ORIG["num_threads"] if "aca" in _ORIG: P._Kernel.__init__, P._Kernel.row, P._Kernel.block, P._aca = (_ORIG["Kernel.__init__"], _ORIG["Kernel.row"], _ORIG["Kernel.block"], _ORIG["aca"]) _ORIG.clear() for tp in _TP: try: tp.restore_original_limits() except Exception: # noqa: BLE001 pass _TP.clear() STATE.update(mode=None, components=(), workers=1, gpu=False, value_patch=None, parallel_off=None)
@contextlib.contextmanagerdef installed(**kw): install(**kw) try: yield dict(STATE) finally: uninstall()
def warmup() -> float: """Compile / load the numba kernels (first call per process; cached on disk afterwards). Returns seconds.""" t = time.perf_counter() rng = np.random.default_rng(0) c = rng.random((600, 2)) * 100 H = HFar(c, leaf=64) H(np.ones((600, 2))) Y = np.empty((600, 1)) _numba()["far"](c[:, 0].copy(), c[:, 1].copy(), np.ones((1, 600)), Y) return time.perf_counter() - t
def status() -> dict: return dict(STATE, cfg=dict(CFG), mixed_gated=MIXED_GATED, frozen_dense_max=FROZEN_DENSE_MAX)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Flagship Space tiers (deploy/registry.yaml: flagship_hub, flagship_tiers; deploy/GNN_SPACE.md "Flagship Space").
The tiers are the models QCap (default), QCap-Lite and QCap-Fast (registry paper_name; handoff/squadds_integration/RENAME_QCAP.md).Their registry keys (accurate, balanced, fast) stay internal: model folders, checkpoints and the paper code path use them; everyresult, label and API argument uses the model names (case-insensitive, "-" and "_" interchangeable).
The tiers run through the paper Space's code path (geomgnn.paper: scene -> embedding -> priors under the tier's prior stack, or thelearned prior surrogate -> networks), unchanged. `view(reg)` is the registry seen with paper_arms / paper_hub replaced byflagship_tiers / flagship_hub, so every geomgnn.paper function serves the tiers as arms."""
from __future__ import annotations
import copy
from . import paper as PA
def view(reg): if reg.data.get("_flagship_view"): return reg v = copy.copy(reg) v.data = dict(reg.data, paper_arms=reg.data["flagship_tiers"], paper_hub=reg.data["flagship_hub"], _flagship_view=True) return v
def tiers(reg) -> dict: return view(reg)["paper_arms"]
def served(reg) -> list[str]: v = view(reg) return [k for k in PA.live(v) if PA.available(k, v)]
def name(reg, tier) -> str: """Model name (QCap, QCap-Lite, QCap-Fast) of a tier key.""" return tiers(reg)[tier]["paper_name"]
def _norm(s) -> str: return str(s).strip().lower().replace("_", "-")
def key(reg, model) -> str: """Tier key of a model name (case-insensitive, "-" and "_" interchangeable); ValueError naming the models otherwise.""" ts = tiers(reg) k = next((k for k in ts if _norm(ts[k]["paper_name"]) == _norm(model)), None) if k is None: raise ValueError(f"Unknown model {model!r}. Choose one of {', '.join(ts[k]['paper_name'] for k in served(reg))}.") return k
def predict(prepared, tier, reg, **kw) -> dict: """Full N x N Maxwell matrix (fF; ground row/column 0) of a prepared layout with a flagship tier (geomgnn.paper.predict). tier: a tier key or a model name; the result names the model (model, arm, tier = QCap / QCap-Lite / QCap-Fast).""" v = view(reg) tier = tier if tier in v["paper_arms"] else key(reg, tier) res = PA.predict(prepared, tier, v, **kw) t = v["paper_arms"][tier] res.pop("paper", None) n = t["paper_name"] res.update(model=n, arm=n, tier=n, tier_title=t["title"], reference=t.get("reference") or {}, own=t.get("own") or {}, b5=t.get("b5"), b5_physics=t.get("b5_physics")) return res
def preload(reg, example=None) -> dict: return PA.preload(view(reg), example=example)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246"""'Check the ground' step of the Space apps, for layouts whose ground and conductors share one layer: the automatic pick(tlsq_infer.layout.detect_ground) is shown on a numbered image; the user confirms it, or clicks shapes / edits the table to switchpieces between ground and conductor. Predict stays disabled until the pick is confirmed."""
from __future__ import annotations
import gradio as grimport numpy as npimport shapelyfrom tlsq_infer.app_ui import _path, _rolesfrom tlsq_infer.layout import prepare
COLS = ["piece", "ground", "name", "area (µm²)", "bbox (µm)"]PRED_LOCKED = "Predict (confirm the ground first)"
def _lay(st, pieces=None): return prepare(st["path"], ground_layers=st["g"], conductor_layers=st["c"], ignore_layers=st["i"], ground_pieces=pieces, max_conductors=10**6)
def _zoom(pieces) -> tuple | None: """View box around every piece but the largest (normally the ground plane), when they fill a small part of the layout.""" big = int(np.argmax([g.area for g in pieces])) full = shapely.union_all(pieces).bounds b = shapely.union_all([g for i, g in enumerate(pieces) if i != big]).bounds m = max(0.25 * max(b[2] - b[0], b[3] - b[1]), 0.03 * max(full[2] - full[0], full[3] - full[1])) box = (max(b[0] - m, full[0]), max(b[1] - m, full[1]), min(b[2] + m, full[2]), min(b[3] + m, full[3])) small = (box[2] - box[0]) * (box[3] - box[1]) < 0.5 * (full[2] - full[0]) * (full[3] - full[1]) return box if small and pieces[big].intersects(shapely.box(*box)) else None
def _title(st) -> str: cur = ", ".join(f"#{i}" for i in st["current"]) if st["current"] == st["auto"]: return f"ground = piece {cur} (automatic, confidence {st['confidence']})" return f"ground = piece {cur} (your choice; automatic: {', '.join(f'#{i}' for i in st['auto'])})"
def _image(lay, st): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt
fig = lay.render(figsize=(6.4, 6.4), compact=True, title=_title(st)) ax = fig.axes[0] box = _zoom(st["pieces"]) if box: ax.set_xlim(box[0], box[2]) ax.set_ylim(box[1], box[3]) ax.set_title(_title(st) + "\nzoomed to the conductors; the table lists every piece", fontsize=10) view = shapely.box(*box) for r in lay.info["ground_detection"]["pieces"]: g = st["pieces"][r["id"] - 1] if r["role"] == "ground" and not view.contains(shapely.Point(r["label_xy"])) and g.intersects(view): q = g.intersection(view).representative_point() ax.annotate(f"G #{r['id']}", (q.x, q.y), ha="center", va="center", fontsize=8, weight="bold", color="#111827", bbox=dict(boxstyle="round,pad=0.2", fc="#e5e7eb", ec="#374151", lw=0.6)) fig.tight_layout() fig.canvas.draw() bb = ax.get_window_extent() img = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy() tr = {"box": [bb.x0, bb.y0, bb.x1, bb.y1], "xlim": list(ax.get_xlim()), "ylim": list(ax.get_ylim()), "h": img.shape[0]} plt.close(fig) return img, tr
def to_um(tr, px, py) -> tuple[float, float]: """Image pixel (origin top-left) -> layout µm.""" x0, y0, x1, y1 = tr["box"] (a, b), (c, d) = tr["xlim"], tr["ylim"] return a + (px - x0) / (x1 - x0) * (b - a), c + ((tr["h"] - py) - y0) / (y1 - y0) * (d - c)
def to_px(tr, x, y) -> tuple[float, float]: x0, y0, x1, y1 = tr["box"] (a, b), (c, d) = tr["xlim"], tr["ylim"] return x0 + (x - a) / (b - a) * (x1 - x0), tr["h"] - (y0 + (y - c) / (d - c) * (y1 - y0))
def hit(pieces, x, y, tol_frac=0.015) -> int | None: """1-based number of the piece under (x, y) µm, else of the nearest piece within tol_frac of the layout size.""" pt = shapely.Point(x, y) d = [float(shapely.distance(g, pt)) for g in pieces] b = shapely.union_all(pieces).bounds k = int(np.argmin(d)) return k + 1 if d[k] <= tol_frac * max(b[2] - b[0], b[3] - b[1]) else None
def _md(st, lay) -> str: gd = lay.info["ground_detection"] cur = ", ".join(f"#{i}" for i in st["current"]) auto = ", ".join(f"#{i}" for i in st["auto"]) if st["current"] == st["auto"]: head = f"Ground found automatically: piece {cur} (confidence {st['confidence']})." else: head = f"Your choice: the ground is piece {cur} (the automatic pick was {auto})." low = "\n\nPlease check it, since the automatic pick is uncertain." if st["confidence"] == "low" and st["current"] == st["auto"] else "" ok = "Ground confirmed: Predict uses this choice." if st["confirmed"] else "Not confirmed yet: Predict is locked until you confirm." n = len(lay.names) return (f"{head}{low}\n\nWhy the automatic pick: {st['reason']}.\n\nGrey = ground (G #k), coloured = conductors: conductor Ck is piece #k in the image, the table and the matrix " f"({n} conductor{'s' if n != 1 else ''}, {gd['n_pieces']} pieces on layer " f"{', '.join(f'{a}/{b}' for a, b in gd['layers'])}).\n\nIf this is right, press \"Looks right → Predict\". Otherwise turn on " f"\"Fix it\" and click a shape (or tick it in the table) to switch it between ground and conductor.\n\n_{ok}_")
def _rows(lay): """Ground pieces first, then the conductors in piece order (piece #k = conductor Ck).""" ps = sorted(lay.info["ground_detection"]["pieces"], key=lambda r: (r["role"] != "ground", r["id"])) return [[r["id"], r["role"] == "ground", r["name"] or "", round(r["area_um2"], 1), "(" + ", ".join(f"{v:.0f}" for v in r["bbox_um"]) + ")"] for r in ps]
def _view(st): lay = _lay(st, st["current"]) img, st["tr"] = _image(lay, st) return img, _md(st, lay), _rows(lay)
def _locked(st): ok = st is None or st["confirmed"] return gr.update(interactive=ok, value="Predict" if ok else PRED_LOCKED)
def check_fn(f, table): """After upload / a layer-role edit: (group, image, text, table, state, predict button, fix mode).""" hide = (gr.update(visible=False), None, "", [], None, gr.update(interactive=True, value="Predict"), False) if f is None: return hide g, c, i = _roles(table) st = {"path": _path(f), "g": g, "c": c, "i": i} try: lay = _lay(st) except Exception: # noqa: BLE001 (the inspect step reports the file error inline) return hide gd = lay.info.get("ground_detection") if not gd: return hide st.update(auto=gd["ground_pieces"], current=gd["ground_pieces"], reason=gd["reason"], confidence=gd["confidence"], history=[], confirmed=False, pieces=lay.pieces) img, md, rows = _view(st) return gr.update(visible=True), img, md, rows, st, _locked(st), False
def _set(st, new): new = sorted(set(new)) if not new: gr.Warning("The ground needs at least one piece.") elif len(new) == len(st["pieces"]): gr.Warning("At least one piece must stay a conductor.") elif new != st["current"]: st["history"].append(st["current"]) st["current"], st["confirmed"] = new, False img, md, rows = _view(st) return img, md, rows, st, _locked(st)
def click_fn(st, fix, evt=None): if st is None or evt is None: raise gr.Error("Upload a layout first.") if not fix: gr.Info("Turn on 'Fix it' to change the roles by clicking.") img, md, rows = _view(st) return img, md, rows, st, _locked(st) k = hit(st["pieces"], *to_um(st["tr"], *evt.index)) if k is None: gr.Info("No shape there: click on a piece of metal.") img, md, rows = _view(st) return img, md, rows, st, _locked(st) cur = set(st["current"]) return _set(st, cur ^ {k})
def select_fn(st, fix, evt: gr.SelectData): return click_fn(st, fix, evt)
def table_fn(st, rows): rows = rows.values.tolist() if hasattr(rows, "values") else rows return _set(st, [int(r[0]) for r in rows if str(r[1]).strip().lower() in ("true", "1", "yes")])
def undo_fn(st): if st and st["history"]: st["current"], st["confirmed"] = st["history"].pop(), False img, md, rows = _view(st) return img, md, rows, st, _locked(st)
def reset_fn(st): return _set(st, st["auto"])
def confirm_fn(st): if st is not None: st["confirmed"] = True return _md(st, _lay(st, st["current"])), st, _locked(st) return "", st, gr.update(interactive=True, value="Predict")
def pieces_of(st): """ground_pieces for prepare: the confirmed choice, or None (automatic) when there is no check step.""" return None if st is None else list(st["current"])
def build(): """The step's components, created inside the current Blocks (hidden until a layout needs the check).""" st = gr.State(None) with gr.Column(visible=False, variant="panel") as box: gr.Markdown("## Check the ground\nGround and conductors are on the same layer, so the ground was picked automatically. " "Check it before predicting.") with gr.Row(): with gr.Column(scale=3, min_width=300): img = gr.Image(label="pieces (grey = ground, coloured = conductors)", type="numpy", interactive=False, show_label=False, buttons=["download", "fullscreen"], elem_id="tl-ground-img", alt_text="Layout pieces, numbered: grey = ground, coloured = conductors. With 'Fix it' on, click a " "piece to switch it between ground and conductor; the table below does the same.") with gr.Column(scale=2, min_width=280): info = gr.Markdown() confirm = gr.Button("Looks right → Predict", variant="primary") fix = gr.Checkbox(False, label="Fix it: click a shape to switch it between ground and conductor", elem_classes="tl-check") with gr.Row(elem_classes="tl-touch"): undo = gr.Button("Undo", variant="secondary", size="sm") reset = gr.Button("Reset to automatic", variant="secondary", size="sm") gr.HTML("<style>#ground-pieces .select-all-checkbox{display:none !important}</style>", container=False, padding=False) table = gr.Dataframe(headers=COLS, elem_id="ground-pieces", show_search="none", datatype=["number", "bool", "str", "number", "str"], interactive=True, static_columns=[0, 2, 3, 4], label="Pieces. Tick 'ground' to make a piece part of the ground (several pieces form one ground net).", wrap=True) return st, box, img, info, confirm, fix, undo, reset, table
def wire(gds, layers, pred_btn, parts, events, after=None): """Event wiring: file changes / layer-role edits (events) -> check; image clicks, table edits, undo, reset -> re-render; confirm unlocks Predict. after(event) is applied to every event that can change the ground pick.""" st, box, img, info, confirm, fix, undo, reset, table = parts outs = [box, img, info, table, st, pred_btn, fix] evs = [ev.then(check_fn, [gds, layers], outs, api_visibility="private") for ev in events] view = [img, info, table, st, pred_btn]
evs += [img.select(select_fn, [st, fix], view, api_visibility="private"), table.input(table_fn, [st, table], view, api_visibility="private"), undo.click(undo_fn, st, view, api_visibility="private"), reset.click(reset_fn, st, view, api_visibility="private")] for ev in evs if after else (): after(ev) return confirm.click(confirm_fn, st, [info, st, pred_btn], api_visibility="private")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Label-free standalone prediction for geomfast checkpoints.Only checkpoints, geometry, and optional priors are accepted; never Q3D labels."""import osos.environ.setdefault('PYTHONDONTWRITEBYTECODE','1')import sys,importlib.util,timefrom pathlib import Pathimport numpy as npimport torchW=Path(__file__).resolve().parentfrom .pilot_p2 import build_modelfrom ._tlsq.uge.scene import scene_from_gds,tlsq_namerfrom ._tlsq.uge.graph import scene_graphfrom ._tlsq.uge.blocks import edge_matrixfrom ._tlsq.uge.proxies import CapacitanceMoMfrom ._tlsq.uge import localtok as lt
class Predictor: def __init__(self,paths,threads=2): torch.set_num_threads(threads);self.models=[];self.threads=threads for path in paths: c=torch.load(path,map_location='cpu',weights_only=False) model=build_model(len(c['scales']['X']['median']),len(c['scales']['E']['median']),len(c['scales']['G']['median']),c['rounds']);model.load_state_dict(c['state']);model.eval();self.models.append((c,model)) assert len({c['arm'] for c,m in self.models})==1 self.arm=self.models[0][0]['arm'];self.direct=self.arm=='direct_gnn';self.fast=self.arm=='fast_gnn' def from_features(self,row,priors=None): n=len(row['names']);pairs=np.array([(i,j) for i in range(n) for j in range(i+1,n)]);i,j=pairs.T;assert len(row['edges'])==len(pairs),'complete graph required' outputs=[] for ck,model in self.models: schema=ck.get('schema',ck);nk=schema['nodekeys'];ek=schema['edgekeys'];gk=schema.get('globkeys',['log_chip_area','log_pocket_area','log_substrate_t','eps_eff']) X=np.array([[(float(not np.isfinite(nd['log_min_halfwidth'])) if k=='missing_log_min_halfwidth' else nd[k]) for k in nk] for nd in row['nodes']],np.float32)[None] E=edge_matrix(row['edges'],ek,n)[None];G=np.array([[row['global'][k] for k in gk]],np.float32) kinds=E[0,:,ek.index('is_ground_pair')].astype(int) if self.arm in ['pair_mlp','mesh','lofo_pair']:X=X[:,:,[nk.index('role_ground')]];G=np.zeros((1,1),np.float32) if self.direct:base=np.array([[ck['direct_intercepts'][str(k)] for k in kinds]],np.float32) else: p0,p1=(.75,1.5) if self.fast else (1.5,3.) lo=np.log(priors[p0][i,j]);hi=np.log(priors[p1][i,j]);assert np.isfinite(lo).all() and np.isfinite(hi).all() base=(2*hi-lo)[None].astype(np.float32);E=np.concatenate([E,(hi-lo)[None,:,None].astype(np.float32)],-1) for name,z in [('X',X),('E',E),('G',G)]: scale=ck['scales'][name];med=np.array(scale['median']);iqr=np.array(scale['iqr']);z[:]=np.clip((np.where(np.isfinite(z),z,med)-med)/iqr,-10,10) assert np.isfinite(z).all() closure=ck['closure_intercepts'];bbase=np.array([[closure.get('1',closure.get('True')) if nm!='G' else closure.get('0',closure.get('False')) for nm in row['names']]],np.float32) T=lambda a:torch.from_numpy(np.asarray(a));M=torch.ones((1,n),dtype=torch.bool);PM=torch.ones((1,len(pairs)),dtype=torch.bool) with torch.inference_mode():C,_=model(T(X),T(E),T(G),M,PM,T(pairs),T(base),T(bbase),self.direct) outputs.append(C[0].numpy()) result=np.mean(outputs,axis=0);assert np.isfinite(result).all();return result def from_gds(self,path,names=None,alpha=None,local_gap=None): from ._tlsq.embed import proxy,fastprior physics=self.models[0][0].get('schema',{}).get('physics',{}) if alpha is None:alpha=physics.get('alpha') if local_gap is None:local_gap=physics.get('prior_method')=='local_gap' proxy.NUM_THREADS=self.threads;start=time.perf_counter() if names is None:namer=tlsq_namer else: def namer(S,m): sig=[n for n in names if n!='G'];assert len(S)==len(sig),'signal polygons vs supplied file-order names';return sig sc=scene_from_gds(path,namer=namer);t1=time.perf_counter();row=lt.add_tokens(sc,scene_graph(sc));t2=time.perf_counter();priors={} if not self.direct: old=fastprior.ALPHA_GAP_SHARE try: if alpha is not None:fastprior.ALPHA_GAP_SHARE=alpha for p in ([.75,1.5] if self.fast else [1.5,3.]): if local_gap: from ._tlsq.embed.fastprior_loc import micro_mom_loc with proxy.substrate('slab_open',sc.stack['substrate_thickness_um']): mat,_,_=micro_mom_loc(sc.conductors[0].geom,[c.geom for c in sc.conductors[1:]],eps_r=sc.stack['substrate_eps_r'],ppg=p) priors[p]=-mat else:priors[p]=-CapacitanceMoM(max_cells=10**9,mesh='lite',cells_per_gap=p,substrate='slab_open').compute(sc,list(row['edges']))['matrix'] finally:fastprior.ALPHA_GAP_SHARE=old t3=time.perf_counter();C=self.from_features(row,priors);t4=time.perf_counter() return dict(C=C,names=row['names'],timing=dict(scene=t1-start,geometry=t2-t1,prior=t3-t2,network_and_pack=t4-t3,total=t4-start))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Fast tier: the learned prior surrogate (agents/learnedprior, t100_norm) in place of the two field solves.
priors(model, prep, row) = the statements of scripts/learnedprior/lp_bench.py `Learned.from_gds` between the features and thenetwork: pack the scene-graph row with the P2d schema (scripts/learnedprior/lp_label.py `pack`), predict log P at 1.5 and 3panels per gap with lp_surrogate.predict_bucket (one layout), and return the symmetric positive mutual matrices thatinfer.Predictor.from_features reads. Self / closure terms are not inputs, so the diagonals stay zero."""
from __future__ import annotations
import numpy as np
from . import lp_surrogate as Sfrom ._tlsq.uge.blocks import edge_matrix
PPG = (1.5, 3.0)
def load(path): """(model, prep, checkpoint) on CPU (lp_surrogate.load_model).""" return S.load_model(str(path), "cpu")
def pack(row: dict) -> dict: """lp_label.pack: X (n, nodekeys), E (P, edgekeys), G (globkeys); pairs i < j in scene order.""" n = len(row["names"]) pairs = [(i, j) for i in range(n) for j in range(i + 1, n)] nk = S.SCHEMA["nodekeys"] X = np.array([[(float(not np.isfinite(nd["log_min_halfwidth"])) if k == "missing_log_min_halfwidth" else nd[k]) for k in nk] for nd in row["nodes"]], np.float32) E = edge_matrix(row["edges"], S.SCHEMA["edgekeys"], n) Gv = np.array([row["global"][k] for k in S.SCHEMA["globkeys"]], np.float32) return dict(X=X, E=E, G=Gv, names=row["names"])
def priors(model, prep, row: dict) -> dict: z = pack(row) n = len(z["names"]) b = dict(n=n, X=z["X"][None], E=z["E"][None], G=z["G"][None]) lp = S.predict_bucket(model, prep, b, "cpu")[0] iu = np.triu_indices(n, 1) out = {} for k, p in enumerate(PPG): M = np.zeros((n, n)) v = np.exp(lp[:, k]) fl = getattr(prep, "floor_ff", None) M[iu] = v if fl is None else np.maximum(v, fl) # registry learned_prior.floor_ff: the training minimum (agents/embedspeed) out[p] = M + M.T return out12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""Mesh levels of the prior concurrently (agents/embedspeed). The two thin-film solves (e.g. 1.5 and 3 panels per gap) areindependent; on macOS each runs its windows serially and keeps only ~2-5 cores busy, so the extra levels run in spawnedworker processes that install the same prior stack (geomgnn.api.set_prior_stack with the recorded registry prior andthreads) and execute the same statements as the in-process loop; the caller solves the first level meanwhile.
TLSQ_LEVEL_PROCS: auto (default: TLSQ_LEVEL_MIN_N <= N <= TLSQ_LEVEL_MAX_N, default 30 and 150, on macOS or with >= 8 threads),1 (always), 0 (never)."""from __future__ import annotations
import osimport sysimport timefrom concurrent.futures import ProcessPoolExecutorfrom multiprocessing import get_context
_EX: dict = {}
def enabled(sc, levels, threads: int = 2) -> bool: from . import api as A v = os.environ.get("TLSQ_LEVEL_PROCS", "auto") if v == "0" or len(levels) < 2 or not A._STATE.get("pr"): return False if v == "1": return True n = len(sc.conductors) # measured (Mac, 18 threads): a gain at N = 67 (18.1 -> 11.9 s with spawned windows), a loss from # N = 277 on (69 -> 75 s; grid_full 194 -> 238 s) where the spawned windows already fill the cores # Linux x86, 16 CPUs (forked windows): 5q 15.1 -> 12.0 s, 9q 76.0 -> 46.6 s, 1q 7.8 -> 10.3 s (spawn cost); never below 8 threads mid = int(os.environ.get("TLSQ_LEVEL_MIN_N", "30")) <= n <= int(os.environ.get("TLSQ_LEVEL_MAX_N", "150")) return mid and (sys.platform == "darwin" or int(threads) >= int(os.environ.get("TLSQ_LEVEL_MIN_THREADS", "8")))
def _init(paths, impl, pr, threads): for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", "TLSQ_NUM_THREADS"): os.environ[k] = str(threads) for p in reversed(paths): if p not in sys.path: sys.path.insert(0, p) import torch torch.set_num_threads(threads) from geomgnn import api as A A.set_prior_impl(impl) A.set_prior_stack(pr, threads) A._thread_limits(threads)
def solve_one(sc, p, threads, alpha, stack=None): """The statements of the prior loop (geomgnn.api.predict_scene / paper.solve_levels) for one level; stack = (eps_r, thickness_um) the prior is solved at (default the scene's).""" from geomgnn import api as A from geomgnn._tlsq.embed import fastprior, proxy from geomgnn._tlsq.embed.fastprior_loc import micro_mom_loc proxy.NUM_THREADS = threads if set(A.V2_KWARGS) & set(A._STATE["patches"]): from geomgnn import priorv2 priorv2.clear() old = fastprior.ALPHA_GAP_SHARE t = time.perf_counter() try: if alpha is not None: fastprior.ALPHA_GAP_SHARE = alpha eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"]) with proxy.substrate("slab_open", t_um), A._quiet_mixed_cast(): mat, _, _ = micro_mom_loc(sc.conductors[0].geom, [c.geom for c in sc.conductors[1:]], eps_r=eps_r, ppg=p) finally: fastprior.ALPHA_GAP_SHARE = old return -mat, time.perf_counter() - t
def _executor(n, threads): from . import api as A key = (n, threads, A._STATE["prior_impl"], repr(A._STATE["pr"])) if _EX.get("key") != key: if _EX.get("ex") is not None: _EX["ex"].shutdown(wait=False, cancel_futures=True) here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) main = sys.modules["__main__"] saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script in the worker try: ex = ProcessPoolExecutor(n, mp_context=get_context("spawn"), initializer=_init, initargs=([here], A._STATE["prior_impl"], A._STATE["pr"], threads)) list(ex.map(int, range(n))) finally: if saved is not None: main.__file__ = saved _EX.update(key=key, ex=ex) return _EX["ex"]
def solve(sc, levels, threads, alpha, stack=None) -> tuple[dict, dict]: """{ppg: P} and {ppg: seconds} with levels[1:] in the workers and levels[0] here.""" ex = _executor(len(levels) - 1, threads) futs = [ex.submit(solve_one, sc, p, threads, alpha, stack) for p in levels[1:]] first = solve_one(sc, levels[0], threads, alpha, stack) res = [first] + [f.result() for f in futs] return {p: r[0] for p, r in zip(levels, res)}, {f"{p:g}": r[1] for p, r in zip(levels, res)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396"""learnedprior surrogate (PROTOCOL.md section 3): tri-GNN on the P2d scene-graph features -> (base, delta) per pair.
python lp_surrogate.py train --p2d DIR [--gen DIR] --out DIR [--steps N] [--raw] [--gen-frac F] [--seed S] python lp_surrogate.py predict --ckpt FILE --data DIR --kind p2d|gen --out FILE.npz
Data buckets are homogeneous in conductor count n (no padding). Pairs i < j in the stored order."""from __future__ import annotations
import os
os.environ.setdefault("PYTHONDONTWRITEBYTECODE", "1")import argparseimport globimport hashlibimport jsonimport platformimport timefrom pathlib import Path
import numpy as npimport torchfrom torch import nnfrom torch.nn import functional as F
HERE = Path(__file__).resolve().parentSCHEMA = json.loads((HERE / "schema_p2d.json").read_text())NK, EK, GK = SCHEMA["nodekeys"], SCHEMA["edgekeys"], SCHEMA["globkeys"]NODE_DIM = {"log_area": 2, "log_perimeter": 1, "log_min_halfwidth": 1, "log_width": 1}EDGE_DIM = {"log_dmin": 1, "log_cps": 1, "mom_0.5": 0.5, "mom_1": 0.0, "mom_2": -1.0}EDGE_DIM.update({f"lg_{k}": v for k, v in list(EDGE_DIM.items())})GLOB_DIM = {"log_chip_area": 2, "log_pocket_area": 2, "log_substrate_t": 1}GROUPS = ("geomfast", "base", "large", "scaled", "near")T_GROUP = {"t1_near": "near", "t2_large": "large", "t3_scaled": "scaled"}
# ----------------------------------------------------------------------------------------------------------- datadef load_p2d(root) -> list: out = [] for p in sorted(glob.glob(f"{root}/n*.npz")): d = np.load(p, allow_pickle=False) out.append(dict(n=d["X"].shape[1], X=d["X"], E=d["E"][:, :, :len(EK)], G=d["G"], pri=d["pri"].astype(np.float64), key=d["key"], split=d["split"], family=d["family"], group=np.full(len(d["key"]), "geomfast"), scale=np.ones(len(d["key"])))) return out
def load_gen(roots) -> list: """roots: one packed dir or several separated by "+" (v1 corpus + targeted corpus; no commas: sbatch --export splits on them).""" out = [] for p in sorted(f for root in str(roots).replace(",", "+").split("+") for f in glob.glob(f"{root}/n*.npz")): d = np.load(p, allow_pickle=False) grp = np.array([T_GROUP.get(str(s), str(s)) for s in d["stratum"]]) out.append(dict(n=d["X"].shape[1], X=d["X"], E=d["E"], G=d["G"], pri=d["pri"].astype(np.float64), key=d["key"], split=d["split"], family=np.char.add("gen_", d["stratum"].astype(str)), group=grp, scale=d["scale"])) return out
def merge_buckets(bs: list) -> list: by = {} for b in bs: by.setdefault(b["n"], []).append(b) return [{k: (v[0][k] if k == "n" else np.concatenate([x[k] for x in v])) for k in v[0]} for n, v in sorted(by.items())]
def subset(b: dict, m: np.ndarray) -> dict: return {k: (v if k == "n" else v[m]) for k, v in b.items()}
def log_L(X: np.ndarray) -> np.ndarray: """(B,) log characteristic length: mean over signal nodes of 0.5 log_area.""" sig = X[:, :, NK.index("role_ground")] < 0.5 la = X[:, :, NK.index("log_area")] return 0.5 * (la * sig).sum(1) / sig.sum(1).clip(1)
class Prep: """Scale shift (optional) + robust scaling; TRAIN statistics only."""
def __init__(self, raw: bool = False): self.raw = raw self.nshift = np.array([NODE_DIM.get(k, 0.0) for k in NK]) self.eshift = np.array([EDGE_DIM.get(k, 0.0) for k in EK]) self.gshift = np.array([GLOB_DIM.get(k, 0.0) for k in GK])
def features(self, b: dict): X, E, G = b["X"].astype(np.float64), b["E"].astype(np.float64), b["G"].astype(np.float64) lL = log_L(b["X"]) if not self.raw else np.zeros(len(X)) if not self.raw: X = X - self.nshift * lL[:, None, None] E = E - self.eshift * lL[:, None, None] G = G - self.gshift * lL[:, None] G = np.concatenate([G, lL[:, None]], 1) return X, E, G, lL
def targets(self, b: dict, lL: np.ndarray): y = np.log(b["pri"]) - lL[:, None, None] return np.stack([2 * y[..., 1] - y[..., 0], y[..., 1] - y[..., 0]], -1)
def fit(self, buckets: list): acc = {k: [] for k in "XEGT"} rng = np.random.default_rng(0) for b in buckets: tr = np.flatnonzero(b["split"] == "train") if not len(tr): continue tr = rng.choice(tr, min(len(tr), 3000), replace=False) X, E, G, lL = self.features(subset(b, np.isin(np.arange(len(b["key"])), tr))) acc["X"].append(X.reshape(-1, X.shape[-1])) acc["E"].append(E.reshape(-1, E.shape[-1])) acc["G"].append(G) acc["T"].append(self.targets(subset(b, np.isin(np.arange(len(b["key"])), tr)), lL).reshape(-1, 2)) self.stats = {} for k in "XEG": v = np.concatenate(acc[k]) med = np.nanmedian(v, 0) iq = np.nanpercentile(v, 75, 0) - np.nanpercentile(v, 25, 0) self.stats[k] = (med, np.where(iq > 1e-6, iq, 1.0)) t = np.concatenate(acc["T"]) self.stats["T"] = (t.mean(0), t.std(0)) return self
def apply(self, b: dict): X, E, G, lL = self.features(b) out = [] for k, z in (("X", X), ("E", E), ("G", G)): med, iq = self.stats[k] out.append(np.clip((np.where(np.isfinite(z), z, med) - med) / iq, -10, 10).astype(np.float32)) return (*out, lL)
def state(self): return dict(raw=self.raw, stats={k: [np.asarray(x).tolist() for x in v] for k, v in self.stats.items()})
@classmethod def from_state(cls, s): p = cls(s["raw"]) p.stats = {k: tuple(np.array(x) for x in v) for k, v in s["stats"].items()} return p
# ---------------------------------------------------------------------------------------------------------- modeldef mlp(i, o, w): return nn.Sequential(nn.Linear(i, w), nn.SiLU(), nn.Linear(w, o))
class Round(nn.Module): def __init__(self, w): super().__init__() self.me, self.mh = nn.Linear(w, w), nn.Linear(w, w) self.node = mlp(3 * w, w, w) self.edge = mlp(3 * w, w, w) self.ln_t = nn.LayerNorm(w) self.ta, self.tb, self.tg = nn.Linear(w, w), nn.Linear(w, w), nn.Linear(w, w) self.tout = nn.Sequential(nn.LayerNorm(w), nn.Linear(w, w)) self.ln_h, self.ln_e = nn.LayerNorm(w), nn.LayerNorm(w)
def forward(self, h, e, off): # h (B,N,w), e (B,N,N,w) symmetric, off (N,N,1) off-diagonal mask N = h.shape[1] m = self.me(e) * self.mh(h)[:, None, :, :] * off # message j -> i mean = m.sum(2) / max(N - 1, 1) mx = (m + (off - 1) * 1e4).amax(2) if N > 1 else torch.zeros_like(mean) h = h + self.node(torch.cat([self.ln_h(h), mean, mx], -1)) hs, hd = h[:, :, None] + h[:, None], (h[:, :, None] - h[:, None]).abs() e = e + self.edge(torch.cat([self.ln_e(e), hs, hd], -1)) * off z = self.ln_t(e) a, b = self.ta(z) * off, self.tb(z) * off t = torch.einsum("bikc,bjkc->bijc", a, b) / max(N - 2, 1) t = 0.5 * (t + t.transpose(1, 2)) e = e + torch.sigmoid(self.tg(z)) * self.tout(t) * off return h, e
class TriGNN(nn.Module): def __init__(self, dx, de, dg, w=128, rounds=4): super().__init__() self.node_in, self.edge_in = mlp(dx + dg, w, w), mlp(de, w, w) self.rounds = nn.ModuleList([Round(w) for _ in range(rounds)]) self.head = mlp(3 * w, 2, w)
def forward(self, X, Eu, G, iu): """X (B,N,dx), Eu (B,P,de) upper-triangle pairs iu=(i,j), G (B,dg) -> (B,P,2) standardised (b, d).""" B, N, _ = X.shape i, j = iu h = self.node_in(torch.cat([X, G[:, None].expand(-1, N, -1)], -1)) eu = self.edge_in(Eu) e = torch.zeros(B, N, N, eu.shape[-1], device=X.device, dtype=eu.dtype) e[:, i, j] = eu e[:, j, i] = eu off = (1 - torch.eye(N, device=X.device, dtype=eu.dtype))[:, :, None] for r in self.rounds: h, e = r(h, e, off) return self.head(torch.cat([e[:, i, j], h[:, i] + h[:, j], (h[:, i] - h[:, j]).abs()], -1))
def build(dx, de, dg, w=128, rounds=4): return TriGNN(dx, de, dg, w, rounds)
# ------------------------------------------------------------------------------------------------------- trainingdef pairs_of(n): return np.array([(i, j) for i in range(n) for j in range(i + 1, n)]).T.reshape(2, -1)
def predict_bucket(model, prep, b, device, max_pairs=2**17): """(B,P,2) log P (ppg 1.5, 3) predicted for every layout of bucket b.""" n = b["n"] iu = torch.as_tensor(pairs_of(n), device=device) X, E, G, lL = prep.apply(b) mu, sd = prep.stats["T"] bs = max(1, max_pairs // (n * n)) out = [] model.eval() with torch.inference_mode(): for s in range(0, len(X), bs): T = lambda a: torch.as_tensor(a[s:s + bs], device=device) # noqa: E731 z = model(T(X), T(E), T(G), iu).double().cpu().numpy() * sd + mu out.append(z) z = np.concatenate(out) bb, dd = z[..., 0], z[..., 1] y3, y1 = bb - dd, bb - 2 * dd return np.stack([y1, y3], -1) + lL[:, None, None]
def fidelity(logp_hat, pri): """Per-entry C0 errors (C0 = exp(2 log P3 - log P1.5)): |rel| with 0.1 fF floor, abs fF; |delta error|.""" c0 = np.exp(2 * np.log(pri[..., 1]) - np.log(pri[..., 0])) c0h = np.exp(2 * logp_hat[..., 1] - logp_hat[..., 0]) d = np.log(pri[..., 1] / pri[..., 0]) dh = logp_hat[..., 1] - logp_hat[..., 0] err = np.abs(c0h - c0) return err / np.maximum(c0, 0.1), err, np.abs(dh - d), c0
def summarize(rel, err): rel, err = np.ravel(rel), np.ravel(err) return dict(entries=int(len(rel)), median_percent=float(np.median(rel) * 100), p95_percent=float(np.percentile(rel, 95) * 100), mae_fF=float(err.mean()), rmse_fF=float(np.sqrt((err ** 2).mean())))
def cmd_train(a): torch.manual_seed(a.seed) rng = np.random.default_rng(a.seed) dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") out = Path(a.out) out.mkdir(parents=True, exist_ok=False) buckets = load_p2d(a.p2d) if a.p2d_holdout_fold is not None: # out-of-fold surrogate for geomfast TRAIN (PROTOCOL amendment 2026-10-17) for b in buckets: f = np.array([int(hashlib.sha256(str(k).encode()).hexdigest(), 16) % a.p2d_nfolds for k in b["key"]]) b.update(subset(b, ~((b["split"] == "train") & (f == a.p2d_holdout_fold)))) if a.gen: g = load_gen(a.gen) if a.gen_frac < 1: # nested subsets by parent index hash (learning curve) for b in g: parent = np.array(["/".join(k.split("/")[:2]) for k in b["key"]]) u = np.array([int(hashlib.sha256(p.encode()).hexdigest(), 16) % 10**6 / 1e6 for p in parent]) keep = (b["split"] != "train") | (u < a.gen_frac) b.update(subset(b, keep)) buckets += g buckets = [b for b in merge_buckets(buckets) if b["n"] >= 2] prep = Prep(a.raw).fit(buckets) data = [] for b in buckets: X, E, G, lL = prep.apply(b) Y = ((prep.targets(b, lL) - prep.stats["T"][0]) / prep.stats["T"][1]).astype(np.float32) data.append(dict(n=b["n"], X=torch.as_tensor(X), E=torch.as_tensor(E), G=torch.as_tensor(G), Y=torch.as_tensor(Y), split=b["split"], group=b["group"], iu=torch.as_tensor(pairs_of(b["n"]), device=dev))) index = {g: [] for g in GROUPS} for k, d in enumerate(data): for g in GROUPS: idx = np.flatnonzero((d["split"] == "train") & (d["group"] == g)) if len(idx): index[g].append((k, idx)) groups = [g for g in GROUPS if index[g]] counts = {g: int(sum(len(i) for _, i in index[g])) for g in groups} val = [(k, np.flatnonzero(d["split"] == "val")) for k, d in enumerate(data)] model = build(data[0]["X"].shape[-1], data[0]["E"].shape[-1], data[0]["G"].shape[-1], a.width, a.rounds).to(dev) opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=1e-4) sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=a.lr, total_steps=a.steps, pct_start=0.03, anneal_strategy="cos") sd = torch.as_tensor(prep.stats["T"][1], device=dev, dtype=torch.float32) meta = dict(args=vars(a), host=platform.node(), device=str(dev), gpu=torch.cuda.get_device_name(0) if dev.type == "cuda" else None, train_counts=counts, val_layouts=int(sum(len(i) for _, i in val)), params=sum(p.numel() for p in model.parameters())) (out / "run.json").write_text(json.dumps(meta, indent=1)) print(json.dumps(meta), flush=True)
def batch_loss(k, idx): d = data[k] T = lambda z: z[idx].to(dev, non_blocking=True) # noqa: E731 z = model(T(d["X"]), T(d["E"]), T(d["G"]), d["iu"]) * sd y = T(d["Y"]) * sd return (F.huber_loss(z[..., 0], y[..., 0], delta=0.05, reduction="none") + F.huber_loss(z[..., 1], y[..., 1], delta=0.05, reduction="none")).mean(1)
def evaluate(maxn=600): model.eval() res = {} with torch.inference_mode(): for k, idx in val: if not len(idx): continue d = data[k] bs = max(1, a.pair_budget // (d["n"] ** 2)) for s in range(0, min(len(idx), maxn), bs): l = batch_loss(k, torch.as_tensor(idx[s:s + bs])) for gname in set(d["group"][idx[s:s + bs]]): m = d["group"][idx[s:s + bs]] == gname res.setdefault(gname, []).extend(l[torch.as_tensor(m, device=dev)].tolist()) model.train() return {g: float(np.mean(v)) for g, v in res.items()}
hist, t0, skipped = [], time.perf_counter(), 0 for step in range(a.steps): g = groups[rng.integers(len(groups))] w = np.array([len(i) for _, i in index[g]], float) k, idx = index[g][rng.choice(len(w), p=w / w.sum())] n = data[k]["n"] bs = int(max(1, min(a.max_batch, a.pair_budget // (n * n)))) b = torch.as_tensor(rng.choice(idx, bs)) loss = batch_loss(k, b).mean() if not torch.isfinite(loss): # skipped and counted (PROTOCOL amendment 2026-10-17); abort if frequent skipped += 1 print(json.dumps(dict(step=step, skipped_nonfinite=skipped, n=int(n), batch=bs)), flush=True) if skipped > 100: raise RuntimeError(f"non-finite loss at step {step} ({skipped} skipped)") opt.zero_grad(set_to_none=True) sched.step() continue opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 5) opt.step() sched.step() if step % a.eval_every == 0 or step == a.steps - 1: ev = evaluate() hist.append(dict(step=step, loss=float(loss), seconds=time.perf_counter() - t0, val=ev)) print(json.dumps(hist[-1]), flush=True) torch.save(dict(state=model.state_dict(), prep=prep.state(), width=a.width, rounds=a.rounds, dims=[data[0]["X"].shape[-1], data[0]["E"].shape[-1], data[0]["G"].shape[-1]], step=step, history=hist), out / "model.pt") meta.update(train_seconds=time.perf_counter() - t0, history=hist, skipped_nonfinite=skipped) (out / "run.json").write_text(json.dumps(meta, indent=1)) print("TRAIN_DONE", time.perf_counter() - t0, flush=True)
def load_model(path, device="cpu"): c = torch.load(path, map_location=device, weights_only=False) m = build(*c["dims"], c["width"], c["rounds"]).to(device) m.load_state_dict(c["state"]) m.eval() return m, Prep.from_state(c["prep"]), c
def cmd_predict(a): dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") model, prep, _ = load_model(a.ckpt, dev) buckets = load_p2d(a.data) if a.kind == "p2d" else load_gen(a.data) keys, logp = [], {} for b in merge_buckets(buckets): if b["n"] < 2: continue sel = b["split"] == "val" if a.split == "val" else np.ones(len(b["key"]), bool) b = subset(b, sel) if not len(b["key"]): continue lp = predict_bucket(model, prep, b, dev) for k, v in zip(b["key"], lp): logp[str(k)] = v.astype(np.float64) np.savez_compressed(a.out, keys=np.array(list(logp)), **{f"k{i}": v for i, v in enumerate(logp.values())}) print("PREDICTED", len(logp))
if __name__ == "__main__": ap = argparse.ArgumentParser() sp = ap.add_subparsers(dest="cmd", required=True) p = sp.add_parser("train") p.add_argument("--p2d", required=True) p.add_argument("--gen") p.add_argument("--gen-frac", type=float, default=1.0) p.add_argument("--out", required=True) p.add_argument("--raw", action="store_true") p.add_argument("--steps", type=int, default=20000) p.add_argument("--lr", type=float, default=1e-3) p.add_argument("--width", type=int, default=128) p.add_argument("--rounds", type=int, default=4) p.add_argument("--pair-budget", type=int, default=2**16) p.add_argument("--max-batch", type=int, default=256) p.add_argument("--eval-every", type=int, default=1000) p.add_argument("--seed", type=int, default=0) p.add_argument("--p2d-holdout-fold", type=int) p.add_argument("--p2d-nfolds", type=int, default=2) p = sp.add_parser("predict") p.add_argument("--ckpt", required=True) p.add_argument("--data", required=True) p.add_argument("--kind", choices=["p2d", "gen"], default="p2d") p.add_argument("--split", choices=["val", "all"], default="val") p.add_argument("--out", required=True) a = ap.parse_args() {"train": cmd_train, "predict": cmd_predict}[a.cmd](a)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980"""Embedding concurrently with the prior solves (agents/embedspeed). Both read only the geometry, so the embedding row(scene_graph + localtok.add_tokens, the same functions) is computed in one spawned worker process while the caller runs theprior solves, and joined before the network: bitwise the same row and priors as the sequential path.
The worker is spawned (never forked: macOS Accelerate; the prior forks its own window workers on Linux) once per processand reused. TLSQ_OVERLAP=0 turns it off; layouts with fewer than TLSQ_OVERLAP_MIN_N conductors (default 30), and machines with fewer thanTLSQ_OVERLAP_MIN_THREADS threads (default 4), stay sequential."""from __future__ import annotations
import osimport sysfrom concurrent.futures import Future, ProcessPoolExecutorfrom multiprocessing import get_context
_EX: dict = {}
def enabled(sc, threads: int = 2) -> bool: """On for >= TLSQ_OVERLAP_MIN_N conductors (default 30) and >= TLSQ_OVERLAP_MIN_THREADS threads (default 4): measured on 2 x86 CPUs the two stages compete for the cores (3 x 3 lattice 141 -> 153 s with the overlap), from 16 they gain (grid_full 609 -> 572 s).""" return (os.environ.get("TLSQ_OVERLAP", "1") != "0" and len(sc.conductors) >= int(os.environ.get("TLSQ_OVERLAP_MIN_N", "30")) and int(threads) >= int(os.environ.get("TLSQ_OVERLAP_MIN_THREADS", "4")))
def _settings() -> dict: from geomgnn._tlsq.uge import blocks
return {"EMBED_MODE": dict(blocks.EMBED_MODE), "EMBED_CACHE": dict(blocks.EMBED_CACHE), "FAR_DECIMATION": dict(blocks.FAR_DECIMATION)}
def _apply(threads: int, st: dict): from geomgnn._tlsq.embed import proxy from geomgnn._tlsq.uge import blocks
proxy.NUM_THREADS = threads for k, v in st.items(): getattr(blocks, k).update(v)
def _init(threads: int, paths: list): for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", "TLSQ_NUM_THREADS"): os.environ[k] = str(threads) for p in reversed(paths): if p not in sys.path: sys.path.insert(0, p)
def _embed(sc, threads: int, st: dict) -> tuple: import time
from geomgnn._tlsq.uge import localtok as lt from geomgnn._tlsq.uge.graph import scene_graph
_apply(threads, st) t = time.perf_counter() return lt.add_tokens(sc, scene_graph(sc)), time.perf_counter() - t
def _executor(threads: int) -> ProcessPoolExecutor: if _EX.get("key") != threads: if _EX.get("ex") is not None: _EX["ex"].shutdown(wait=False, cancel_futures=True) here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) main = sys.modules["__main__"] saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script in the worker try: ex = ProcessPoolExecutor(1, mp_context=get_context("spawn"), initializer=_init, initargs=(threads, [here])) ex.submit(int, 0).result() # start the worker now, while __file__ is hidden finally: if saved is not None: main.__file__ = saved _EX.update(key=threads, ex=ex) return _EX["ex"]
def start(sc, threads: int) -> Future: """Future of (embedding row, worker seconds) of scene sc, computed in the worker process.""" return _executor(threads).submit(_embed, sc, threads, _settings())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439"""Paper Space arms (deploy/registry.yaml: paper_hub, paper_arms; deploy/GNN_SPACE.md "Paper Space").
Every arm of the paper's ladder and routes tables that runs from a layout file on a CPU, through one code path:scene (geomgnn.api.scene_from_prepared) -> geometric embedding -> priors at the arm's mesh levels under the arm's prior stack-> the arm's combination. Kinds: gnn geomfast networks (infer.Predictor): full_gnn / direct_gnn / full_mlp / pair_mlp checkpoints; the two levels are fed as the networks' (1.5, 3) inputs (the coarser-pair arm reads R(0.75, 1.5) there, as it was trained); learned_prior: the fast model's surrogate replaces the solves multifid cheap-physics networks (x1_core.Multifid, scripts/multifid/train_mf.py); learned-exponent arms (curve) use the train_mf.fit anchor (finest level) and curve=True physics no learned parameter: one level (to_maxwell) or a Richardson pair (x1_core.c0) final the prior-generation model and its fast mode (tlsq_infer.final, unchanged)Prior stacks (paper_hub.prior_stacks) are process-wide (geomgnn.api.set_prior_stack); each request installs its arm's stack."""
from __future__ import annotations
import hashlibimport jsonimport osimport timefrom collections import OrderedDictfrom pathlib import Path
import numpy as np
from . import __version__from . import api as Afrom . import infer as Ifrom . import x1_core as Xfrom ._tlsq.embed import fastprior, proxyfrom ._tlsq.uge.graph import scene_graph
lt = I.ltALPHA = 0.49685219816506904 # TRAIN-fitted gap share of every paper prior (P2d physics.alpha)_CACHE: dict = {}
def arms(reg) -> dict: return reg.data.get("paper_arms") or {}
def live(reg) -> list[str]: return [k for k, v in arms(reg).items() if v.get("status", "available") == "available"]
def _sha(p) -> str: return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def _model_dir(model_dir=None): return os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir
def files(reg, name, key="checkpoints", model_dir=None) -> list[Path]: """Bundle copies (<model_dir>/<name>/info.json) or the registry's source paths.""" a = arms(reg)[name] md = _model_dir(model_dir) info = Path(md) / name / "info.json" if md else None if info is not None and info.exists(): return [Path(md) / name / f for f in json.loads(info.read_text()).get(key, [])] src = a.get(key) or [] if key == "surrogate": src = [a["learned_prior"]["checkpoint"]] if a.get("learned_prior") else [] return [reg.root / c["path"] for c in src]
def _hashes(a, key): if key == "surrogate": return [a["learned_prior"]["checkpoint"]["sha256"]] if a.get("learned_prior") else [] return [c["sha256"] for c in a.get(key) or []]
def available(name, reg, model_dir=None) -> bool: a = arms(reg)[name] if a["kind"] == "final": from tlsq_infer import final as F return F.available(a["final_model"], reg) return all(f.exists() for k in ("checkpoints", "surrogate") for f in files(reg, name, k, model_dir))
def stack_of(reg, a) -> dict | None: s = a.get("stack") return None if s is None else reg["paper_hub"]["prior_stacks"][s]
def _check(reg, name, model_dir=None): a = arms(reg)[name] for key in ("checkpoints", "surrogate"): fs, hs = files(reg, name, key, model_dir), _hashes(a, key) assert len(fs) == len(hs), (name, key) for f, h in zip(fs, hs): if _sha(f) != h: raise RuntimeError(f"{name}: {f.name} SHA256 differs from the registry ({h[:12]})") return a
class _Curve: """Learned-exponent cheap-physics arms (train_mf.fit with curve=True): anchor = log of the finest level, slope = finest - next level, the head's exponent p sets m = anchor + slope / (2^p - 1); otherwise x1_core.Multifid.predict_arrays."""
def __init__(self, paths, threads=2): import torch
from .train_mf import build torch.set_num_threads(threads) self.models = [] for p in paths: c = torch.load(p, map_location="cpu", weights_only=False) assert c["curve"] m = build(len(c["scales"]["X"]["median"]), len(c["scales"]["E"]["median"]), len(c["scales"]["G"]["median"]), 2) m.load_state_dict(c["state"]) m.eval() self.models.append((c, m)) self.levels = self.models[0][0]["levels"] assert all(c["levels"] == self.levels for c, _ in self.models)
def predict(self, row, levels): nk, ek, gk = X.schema_of(self.models[0][0]) X0, E0, G0, pairs = X.raw_arrays(row, nk, ek, gk) i, j = pairs.T sig = np.array([nm != "G" for nm in row["names"]]) lev = {p: np.asarray(levels[p], float)[i, j] for p in self.levels} import torch out = [] for c, m in self.models: L = [np.log(np.asarray(lev[p], float)) for p in self.levels] assert all(np.isfinite(v).all() for v in L) lf, lc = L[-1], L[-2] anchor, slope = lf, lf - lc E = np.concatenate([E0] + [(L[k + 1] - L[k])[:, None].astype(np.float32) for k in range(len(L) - 1)], -1) Xn, En, Gn = X.norm(X0, c["scales"]["X"])[None], X.norm(E, c["scales"]["E"])[None], X.norm(G0[None], c["scales"]["G"]) bbase = np.where(sig, c["closure"]["1"], c["closure"]["0"]).astype(np.float32)[None] T = lambda a: torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32)) # noqa: E731 n = len(sig) with torch.inference_mode(): C = m(T(Xn), T(En), T(Gn), torch.ones((1, n), dtype=torch.bool), torch.ones((1, len(pairs)), dtype=torch.bool), torch.from_numpy(pairs), T(anchor[None].astype(np.float32)), T(slope[None].astype(np.float32)), T(bbase), True)[0] out.append(C[0].numpy().astype(np.float64)) r = np.mean(out, 0) assert np.isfinite(r).all() return r
def load(name, reg, model_dir=None, threads=2): """The arm's network object (cached): infer.Predictor (gnn, with .surrogate), x1_core.Multifid / _Curve (multifid), None.""" key = (str(reg.path), name, str(_model_dir(model_dir)), int(threads)) if key in _CACHE: return _CACHE[key] a = _check(reg, name, model_dir) obj = None if a["kind"] == "gnn": obj = I.Predictor(files(reg, name, "checkpoints", model_dir), threads=threads) if obj.arm != a["arm"]: raise RuntimeError(f"{name}: checkpoints are arm {obj.arm!r}, registry says {a['arm']!r}") phys = obj.models[0][0].get("schema", {}).get("physics", {}) if not obj.direct and float(phys.get("alpha")) != ALPHA: raise RuntimeError(f"{name}: checkpoint alpha {phys.get('alpha')} != {ALPHA}") obj.surrogate = None if a.get("learned_prior"): from . import learned_prior model, prep, _ = learned_prior.load(files(reg, name, "surrogate", model_dir)[0]) prep.floor_ff = a["learned_prior"].get("floor_ff") obj.surrogate = (model, prep) if obj.direct != (a.get("stack") is None and not a.get("learned_prior")): raise RuntimeError(f"{name}: solver-free checkpoints iff no prior stack and no learned prior") elif a["kind"] == "multifid": paths = files(reg, name, "checkpoints", model_dir) import torch curve = torch.load(paths[0], map_location="cpu", weights_only=False)["curve"] obj = _Curve(paths, threads) if curve else X.Multifid(paths, threads) if [float(p) for p in obj.levels] != [float(p) for p in a["levels"]]: raise RuntimeError(f"{name}: checkpoint levels {obj.levels} != registry {a['levels']}") _CACHE[key] = obj return obj
def levels_of(a) -> list[float]: return [float(p) for p in (a.get("levels") or a.get("ppg") or [])]
def apply_stack(reg, a, threads=2): st = stack_of(reg, a) if st is not None: A.set_prior_impl("frozen") A.set_prior_stack(st, threads) A._thread_limits(threads)
_LEVELS: OrderedDict = OrderedDict() # solved prior levels: (layout, level, substrate, stack) -> P; TLSQ_PRIOR_LEVEL_CACHE_MB (0 = off)_MESHES: OrderedDict = OrderedDict() # the prior's window meshes (geometry and lattice only, no substrate), same bound
def _geom_hash(geoms) -> str: import shapely h = hashlib.sha256() for g in geoms: h.update(shapely.to_wkb(g)) h.update(b"|") return h.hexdigest()
def _level_key(sc, threads, eps_r, t_um) -> tuple: return (_geom_hash([c.geom for c in sc.conductors]), float(eps_r), float(t_um), int(threads), ALPHA, A._STATE["prior_impl"], repr(A._STATE.get("stack")), repr(A._STATE.get("pr")))
def _put(cache, k, v, cap) -> None: cache[k] = v nb = lambda x: sum(a.nbytes for a in (x if isinstance(x, tuple) else (x,)) if isinstance(a, np.ndarray)) # noqa: E731 while len(cache) > 1 and sum(nb(x) for x in cache.values()) > cap: cache.popitem(last=False)
def _memo_mesh(f, cap): """f(metals, *args) -> mesh arrays, memoised on the metals' WKB and the arguments; hits return copies.""" def g(metals, *args, **kw): k = (f.__module__, f.__name__, _geom_hash(metals), repr(args), repr(sorted(kw.items()))) v = _MESHES.get(k) if v is None: v = tuple(x.copy() if isinstance(x, np.ndarray) else x for x in f(metals, *args, **kw)) _put(_MESHES, k, v, cap) else: _MESHES.move_to_end(k) return tuple(x.copy() if isinstance(x, np.ndarray) else x for x in v) return g
def solve_levels(sc, levels, threads=2, stack=None) -> tuple[dict, dict]: """Positive-mutual prior matrices P = -C at each level under the installed stack (the statements of geomgnn.api.predict_scene's prior loop, any level list); stack = (eps_r, thickness_um) of the substrate the prior is solved at (default the scene's, i.e. the training stack). With TLSQ_PRIOR_LEVEL_CACHE_MB > 0 every solved level is kept (LRU, bounded in MB) and reused by any later call with the same layout, level, substrate and prior stack (tiers sharing a level), and the window meshes are reused across substrates (same layout and level).""" eps_r, t_um = stack or (sc.stack["substrate_eps_r"], sc.stack["substrate_thickness_um"]) cap = float(os.environ.get("TLSQ_PRIOR_LEVEL_CACHE_MB", "0")) * 2**20 key = _level_key(sc, threads, eps_r, t_um) if cap > 0 and levels else None out, tm = {}, {} for p in levels if key else (): v = _LEVELS.get(key + (float(p),)) if v is not None: _LEVELS.move_to_end(key + (float(p),)) out[p], tm[f"{p:g}"] = v.copy(), 0.0 todo = [p for p in levels if p not in out] if todo: from ._tlsq.embed import fastprior_loc as FL from . import priorv2 hooks = [(m, n, getattr(m, n)) for m, n in ((priorv2, "_mesh"), (FL, "mesh_local"))] if key else [] try: for m, n, f in hooks: setattr(m, n, _memo_mesh(f, cap)) P, t = _solve_levels(sc, todo, threads, eps_r, t_um) finally: for m, n, f in hooks: setattr(m, n, f) out.update(P) tm.update(t) for p in todo if key else (): _put(_LEVELS, key + (float(p),), P[p].copy(), cap) return {p: out[p] for p in levels}, {f"{p:g}": tm[f"{p:g}"] for p in levels}
def _solve_levels(sc, levels, threads, eps_r, t_um) -> tuple[dict, dict]: from ._tlsq.embed.fastprior_loc import micro_mom_loc from . import levelpar if levelpar.enabled(sc, levels, threads): # the levels concurrently (spawned workers, same stack and statements) return levelpar.solve(sc, list(levels), threads, ALPHA, (eps_r, t_um)) proxy.NUM_THREADS = threads if set(A.V2_KWARGS) & set(A._STATE["patches"]): from . import priorv2 priorv2.clear() out, tm = {}, {} old = fastprior.ALPHA_GAP_SHARE try: fastprior.ALPHA_GAP_SHARE = ALPHA for p in levels: t = time.perf_counter() with proxy.substrate("slab_open", t_um), A._quiet_mixed_cast(): mat, _, _ = micro_mom_loc(sc.conductors[0].geom, [c.geom for c in sc.conductors[1:]], eps_r=eps_r, ppg=p) out[p] = -mat tm[f"{p:g}"] = time.perf_counter() - t finally: fastprior.ALPHA_GAP_SHARE = old return out, tm
def combine(a, obj, row, P) -> np.ndarray: """The arm's Maxwell matrix from the embedding row and the priors P {ppg: -C} (scene order).""" k = a["kind"] if k == "physics": lv = levels_of(a) return X.to_maxwell(P[lv[0]]) if len(lv) == 1 else X.c0(P, lv[0], lv[1]) if k == "multifid": return obj.predict(row, P) if obj.direct: return obj.from_features(row) if obj.surrogate is not None: from . import learned_prior return obj.from_features(row, learned_prior.priors(*obj.surrogate, row)) lo, hi = levels_of(a) return obj.from_features(row, {1.5: P[lo], 3.0: P[hi]})
def predict_scene(reg, name, sc, threads=2, model_dir=None, stack=None) -> dict: """The arm's prediction; an arm's `embedding: {far_k, d_far_um}` (flagship tiers only, agents/embedspeed Part A) selects the far-sample decimation of the pair vectors for this call (the paper's arms always use the exact embedding).""" from ._tlsq.uge import blocks as _B emb = {} if os.environ.get("TLSQ_EMBEDDING_EXACT") == "1" else (arms(reg)[name].get("embedding") or {}) # tests of the exact recipe old = dict(_B.FAR_DECIMATION) _B.FAR_DECIMATION.update(k=int(emb.get("far_k", 0)), d_far=float(emb.get("d_far_um", 100.0))) try: return _predict_scene(reg, name, sc, threads, model_dir, stack) finally: _B.FAR_DECIMATION.clear() _B.FAR_DECIMATION.update(old)
def _predict_scene(reg, name, sc, threads=2, model_dir=None, stack=None) -> dict: a = arms(reg)[name] obj = load(name, reg, model_dir, threads) apply_stack(reg, a, threads) t0 = time.perf_counter() need = [] if (a["kind"] == "gnn" and (obj.direct or obj.surrogate is not None)) else levels_of(a) from . import overlap as OV fut = OV.start(sc, threads) if need and OV.enabled(sc, threads) else None # the embedding runs in the worker during the priors row = None if fut else lt.add_tokens(sc, scene_graph(sc)) t1 = time.perf_counter() P, tl = solve_levels(sc, need, threads, stack) if need else ({}, {}) t2 = time.perf_counter() extra = {} if fut is not None: row, embed_s = fut.result() extra = dict(overlap=True, geometry_worker=embed_s, geometry_wait_after_prior=time.perf_counter() - t2) t2 = time.perf_counter() C = np.asarray(combine(a, obj, row, P), float) t3 = time.perf_counter() return dict(C=C, names=row["names"], row=row, priors=P, timing=dict(geometry=t1 - t0, prior=t2 - t1, prior_levels=tl, network=t3 - t2, total=t3 - t0, **extra))
def route(a, eps, t_um) -> tuple[dict, list]: """Substrate route of an arm (geomgnn.api.substrate_route): arms that solve a prior solve it at (eps, t_um); learned-prior arms (the Fast tier) are eps-rescaled off the stack with a warning; the solver-free arm has neither and serves the training stack only.""" if a["kind"] == "gnn" and a.get("stack") is None and not a.get("learned_prior"): if not A.on_training_stack(eps, t_um): raise ValueError(f"the solver-free model has no physics prior to solve at another stack: it is served for Si (eps_r " f"{A.EPS_TRAIN:g}), {A.T_TRAIN_UM:g} um only (requested eps_r {eps:g}, {t_um:g} um)") return A.substrate_route(eps, t_um, solves_prior=False) sub, w = A.substrate_route(eps, t_um, solves_prior=not a.get("learned_prior")) if a["kind"] == "physics" and sub.get("caveat"): sub["caveat"] = "physics prior alone (no network), solved at your stack" return sub, w
def predict(prepared, name, reg, substrate="Si (cryogenic, training)", thickness_um=350.0, model_dir=None, threads=None, self_from_rows=True, trust_rule=None) -> dict: """Full N x N Maxwell matrix (fF; ground row/column 0) of a prepared layout with a paper_arms entry.""" a = arms(reg)[name] threads = int(threads or os.environ.get("TLSQ_NUM_THREADS") or 2) if a["kind"] == "final": from tlsq_infer import final as F tr = bool(reg["final_defaults"].get("trust_rule", True)) if trust_rule is None else bool(trust_rule) res = F.predict_final(prepared, a["final_model"], substrate=substrate, thickness_um=thickness_um, self_from_rows=bool(self_from_rows), trust_rule=tr if a.get("trust_rule_applies") else False) res.update(arm=name, arm_title=a["title"], paper_name=a["paper_name"], route=a.get("route")) return res eps, t_um = reg.eps_of(substrate), float(thickness_um) sub, sub_w = route(a, eps, t_um) stack = None if A.on_training_stack(eps, t_um) else (eps, t_um) t = time.perf_counter() load(name, reg, model_dir, threads) load_s = time.perf_counter() - t sc = A.scene_from_prepared(prepared) try: r = predict_scene(reg, name, sc, threads, model_dir, stack) except AssertionError as e: raise ValueError(f"{name}: the prior or the features of this layout are not finite (no matrix returned): {e}") from e C = r["C"] if stack is None or sub["eps_rescale_factor"] is None else r["C"] * sub["eps_rescale_factor"] chk = A.physical_checks(C) warnings = [w for w in prepared.warnings if "beyond the validated range" not in w] if a.get("warning"): warnings.insert(0, a["warning"]) pw = A.physical_warning(chk, C) if pw: warnings.insert(0, pw) warnings += sub_w st = stack_of(reg, a) tm = r["timing"] return {"names": ["G"] + list(prepared.names), "matrix_fF": C.tolist(), "units": "fF", "convention": "Maxwell matrix: diagonal = self, off-diagonal = -mutual; row/column 0 = ground", "self_capacitance": a.get("self_note") or ("predicted by the network (learned positive row-sum closure). The ground self term " "depends on the chip boundary: indicative only"), "model": name, "arm": name, "arm_title": a["title"], "paper_name": a["paper_name"], "route": a.get("route"), "kind": a["kind"], "network_arm": a.get("arm"), "levels_ppg": levels_of(a) if a["kind"] != "gnn" or not (a.get("learned_prior") or a.get("stack") is None) else [], "weights_sha256": _hashes(a, "checkpoints"), "learned_prior_sha256": (_hashes(a, "surrogate") or [None])[0], "prior_stack": (None if st is None else {"name": a["stack"], "patches": A._STATE.get("patches", []), "mode": A._STATE.get("mode") or "frozen", "alpha": ALPHA, "method": "local_gap micro-MoM (slab)"}), "package_version": f"geomgnn {__version__}", "registry_version": reg["version"], "substrate": substrate if not isinstance(substrate, (int, float)) else f"custom eps={eps:g}", "eps_r": eps, "thickness_um": t_um, "substrate_route": sub, "training_stack": {"eps_r": A.EPS_TRAIN, "thickness_um": A.T_TRAIN_UM}, "timing_s": {"load_s": load_s, "geometry_s": tm["geometry"], "prior_s": tm["prior"], "prior_levels_s": tm["prior_levels"], "network_s": tm["network"], "total_s": tm["total"], "threads": threads}, "paper": a.get("paper") or {}, "checks": chk, "warnings": warnings, "stored": False}
STARTUP: dict = {}
def preload(reg, example=None, names=None) -> dict: """Server start: load every live arm (SHA checks) and run the default arm on a small example (numba warmup of the compiled solver included), so the first request does not pay the compile.""" t0 = time.perf_counter() for k in names or live(reg): if arms(reg)[k]["kind"] != "final" and available(k, reg): load(k, reg) STARTUP["load_all_s"] = time.perf_counter() - t0 d = reg["paper_hub"]["default_arm"] if example is not None and Path(example).exists(): from tlsq_infer.layout import prepare t = time.perf_counter() predict(prepare(str(example)), d, reg) STARTUP["example_s"] = time.perf_counter() - t if os.environ.get("TLSQ_PRELOAD_ALL", "1") != "0": # every live arm once (each stack's compile, the surrogates) t = time.perf_counter() for k in names or live(reg): if k != d and arms(reg)[k]["kind"] != "final" and available(k, reg): predict(prepare(str(example)), k, reg) STARTUP["example_all_arms_s"] = time.perf_counter() - t t = time.perf_counter() from ._tlsq.uge import nnk STARTUP["nn_kernel"] = nnk.available() and nnk._STATE.get("arith") # probe + compile of the exact NN kernel from . import overlap th = int(os.environ.get("TLSQ_NUM_THREADS") or 2) if th >= int(os.environ.get("TLSQ_OVERLAP_MIN_THREADS", "4")): overlap._executor(th) # the embedding worker of large layouts, spawned now STARTUP["kernel_and_worker_s"] = time.perf_counter() - t STARTUP.update(default=d, numba_warmup_s=A._STATE.get("warmup_s"), total_s=time.perf_counter() - t0) print("preload " + json.dumps({k: (round(v, 2) if isinstance(v, float) else v) for k, v in STARTUP.items()}), flush=True) return dict(STARTUP)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Isolated P1 pilot. No external-test loaders or paths are implemented."""import osos.environ.setdefault('PYTHONDONTWRITEBYTECODE','1')import argparse, hashlib, json, pickle, time, platform, sysfrom pathlib import Pathimport numpy as npARMS=['mesh','pair_mlp','full_mlp','full_gnn','fast_gnn','direct_gnn','lofo_pair','lofo_full']ROOT=Path(__file__).resolve().parent
def digest(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()def qc(x): C=x['C']; n=len(x['names']); sig=np.array([n!='G' for n in x['names']]) assert C.shape==(n,n) and np.isfinite(C).all(), 'shape/finite' assert np.max(abs(C-C.T))<1e-5*max(1,np.max(abs(C))), 'symmetry' assert np.all(np.diag(C)>0), 'diagonal' assert np.max(C[~np.eye(n,dtype=bool)])<=1e-6, 'mutual sign' assert np.min(C.sum(1)[sig])>=-1e-6, 'closure' assert np.linalg.eigvalsh(C[np.ix_(sig,sig)]).min()>0, 'positive signal block' for p in [.75,1.5,3.]: v=x['priors'][p][np.triu_indices(n,1)]; assert np.isfinite(v).all() and np.all(v>0), 'prior positive'
def feature(x): t=time.perf_counter() try: qc(x) if x['nodes'] is None: from tlsq.uge.scene import scene_from_gds,tlsq_namer from tlsq.uge.blocks import node_features,global_features sc=scene_from_gds(x['gds'],namer=tlsq_namer) assert len(set(sc.names()))==sc.n and set(sc.names())==set(x['names']), 'net mapping' x['nodes']=[node_features(sc,sc.names().index(name)) for name in x['names']] x['global_features'].update(global_features(sc)) x['node_features_s']=time.perf_counter()-t else: x['node_features_s']=None for n in x['nodes']: for k,v in n.items(): if not k.startswith('proxy_'): assert np.isfinite(v), 'node feature finite' return x,None except Exception as e:return None,dict(key=x['key'],reason=repr(e))
def prepare(a): from concurrent.futures import ProcessPoolExecutor sys.path.insert(0,str(ROOT/'vendor')) items=pickle.load(open(a.input,'rb')); assert all(x['split'] in ['train','val'] for x in items) start=time.time() with ProcessPoolExecutor(a.workers) as pool: result=list(pool.map(feature,items)) good=[x for x,e in result if x is not None]; bad=[e for x,e in result if e] assert good and len(good)>0.9*len(items),(len(good),bad[:5]) # Conservative feature-identity audit; all labels remain unused in this decision. def geometry_key(x): vals=[[{k:round(float(v),9) for k,v in nd.items() if not k.startswith('proxy_')} for nd in x['nodes']], [(str(k),{a:round(float(b),9) for a,b in v.items() if not a.startswith(('proxy_','conf_','_'))}) for k,v in sorted(x['edges'].items())]] return hashlib.sha256(json.dumps(vals,sort_keys=True).encode()).hexdigest() validation_geometry={geometry_key(x) for x in good if x['split']=='val'} retained=[] for x in good: if x['split']=='train' and geometry_key(x) in validation_geometry: bad.append(dict(key=x['key'],reason='geometry descriptor duplicate of validation; training copy excluded')) else: retained.append(x) good=retained nodekeys=sorted(set.intersection(*[set(nd) for x in good for nd in x['nodes']])) nodekeys=[k for k in nodekeys if not k.startswith('proxy_')] edgekeys=sorted(set.intersection(*[set(e) for x in good for e in x['edges'].values()])) edgekeys=[k for k in edgekeys if not k.startswith(('proxy_','conf_','_'))] globkeys=['log_chip_area','log_pocket_area','log_substrate_t','eps_eff'] B=len(good); N=max(len(x['names']) for x in good); pairs=np.array([(i,j) for i in range(N) for j in range(i+1,N)]) F=len(pairs); X=np.zeros((B,N,len(nodekeys)),np.float32); E=np.zeros((B,F,len(edgekeys)),np.float32) G=np.zeros((B,len(globkeys)),np.float32); C=np.zeros((B,N,N),np.float32); M=np.zeros((B,N),bool); PM=np.zeros((B,F),bool) pri=np.zeros((B,F,3),np.float32); sig=np.zeros((B,N),bool) for b,x in enumerate(good): n=len(x['names']); M[b,:n]=True; sig[b,:n]=[v!='G' for v in x['names']]; C[b,:n,:n]=x['C'] X[b,:n]=[[nd[k] for k in nodekeys] for nd in x['nodes']]; G[b]=[x['global_features'][k] for k in globkeys] for f,(i,j) in enumerate(pairs): if j>=n:continue PM[b,f]=True; E[b,f]=[x['edges'][(i,j)][k] for k in edgekeys] pri[b,f]=[x['priors'][p][i,j] for p in [.75,1.5,3.]] assert np.isfinite(E).all() and np.isfinite(G).all() out=Path(a.output); out.mkdir(parents=True,exist_ok=True) np.savez_compressed(out/'data.npz',X=X,E=E,G=G,C=C,M=M,PM=PM,pri=pri,sig=sig,pairs=pairs, key=np.array([x['key'] for x in good]),split=np.array([x['split'] for x in good]),family=np.array([x['family'] for x in good]), nodekeys=np.array(nodekeys),edgekeys=np.array(edgekeys),globkeys=np.array(globkeys)) report=dict(accepted=len(good),excluded=bad,seconds=time.time()-start,nodekeys=nodekeys,edgekeys=edgekeys,source_hash=digest(a.input),code_hash=digest(__file__), source_code_hashes={p:digest(Path(a.repo)/p) for p in ['src/tlsq/uge/blocks.py','src/tlsq/uge/scene.py','src/tlsq/geometry.py']}, node_feature_seconds=[dict(key=x['key'],seconds=x['node_features_s']) for x in good if x['node_features_s'] is not None], twonet_cached_feature_seconds=[dict(key=x['key'],features=x.get('cached_features_s'),tokens=x.get('cached_tokens_s')) for x in good if x['family']=='twonet']) (out/'prep.json').write_text(json.dumps(report,indent=2)); print('PREP_DONE',len(good),'excluded',len(bad),flush=True)
def build_model(dx,de,dg,rounds,width=64): import torch from torch import nn def mlp(i,o):return nn.Sequential(nn.Linear(i,width),nn.SiLU(),nn.Linear(width,o)) class Net(nn.Module): def __init__(self): super().__init__(); self.node=mlp(dx+dg,width); self.edge=mlp(de,width) self.msg=nn.ModuleList([mlp(3*width,width) for _ in range(rounds)]) self.up=nn.ModuleList([mlp(2*width,width) for _ in range(rounds)]) self.head=mlp(3*width,1); self.closure=mlp(width,1) nn.init.zeros_(self.head[-1].weight); nn.init.zeros_(self.head[-1].bias) nn.init.zeros_(self.closure[-1].weight); nn.init.zeros_(self.closure[-1].bias) def forward(self,X,E,G,M,PM,pairs,base,bbase,direct=False): B,N,_=X.shape; i,j=pairs[:,0],pairs[:,1] h=self.node(torch.cat([X,G[:,None].expand(-1,N,-1)],-1))*M[:,:,None]; e=self.edge(E) for msg,up in zip(self.msg,self.up): v=msg(torch.cat([h[:,i]+h[:,j],abs(h[:,i]-h[:,j]),e],-1))*PM[:,:,None] agg=torch.zeros_like(h); agg.index_add_(1,i,v); agg.index_add_(1,j,v) degree=torch.zeros_like(M,dtype=X.dtype); degree.index_add_(1,i,PM.float()); degree.index_add_(1,j,PM.float()) h=(h+up(torch.cat([h,agg/degree.clamp_min(1)[:,:,None]],-1)))*M[:,:,None] raw=self.head(torch.cat([h[:,i]+h[:,j],abs(h[:,i]-h[:,j]),e],-1)).squeeze(-1) logc=(base+(raw if direct else .2*torch.tanh(raw))).clamp(-25,20) mutual=logc.exp()*PM; b=(bbase+self.closure(h).squeeze(-1)).clamp(-20,20).exp()*M C=torch.zeros((B,N,N),device=X.device); C[:,i,j]=-mutual; C[:,j,i]=-mutual diag=-C.sum(-1)+b; C=C+torch.diag_embed(diag) return C,logc return Net()
def fit(a): import torch from torch.nn import functional as F torch.set_num_threads(a.threads); torch.manual_seed(a.seed); rng=np.random.default_rng(a.seed) d=dict(np.load(a.data,allow_pickle=False)); arm=a.arm; out=Path(a.output); out.mkdir(parents=True,exist_ok=False) (out/'run.json').write_text(json.dumps(dict(arm=arm,seed=a.seed,steps=a.steps,data_sha=digest(a.data),code_sha=digest(__file__),start=time.time(),threads=a.threads,host=platform.node()),indent=2)) tr=(d['split']=='train') & ((d['family']!='concentric') if arm.startswith('lofo') else True); va=d['split']=='val' assert tr.any() and va.any() and not np.any(tr&va) X=d['X'].copy(); E=d['E'].copy(); G=d['G'].copy() ni=list(d['nodekeys']).index('role_ground'); ei=list(d['edgekeys']).index('is_ground_pair') full=arm not in ['mesh','pair_mlp','lofo_pair']; direct=arm=='direct_gnn'; fast=arm=='fast_gnn' if not full:X=X[:,:,[ni]]; G=np.zeros((len(X),1),np.float32) if arm=='mesh':E=E[:,:,[ei]] lo,hi=(0,1) if fast else (1,2); lp=np.log(d['pri'].clip(1e-12)); base=2*lp[:,:,hi]-lp[:,:,lo] if not direct:E=np.concatenate([E,(lp[:,:,hi]-lp[:,:,lo])[:,:,None]],-1) else: for g in [0,1]: mask=(d['E'][:,:,ei]==g)&d['PM']&tr[:,None] v=(-d['C'][:,d['pairs'][:,0],d['pairs'][:,1]]) base[d['E'][:,:,ei]==g]=np.median(np.log(v[mask].clip(1e-12))) scales={} for name,z,mask in [('X',X,d['M']&tr[:,None]),('E',E,d['PM']&tr[:,None]),('G',G,tr)]: v=z[mask]; med=np.median(v,0); scale=np.percentile(v,75,0)-np.percentile(v,25,0); scale=np.where(scale>1e-6,scale,1) z[:]=np.clip((z-med)/scale,-10,10); scales[name]=dict(median=med.tolist(),iqr=scale.tolist()) bbase=np.zeros(d['M'].shape,np.float32); closure=d['C'].sum(-1).clip(1e-8) for is_signal in [False,True]: mask=(d['sig']==is_signal)&d['M']&tr[:,None]; bbase[d['sig']==is_signal]=np.median(np.log(closure[mask])) T=lambda x:torch.from_numpy(np.asarray(x)) X,E,G,base,bbase=map(T,[X,E,G,base.astype(np.float32),bbase]); M,PM,C,sig,pairs=map(T,[d['M'],d['PM'],d['C'],d['sig'],d['pairs']]) rounds=2 if arm in ['full_gnn','fast_gnn','direct_gnn','lofo_full'] else 0 model=build_model(X.shape[-1],E.shape[-1],G.shape[-1],rounds); opt=torch.optim.AdamW(model.parameters(),lr=1e-3,weight_decay=1e-4) sched=torch.optim.lr_scheduler.CosineAnnealingLR(opt,a.steps,eta_min=1e-5) idx=np.flatnonzero(tr); fam=d['family']; groups=[idx[fam[idx]==f] for f in sorted(set(fam[idx]))] truth=(-C[:,pairs[:,0],pairs[:,1]]).clamp_min(1e-12).log(); hist=[]; t0=time.perf_counter() for step in range(a.steps): b=np.array([rng.choice(groups[g]) for g in rng.integers(len(groups),size=64)]) pred,logc=model(X[b],E[b],G[b],M[b],PM[b],pairs,base[b],bbase[b],direct) pairloss=(F.huber_loss(logc,truth[b],delta=.05,reduction='none')*PM[b]).sum(1)/PM[b].sum(1).clamp_min(1) selfloss=(F.huber_loss(pred.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).log(),C[b].diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).log(),delta=.05,reduction='none')*sig[b]).sum(1)/sig[b].sum(1).clamp_min(1) groundmask=M[b]&~sig[b] groundloss=(F.huber_loss(pred.diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).log(),C[b].diagonal(dim1=-2,dim2=-1).clamp_min(1e-12).log(),delta=.05,reduction='none')*groundmask).sum(1)/groundmask.sum(1).clamp_min(1) loss=(pairloss+.1*selfloss+.02*groundloss).mean(); assert torch.isfinite(loss) opt.zero_grad(); loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(),5); opt.step(); sched.step() if step%250==0:hist.append(dict(step=step,loss=float(loss.detach()),seconds=time.perf_counter()-t0)); print(hist[-1],flush=True) train_s=time.perf_counter()-t0 torch.save(dict(state=model.state_dict(),scales=scales,arm=arm,history=hist,train_keys=d['key'][tr].tolist(),data_hash=digest(a.data),base_closure=bbase.numpy(),nodekeys=d['nodekeys'].tolist(),edgekeys=d['edgekeys'].tolist(),rounds=rounds,closure_intercepts={str(flag):float(np.median(bbase.numpy()[(d['sig']==flag)&d['M']&tr[:,None]])) for flag in [False,True]},direct_intercepts={str(flag):float(np.median(base.numpy()[(d['E'][:,:,ei]==flag)&d['PM']&tr[:,None]])) for flag in [0,1]} if direct else None),out/'model.pt') ev=np.flatnonzero(va); model.eval(); preds=[] with torch.inference_mode(): for chunk in np.array_split(ev,max(1,int(np.ceil(len(ev)/64)))): preds.append(model(X[chunk],E[chunk],G[chunk],M[chunk],PM[chunk],pairs,base[chunk],bbase[chunk],direct)[0].numpy()) b=ev[:1] for _ in range(10):model(X[b],E[b],G[b],M[b],PM[b],pairs,base[b],bbase[b],direct) times=[] for _ in range(100): t=time.perf_counter(); model(X[b],E[b],G[b],M[b],PM[b],pairs,base[b],bbase[b],direct); times.append(time.perf_counter()-t) pred=np.concatenate(preds); np.savez_compressed(out/'validation_predictions.npz',key=d['key'][ev],C=pred) with (out/'VALIDATION_SCORED.json').open('x') as f:json.dump(dict(time=time.time(),prediction_sha=digest(out/'validation_predictions.npz'),scope='validation only; no external test labels'),f) rec=[] for family in sorted(set(fam[ev])): sel=fam[ev]==family; targets=d['C'][ev][sel]; p=pred[sel]; ss=d['sig'][ev][sel]; pm=d['PM'][ev][sel]; ii,jj=d['pairs'].T masks={'mutual':pm,'signal_signal':pm&ss[:,ii]&ss[:,jj],'signal_ground':pm&~(ss[:,ii]&ss[:,jj])} for kind,mask in masks.items(): if mask.any():rec.append(metric(family,kind,-targets[:,ii,jj][mask],-p[:,ii,jj][mask],train_s,times)) rec.append(metric(family,'signal_self',targets.diagonal(axis1=1,axis2=2)[ss],p.diagonal(axis1=1,axis2=2)[ss],train_s,times)) prior=np.exp(2*lp[ev][:, :,2]-lp[ev][:,:,1])[sel] rec.append(metric(family,'C0_mutual',-targets[:,ii,jj][pm],prior[pm],train_s,times)) import pandas as pd pd.DataFrame(rec).to_csv(out/'metrics.csv',index=False) cpu=next((s.split(':',1)[1].strip() for s in Path('/proc/cpuinfo').read_text().splitlines() if s.startswith('model name')),'unknown') if Path('/proc/cpuinfo').exists() else platform.processor() (out/'timing.json').write_text(json.dumps(dict(cpu=cpu,host=platform.node(),threads=a.threads,train_seconds=train_s,network_median_seconds=float(np.median(times)),network_p95_seconds=float(np.quantile(times,.95)),timing_scope='cached features; not end-to-end',parameters=sum(p.numel() for p in model.parameters())),indent=2)) import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt fig,ax=plt.subplots(1,2,figsize=(10,4)); ii,jj=d['pairs'].T; mask=d['PM'][ev]; y=-d['C'][ev][:,ii,jj][mask]; yp=-pred[:,ii,jj][mask] ax[0].loglog(y,yp,'.',alpha=.3); lo=min(y.min(),yp.min()); hi=max(y.max(),yp.max()); ax[0].plot([lo,hi],[lo,hi],'k--'); ax[0].set(xlabel='Q3D mutual (fF)',ylabel='Prediction (fF)',title=arm) ax[1].semilogx(y,yp-y,'.',alpha=.3); ax[1].set(xlabel='Q3D mutual (fF)',ylabel='Signed error (fF)'); fig.tight_layout(); fig.savefig(out/'diagnostics.png',dpi=140); plt.close(fig) print('RUN_DONE',arm,train_s,flush=True)
def metric(family,kind,y,p,train_s,times): err=abs(p-y); return dict(family=family,kind=kind,n=len(y),median_percent=float(np.median(err/np.maximum(abs(y),.1))*100),unfloored_percent=float(np.median(err/np.maximum(abs(y),1e-15))*100),mae_fF=float(err.mean()),rmse_fF=float(np.sqrt(np.mean(err**2))),train_s=train_s,network_median_s=float(np.median(times)))
def smoke(): import torch torch.set_num_threads(2); torch.manual_seed(4) net=build_model(3,4,2,2); pairs=torch.tensor([[0,1],[0,2],[1,2]]) X=torch.randn(1,3,3); E=torch.randn(1,3,4); G=torch.randn(1,2); M=torch.ones(1,3,dtype=torch.bool); PM=M.clone(); base=torch.zeros(1,3); bbase=base.clone() for p in net.parameters():torch.nn.init.normal_(p,0,.05) C,_=net(X,E,G,M,PM,pairs,base,bbase) assert torch.allclose(C,C.transpose(1,2)); assert torch.linalg.eigvalsh(C).min()>0 perm=torch.tensor([2,0,1]); edgeperm=torch.tensor([1,2,0]); C2,_=net(X[:,perm],E[:,edgeperm],G,M,PM,pairs,base,bbase) assert torch.allclose(C2,C[:,perm][:,:,perm],atol=1e-6),'permutation equivariance' C.sum().backward(); assert all(p.grad is None or torch.isfinite(p.grad).all() for p in net.parameters()) print('SMOKE_PASS: symmetry, positive definiteness, permutation equivariance, finite backward')
if __name__=='__main__': p=argparse.ArgumentParser(); sub=p.add_subparsers(dest='cmd',required=True) q=sub.add_parser('prepare'); q.add_argument('--repo',required=True); q.add_argument('--input',required=True); q.add_argument('--output',required=True); q.add_argument('--workers',type=int,default=4) q=sub.add_parser('fit'); q.add_argument('--data',required=True); q.add_argument('--output',required=True); q.add_argument('--arm',choices=ARMS,required=True); q.add_argument('--seed',type=int,default=0); q.add_argument('--threads',type=int,default=2); q.add_argument('--steps',type=int,default=1500) sub.add_parser('smoke'); a=p.parse_args(); {'prepare':prepare,'fit':fit,'smoke':lambda a:smoke()}[a.cmd](a)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215"""Prior v2 = frozen geomfast prior + rejtail fix fc (rescue panels), as a monkeypatch of fastprior._window_solve.Logic copied from scripts/rejtail/rt.py (policies 'exact' and 'fc' only; no wp dependency). Vendor files untouched.Import after the geomfast vendor dir is on sys.path. Usage: import priorv2; with priorv2.installed(): ... fastprior.micro_mom / micro_mom_loc ...fc acts only on windowed solves (all_rhs False, N > 9) whose FIRST attempt leaves a metal without a panel; everythingelse runs the frozen code path."""import timeimport contextlibimport numpy as npimport shapelyfrom ._tlsq.embed import fastprior as F, proxy as P
PRIOR_VERSION = 'v2_fc_dipfill'TRACE = []POLICY = ['fc']
def _solve(c, wh, o, metals, cols, eps_r, all_rhs): if len(c) <= P.DENSE_MAX: A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential) Bm = (o[:, None] == cols[None, :]).astype(float) Q = P._chol_solve(A, Bm) if all_rhs else F._sym_solve(A, Bm) else: Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols] return np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1)
def _mesh(metals, n_core, hh, cap, refined, majority, levels): if not refined: return F._lite_mesh(metals, hh, cap, n_core, levels) if levels: return F._graded_mesh(metals, n_core, hh, levels, majority) return P.mesh_flagship(metals, hh, cap, majority=majority)
def _rescue_panels(metals, miss, h): """Each panel-less metal cut by a lattice of pitch min(h, sqrt(area) / 2) anchored at its bbox; one panel per piece, centre = centroid (point on surface if outside), size = piece bbox (the frozen cut-piece form).""" cs, whs, os_ = [], [], [] for a in miss: g = metals[a] x0, y0, x1, y1 = g.bounds p = min(h, np.sqrt(g.area) / 2) nx, ny = max(1, int(np.ceil((x1 - x0) / p))), max(1, int(np.ceil((y1 - y0) / p))) gx, gy = np.meshgrid(x0 + p * np.arange(nx), y0 + p * np.arange(ny)) pcs = shapely.intersection(shapely.box(gx.ravel(), gy.ravel(), gx.ravel() + p, gy.ravel() + p), g) pcs = pcs[shapely.area(pcs) > 1e-12] bb = shapely.bounds(pcs) cen = shapely.get_coordinates(shapely.centroid(pcs)) inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1]) if not inside.all(): cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs[~inside])) cs.append(cen) whs.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6)) os_.append(np.full(len(pcs), a)) return np.concatenate(cs), np.concatenate(whs), np.concatenate(os_).astype(int)
def window_solve(metals, n_core, h, budget, eps_r, all_rhs, levels=()): pol = POLICY[0] if not all_rhs else 'exact' cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core) t_mesh = t_sol = 0.0 hh, cap, refined, majority = h, budget, 0, False tr = dict(n_core=n_core, n_metals=len(metals), all_rhs=all_rhs, policy=pol, attempts=[]) best, hist = None, [] while True: t = time.perf_counter() c, wh, o, hh, n_raw = _mesh(metals, n_core, hh, cap, refined, majority, levels) miss = np.nonzero(np.bincount(o, minlength=len(metals)) == 0)[0] att = dict(refined=refined, majority=majority, panels=len(c), missing=miss.tolist()) t_mesh += time.perf_counter() - t tr['attempts'].append(att) cs, whs, os_ = c, wh, o if pol != 'exact' and len(miss): empty = np.array([metals[a].is_empty for a in miss]) if pol == 'fc' and not refined and (not empty.any() or len(c) <= P.DENSE_MAX): t = time.perf_counter() if not empty.all(): r = _rescue_panels(metals, miss[~empty], hh) cs, whs, os_ = np.concatenate([c, r[0]]), np.concatenate([wh, r[1]]), np.concatenate([o, r[2]]).astype(o.dtype) att['rescued'] = int(len(r[0])) if empty.any(): att['accept'] = 'empty' t_mesh += time.perf_counter() - t else: att['defer'] = True if att.get('defer'): doomed = len(c) > P.DENSE_MAX hist.append(('doomed',) if doomed else ('mesh', c, wh, o)) att['solve'] = 'doomed' if doomed else 'deferred' ok = False else: t = time.perf_counter() try: R = _solve(cs, whs, os_, metals, cols, eps_r, all_rhs) off = np.ones(R.shape, bool) off[np.arange(len(cols)), cols] = False ok = bool(np.all(np.bincount(os_, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0))) if att.get('accept') == 'empty': ok = True att['solve'] = 'ok' best = R hist.append(('R', R)) except np.linalg.LinAlgError as e: ok = False att['solve'], att['err'] = 'error', str(e)[:120] hist.append(('err',)) t_sol += time.perf_counter() - t if ok or majority: break if refined < F.LITE_REFINE: hh, cap, refined = hh / 2, np.inf, refined + 1 else: majority = True if not ok: # frozen R binding: the latest attempt that solved (deferred dense attempts solved lazily, newest first) R = None t = time.perf_counter() for e in reversed(hist): if e[0] == 'R': R = e[1] break if e[0] == 'mesh': try: R = _solve(e[1], e[2], e[3], metals, cols, eps_r, all_rhs) break except np.linalg.LinAlgError: continue t_sol += time.perf_counter() - t assert R is not None, 'no attempt solved (the frozen code raises here too)' else: R = best tr['fired'] = bool(pol == 'fc' and tr['attempts'][0]['missing']) TRACE.append(tr) return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh, "assemble_s": 0.0, "solve_s": t_sol}
FILL = [] # one entry per formula_prior call replaced by the dipole fill: number of pairsMARGIN = [] # one entry per window whose margin was widened: (d, margin)_FROZEN = dict(formula_prior=F.formula_prior, lite_window=F._lite_window, dipole_far=F.dipole_far)K_TOL = 1e-4
def slab_R(d, t_um=350.0, eps_r=11.45): """src/tlsq/embed/fastprior_farv4.slab_R verbatim: R(d) = 1 + 2 sum_n (-K)^n (1 - 8 n^2 t^2/d^2)/(1 + 4 n^2 t^2/d^2)^(5/2).""" d = np.asarray(d, float) K = (eps_r - 1) / (eps_r + 1) n_max = int(np.ceil(np.log(K_TOL) / np.log(K))) if K > 0 else 0 n = np.arange(1, n_max + 1)[:, None] u = (n * t_um / d[None]) ** 2 return 1 + 2 * np.sum((-K) ** n * (1 - 8 * u) / (1 + 4 * u) ** 2.5, 0)
def dipole_far_slab(G, conds, pairs, eps_r=11.45, gap=None): """src/tlsq/embed/fastprior_farv4.dipole_far_v4 verbatim: the frozen dipole_far with (1 + eps_r) -> 1 + eps_r R(d).""" base = _FROZEN['dipole_far'](G, conds, pairs, eps_r, gap) pairs = np.asarray(pairs, int).reshape(-1, 2) cen = shapely.get_coordinates(shapely.centroid(np.array([G] + list(conds), dtype=object))) d = np.hypot(*(cen[pairs[:, 0]] - cen[pairs[:, 1]]).T) return base * (1 + eps_r * slab_R(d, float(P.SUBSTRATE["t_um"]), eps_r)) / (1 + eps_r)
def formula_as_dipole(G, conds, eps_r=11.45, step_um=None, R_gaps=None, pairs=None, gap=None, screen_um=None, workers=1, max_core=8): """Replaces formula_prior inside micro_mom (its only caller there: same-pocket far pairs): the same pairs get dipole_far(G, conds, pairs, eps_r, gap), the fill micro_mom uses for cross-pocket far pairs.""" pairs = np.asarray(pairs, int).reshape(-1, 2) N = len(conds) + 1 C = np.zeros((N, N)) v = F.dipole_far(G, conds, pairs, eps_r, gap) C[pairs[:, 0], pairs[:, 1]] = v C[pairs[:, 1], pairs[:, 0]] = v FILL.append(len(pairs)) return C, {"dipole_fill_pairs": len(pairs)}
def lite_window_margin(G, conds, core, R_g, margin, fill_um, tree, etched): """Frozen _lite_window, except margin' = 2 d when d = max distance of a core conductor to the chip ground > margin.""" d = max(shapely.distance(conds[i], G) for i in core) if d > margin: MARGIN.append((float(d), float(margin))) margin = 2 * d return _FROZEN['lite_window'](G, conds, core, R_g, margin, fill_um, tree, etched)
@contextlib.contextmanagerdef installed(policy='fc', dip=True, margin=False, slab_alpha=None): """Install prior v2 pieces: window solve policy 'fc' (or 'exact' = traced frozen copy, or None = vendor as is), the dipole fill of same-pocket far pairs (dip), the window margin widening (margin) and, for arm v2-slab, the slab dipole for every far pair with ALPHA_GAP_SHARE = slab_alpha. Always restored.""" saved = (F._window_solve, F.formula_prior, F._lite_window, F.dipole_far, F.ALPHA_GAP_SHARE) if policy is not None: POLICY[0] = policy F._window_solve = window_solve if dip: F.formula_prior = formula_as_dipole if margin: F._lite_window = lite_window_margin if slab_alpha is not None: F.dipole_far, F.ALPHA_GAP_SHARE = dipole_far_slab, float(slab_alpha) try: yield finally: F._window_solve, F.formula_prior, F._lite_window, F.dipole_far, F.ALPHA_GAP_SHARE = saved POLICY[0] = 'fc'
def clear(): TRACE.clear() FILL.clear() MARGIN.clear()
def fired(trace): """True if fc changed the solve of any window of the traced call.""" return any(t.get('fired') for t in trace).dockerignoreDeleted-3
.tlsq_deployDeleted-1
DockerfileDeleted-16
README.md+5-57
app.pyDeleted-96
examples/interdigital.gdsDeleted
examples/lattice_1q.gdsDeleted
examples/lattice_5q.gdsDeleted
examples/shielded_concentric.gdsDeleted
examples/transmon_pocket.gdsDeleted
examples/xmon.gdsDeleted
geomgnn/.ruff_cache/.gitignoreDeleted-2
geomgnn/.ruff_cache/0.3.2/1469527473019908334Deleted
geomgnn/.ruff_cache/0.3.2/15008937266116554827Deleted
geomgnn/.ruff_cache/0.3.2/16722831700881126324Deleted
geomgnn/.ruff_cache/CACHEDIR.TAGDeleted-1
geomgnn/SOURCES.jsonDeleted-233
geomgnn/__init__.pyDeleted-8
geomgnn/_tlsq/__init__.pyDeleted
geomgnn/_tlsq/embed/__init__.pyDeleted
geomgnn/_tlsq/embed/fastprior.pyDeleted-925
geomgnn/_tlsq/embed/fastprior_loc.pyDeleted-210
geomgnn/_tlsq/embed/proxy.pyDeleted-1043
geomgnn/_tlsq/geometry.pyDeleted-256
geomgnn/_tlsq/uge/__init__.pyDeleted-5
geomgnn/_tlsq/uge/blocks.pyDeleted-526
geomgnn/_tlsq/uge/graph.pyDeleted-74
geomgnn/_tlsq/uge/localtok.pyDeleted-126
geomgnn/_tlsq/uge/nnk.pyDeleted-341
geomgnn/_tlsq/uge/proxies.pyDeleted-102
geomgnn/_tlsq/uge/scene.pyDeleted-90
geomgnn/access.pyDeleted-167
geomgnn/api.pyDeleted-536
geomgnn/app_flagship.pyDeleted-651
geomgnn/app_gnn.pyDeleted-314
geomgnn/app_paper.pyDeleted-325
geomgnn/bundle.pyDeleted-33
geomgnn/farfield.pyDeleted-73
geomgnn/fastmom.pyDeleted-147
geomgnn/fastprior_pkg.pyDeleted-1297
geomgnn/flagship.pyDeleted-69
geomgnn/ground_ui.pyDeleted-246
geomgnn/infer.pyDeleted-72
geomgnn/learned_prior.pyDeleted-49
geomgnn/levelpar.pyDeleted-97
geomgnn/lp_surrogate.pyDeleted-396
geomgnn/overlap.pyDeleted-80
geomgnn/paper.pyDeleted-439
geomgnn/pilot_p2.pyDeleted-214
geomgnn/priorv2.pyDeleted-215