diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 6bffa9bf74414000f30442cc47613e556237363f..0000000000000000000000000000000000000000 --- a/.dockerignore +++ /dev/null @@ -1,3 +0,0 @@ -numba_cache -__pycache__ -bake diff --git a/.tlsq_deploy b/.tlsq_deploy deleted file mode 100644 index 5eabbd2993fd52f358dcd47497c39b8779b09807..0000000000000000000000000000000000000000 --- a/.tlsq_deploy +++ /dev/null @@ -1 +0,0 @@ -managed by deploy/sync.py --flagship (registry v2) diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index b4c8d60c053ef376db7da9615e0e28a95c011a39..0000000000000000000000000000000000000000 --- a/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -# Docker variant (agents/embedspeed, scripts/embedspeed/make_docker_space.py): numba cache baked at build time. -FROM python:3.12-slim -RUN useradd -m -u 1000 user -USER user -ENV 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=2 -WORKDIR /home/user/app -COPY --chown=user requirements.txt . -RUN pip install --no-cache-dir --user -r requirements.txt "gradio==6.29.1" && pip freeze > IMAGE_FREEZE.txt -COPY --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.py -CMD ["python", "app.py"] diff --git a/README.md b/README.md index 1ec59e82f0aacf7437f3aed86303172d353e90cb..b8dfc710d71d7e74dfdabd415525c775926e0301 100644 --- a/README.md +++ b/README.md @@ -3,12 +3,10 @@ title: Planar Capacitance Model emoji: 🔌 colorFrom: blue colorTo: gray -sdk: docker -app_port: 7860 -app_file: app.py +sdk: static pinned: false -short_description: 'Maxwell capacitance of planar layouts: QCap models' -hf_oauth: true +license: mit +short_description: 'Moved: the QCap demo now runs on SQuADDS' thumbnail: https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolve/main/assets/qcap_og.png --- @@ -17,59 +15,9 @@ thumbnail: https://huggingface.co/spaces/shanto268/PlanarCapacitanceModel/resolv -# Planar Capacitance Model +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 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 it - -1. 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. - -## API - -The same endpoints work over `gradio_client` or REST (`/gradio_api/call/`). - -```python -import os -from gradio_client import Client, handle_file - -c = Client("shanto268/PlanarCapacitanceModel", oauth_token=os.environ["HF_TOKEN"]) # counts as you for the daily limit -r = 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 demo - -The 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). - -## Privacy - -Uploaded 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. +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 diff --git a/app.py b/app.py deleted file mode 100644 index a8dc13419528498d4c43a89fbacca3ecbca8d053..0000000000000000000000000000000000000000 --- a/app.py +++ /dev/null @@ -1,96 +0,0 @@ -"""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 os -import platform -import sys -import threading -import traceback -from 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().parent -if (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: E402 -from 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: E402 -from 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)) diff --git a/examples/interdigital.gds b/examples/interdigital.gds deleted file mode 100644 index 6cbb2a694e29e93d270b9f14afc998b037387aeb..0000000000000000000000000000000000000000 Binary files a/examples/interdigital.gds and /dev/null differ diff --git a/examples/lattice_1q.gds b/examples/lattice_1q.gds deleted file mode 100644 index 103809f3fdb05398f0c0b1e1f4148fc5a99d3774..0000000000000000000000000000000000000000 Binary files a/examples/lattice_1q.gds and /dev/null differ diff --git a/examples/lattice_5q.gds b/examples/lattice_5q.gds deleted file mode 100644 index 0ab3871511b3a7f7e39d2511100b1f0b7a092533..0000000000000000000000000000000000000000 Binary files a/examples/lattice_5q.gds and /dev/null differ diff --git a/examples/shielded_concentric.gds b/examples/shielded_concentric.gds deleted file mode 100644 index f11843390455e377beae435fe0f881abb217393f..0000000000000000000000000000000000000000 Binary files a/examples/shielded_concentric.gds and /dev/null differ diff --git a/examples/transmon_pocket.gds b/examples/transmon_pocket.gds deleted file mode 100644 index 9d117c44617c3f2ce8d4bf6066c154bd0e3c0d0c..0000000000000000000000000000000000000000 Binary files a/examples/transmon_pocket.gds and /dev/null differ diff --git a/examples/xmon.gds b/examples/xmon.gds deleted file mode 100644 index 5c99528a0d7975359f3b118ccd7eae28b2063be4..0000000000000000000000000000000000000000 Binary files a/examples/xmon.gds and /dev/null differ diff --git a/geomgnn/.ruff_cache/.gitignore b/geomgnn/.ruff_cache/.gitignore deleted file mode 100644 index b100327770759f0efb7859fe78aca4801d69ed61..0000000000000000000000000000000000000000 --- a/geomgnn/.ruff_cache/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Automatically created by ruff. -* diff --git a/geomgnn/.ruff_cache/0.3.2/1469527473019908334 b/geomgnn/.ruff_cache/0.3.2/1469527473019908334 deleted file mode 100644 index bbf33720b255528b64e049588a8f36c4e6602af1..0000000000000000000000000000000000000000 Binary files a/geomgnn/.ruff_cache/0.3.2/1469527473019908334 and /dev/null differ diff --git a/geomgnn/.ruff_cache/0.3.2/15008937266116554827 b/geomgnn/.ruff_cache/0.3.2/15008937266116554827 deleted file mode 100644 index 4525e238ad8fb15872ece1685040f313e0b2e7c5..0000000000000000000000000000000000000000 Binary files a/geomgnn/.ruff_cache/0.3.2/15008937266116554827 and /dev/null differ diff --git a/geomgnn/.ruff_cache/0.3.2/16722831700881126324 b/geomgnn/.ruff_cache/0.3.2/16722831700881126324 deleted file mode 100644 index ac1732243041b4f76c9d73c17b4b36cb6b456c1c..0000000000000000000000000000000000000000 Binary files a/geomgnn/.ruff_cache/0.3.2/16722831700881126324 and /dev/null differ diff --git a/geomgnn/.ruff_cache/CACHEDIR.TAG b/geomgnn/.ruff_cache/CACHEDIR.TAG deleted file mode 100644 index bc1ecb967a482524e7736038de0df6e08f9ee452..0000000000000000000000000000000000000000 --- a/geomgnn/.ruff_cache/CACHEDIR.TAG +++ /dev/null @@ -1 +0,0 @@ -Signature: 8a477f597d28d172789f06886806bc55 \ No newline at end of file diff --git a/geomgnn/SOURCES.json b/geomgnn/SOURCES.json deleted file mode 100644 index 7354a082e025bd9b6c21f9670eaae138c35a6bd2..0000000000000000000000000000000000000000 --- a/geomgnn/SOURCES.json +++ /dev/null @@ -1,233 +0,0 @@ -{ - "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" - } - } -} diff --git a/geomgnn/__init__.py b/geomgnn/__init__.py deleted file mode 100644 index 0a2acf47a067aafdc79963ee6955840ed3f066c9..0000000000000000000000000000000000000000 --- a/geomgnn/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -"""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 import -lines rewritten, see SOURCES.json) so it cannot collide with `tlsq_infer` or the repository's `tlsq`. `geomgnn.api` adapts it -to `tlsq_infer.layout.PreparedLayout` and to the registry entries `gnn_models` (deploy/registry.yaml). -""" - -__version__ = "0.1.0" diff --git a/geomgnn/_tlsq/__init__.py b/geomgnn/_tlsq/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/geomgnn/_tlsq/embed/__init__.py b/geomgnn/_tlsq/embed/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/geomgnn/_tlsq/embed/fastprior.py b/geomgnn/_tlsq/embed/fastprior.py deleted file mode 100644 index bdc69d0e7732eba10adcfd261f33583c1b358082..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/embed/fastprior.py +++ /dev/null @@ -1,925 +0,0 @@ -"""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 the -entries of a conductor are set by its neighbourhood. The layout is partitioned into windows (recursive bisection of -the conductor sites until the metal edge length inside each window fits a panel budget); a window models its core -conductors (whose matrix rows it provides), the halo conductors within R_g of the core as separate nets at 0 V, the -ground plane cropped by a margin around core + halo, and every farther conductor filled into the ground. Each window -is a strip-merged conductor-anchored mesh (the flagship mesh family, PRIOR_SCHEME.md Part II) solved densely with the -exact near field and one right-hand side per core conductor, optionally Richardson-extrapolated (h and 2 h). Windows -that 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 hashlib -import time -from concurrent.futures import ProcessPoolExecutor -from multiprocessing import get_context - -import numpy as np -import shapely -from scipy.spatial import cKDTree - -from ..geometry import sample_boundary -from ..uge.blocks import _kratio -from . 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 labels -FORMULA_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 form -FORMULA_SCREEN_UM = 1.0 # the screening factor is evaluated every FORMULA_SCREEN_UM of boundary and held in between -LITE_REFINE = 3 # rejected window solves: refine h by 2 up to this many times before majority-owned cells -LITE_LEVEL_GAPS = (10.0, 20.0, 40.0, 80.0) # windows of large layouts: finest panel within 10 gaps of the core, doubling beyond 10/20/40/80 -LITE_WINDOW_BUDGET = 2.0 # windows of large layouts: panel budget = this x the budget of the one-window (component) prior -LITE_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, info diff --git a/geomgnn/_tlsq/embed/fastprior_loc.py b/geomgnn/_tlsq/embed/fastprior_loc.py deleted file mode 100644 index 192c71d44cbb0044b22f60215cfbe9100bde288c..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/embed/fastprior_loc.py +++ /dev/null @@ -1,210 +0,0 @@ -"""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 / 4096 -floor 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 pair -gap 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, slab -kernel 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 np -import shapely - -from . import fastprior as F -from . 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), info diff --git a/geomgnn/_tlsq/embed/proxy.py b/geomgnn/_tlsq/embed/proxy.py deleted file mode 100644 index 3754ba442065739ae7f74f46476852b246125691..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/embed/proxy.py +++ /dev/null @@ -1,1043 +0,0 @@ -"""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 is -1 / (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, including -shielding and other non-local effects that local descriptors cannot represent. Truncation: the ground plane is -represented 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 the -gallery 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 os -import queue -import threading -from collections import OrderedDict -from concurrent.futures import ThreadPoolExecutor -from functools import partial - -import numpy as np -import shapely -from scipy.linalg import cho_factor, cho_solve -from scipy.spatial import cKDTree - -EPS0_FF_PER_UM = 8.8541878128e-3 -SELF = 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] = r -except 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, info diff --git a/geomgnn/_tlsq/geometry.py b/geomgnn/_tlsq/geometry.py deleted file mode 100644 index 357d691247147e8087420fecf6bc55ab9463d367..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/geometry.py +++ /dev/null @@ -1,256 +0,0 @@ -"""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 gdstk -import numpy as np -import shapely -from scipy import sparse -from scipy.sparse.linalg import eigsh -from scipy.spatial import cKDTree -from shapely.geometry import MultiPolygon, Polygon - -GROUND_LAYER = (1, 0) -SIGNAL_LAYER = (1, 10) -BOUNDARY_STEP_UM = 0.25 -SEP_BINS_UM = np.geomspace(0.5, 2000.0, 41) -N_FOURIER = 16 -MIC_TOL = [0.01] # inscribed-circle tolerance (um); 0.1 for the approximate token variants (PRIOR_SCHEME.md 14.3.1) -RASTER_PX = 512 -N_EIG = 16 -K_BINS = 48 - - -@dataclass -class 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, arrays diff --git a/geomgnn/_tlsq/uge/__init__.py b/geomgnn/_tlsq/uge/__init__.py deleted file mode 100644 index b6689b8e89b04c8f16ebc3e1102af4190fb8d841..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/uge/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""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 proxy -plugin that fits their observable (capacitance, resonance frequency, kappa, ...), and (3) the target adapter. -""" diff --git a/geomgnn/_tlsq/uge/blocks.py b/geomgnn/_tlsq/uge/blocks.py deleted file mode 100644 index d67c8090c9650257091cbdb06d589c06bdaa8bb4..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/uge/blocks.py +++ /dev/null @@ -1,526 +0,0 @@ -"""Physics-agnostic geometry blocks: node (per conductor), edge (per conductor pair) and global features, all in -physical units (log µm, ratios) so that nothing is fitted to a dataset.""" - -from __future__ import annotations - -import hashlib -import os -import pickle -from collections.abc import Mapping -from pathlib import Path - -import numpy as np -import shapely -from scipy.special import ellipk -from scipy.spatial import cKDTree - -from .. import geometry as _geometry -from ..embed.proxy import _nthreads -from ..geometry import fourier_descriptors, sample_boundary, shape_metrics -from .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 fastest -NN_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)} diff --git a/geomgnn/_tlsq/uge/graph.py b/geomgnn/_tlsq/uge/graph.py deleted file mode 100644 index 64dfdecbb33386905c0ad9c623cc4313e4102f69..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/uge/graph.py +++ /dev/null @@ -1,74 +0,0 @@ -"""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_all -from .proxies import Proxy -from .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 out diff --git a/geomgnn/_tlsq/uge/localtok.py b/geomgnn/_tlsq/uge/localtok.py deleted file mode 100644 index 491b700f076d5ef31b33e9cacfd5633a862cabbb..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/uge/localtok.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Local, window-invariant context tokens (PRIOR_SCHEME.md 14.5 E4; replace the chip / pocket areas): for every signal -conductor and radius R, the fractions of its surrounding annulus (conductor buffered by R, minus the conductor) that are -ground metal, other-conductor metal and etched chip; the rest of the annulus lies outside the chip (no metal). Pair -tokens = 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 np -import shapely - -from ..geometry import sample_boundary -from ..embed.proxy import _nthreads -from .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.0 -TOK = ["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) diff --git a/geomgnn/_tlsq/uge/nnk.py b/geomgnn/_tlsq/uge/nnk.py deleted file mode 100644 index f93bb2ced67785f6090250296f73dd674bfc3f38..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/uge/nnk.py +++ /dev/null @@ -1,341 +0,0 @@ -"""Exact nearest-sample distances (agents/embedspeed, CONSULT_HPC 3a): a 2-D k-d tree in numba whose squared distance is -the platform's cKDTree arithmetic (probed at first use against scipy: fma(dy, dy, dx * dx) on the arm64 wheels, plain -dx * dx + dy * dy elsewhere), queried in boundary order with a warm-start bound from the previous sample (triangle -inequality, inflated), so the minimum over samples, and its sqrt, are the same bits as cKDTree.query. If no variant -reproduces cKDTree on the probe, `available()` is False and callers keep cKDTree. -""" -from __future__ import annotations - -import os -import threading - -import numba as nb -import numpy as np -from llvmlite import ir -from numba import types -from numba.extending import intrinsic - -LEAF = 32 -WARM = 4 # boundary-order neighbours of the previous query's nearest sample evaluated first (an exact upper bound) -_STATE: dict = {} - - -@intrinsic -def _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.0 -HULL_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"] diff --git a/geomgnn/_tlsq/uge/proxies.py b/geomgnn/_tlsq/uge/proxies.py deleted file mode 100644 index 257da3ed0b735f127e702b3c1f0cdf776366d45b..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/uge/proxies.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Physics-proxy plugins. A proxy maps a Scene to extra node / edge / global quantities that are cheap to compute and -physically aligned with the target. Swap the proxy to move the recipe to another observable (e.g. a resonator dataset -would 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_rich -from .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)} diff --git a/geomgnn/_tlsq/uge/scene.py b/geomgnn/_tlsq/uge/scene.py deleted file mode 100644 index fd065001f444949153aed2c227c3eda7c321d02f..0000000000000000000000000000000000000000 --- a/geomgnn/_tlsq/uge/scene.py +++ /dev/null @@ -1,90 +0,0 @@ -"""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, field -from typing import Callable - -import gdstk -import numpy as np -import shapely -from 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} - - -@dataclass -class Conductor: - name: str - role: str # "ground" | "signal" - geom: object # shapely (Multi)Polygon, µm - - -@dataclass -class 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 names diff --git a/geomgnn/access.py b/geomgnn/access.py deleted file mode 100644 index 902f50d43f8ac4260cf4dc75fc3d7c0d29cd27ec..0000000000000000000000000000000000000000 --- a/geomgnn/access.py +++ /dev/null @@ -1,167 +0,0 @@ -"""Sign-in, daily limits and the layout-size limit of the public demo (handoff/squadds_integration/PLAN_PUBLIC_SPACE.md, amendment -2026-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=). -- 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 dt -import hashlib -import html -import os -import threading -import time -from dataclasses import dataclass -from 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 = 70 -HEADS = {"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)} Run the models on your own " - "computer to avoid these limits.") - - -@dataclass -class 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() diff --git a/geomgnn/api.py b/geomgnn/api.py deleted file mode 100644 index a30350d2a618cdab7d8c2b2b5faaa46cc7873563..0000000000000000000000000000000000000000 --- a/geomgnn/api.py +++ /dev/null @@ -1,536 +0,0 @@ -"""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 a -tlsq_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 contextlib -import hashlib -import json -import os -import threading -import time -import warnings -from pathlib import Path - -import numpy as np -import shapely - -from . import __version__ -from . import infer as I -from ._tlsq.embed import fastprior, proxy -from ._tlsq.uge.graph import scene_graph -from ._tlsq.uge.scene import DEFAULT_STACK, Conductor, Scene -from ._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.lt -EPS_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 priors -VALUE_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-20 -FAR_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 (//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.contextmanager -def _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} diff --git a/geomgnn/app_flagship.py b/geomgnn/app_flagship.py deleted file mode 100644 index 2764c2e1598d963965fc8aa53384db0924da8716..0000000000000000000000000000000000000000 --- a/geomgnn/app_flagship.py +++ /dev/null @@ -1,651 +0,0 @@ -"""Gradio front end of the flagship Space (deploy/GNN_SPACE.md "Flagship Space"; registry flagship_hub, flagship_tiers): three models in -one selector (QCap default, QCap-Lite, QCap-Fast), served through geomgnn.flagship (= the paper Space's code path). Endpoints and argument -order 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=) on gradio_client calls) gets 10 predictions of their own layouts per UTC day, layouts need fewer than -70 conductors with the ground. Aggregate daily counts only (geomgnn.usage). -""" - -from __future__ import annotations - -import functools -import html -import json -import threading -import time -from pathlib import Path - -from tlsq_infer import __version__ as TLSQ_VERSION -import gradio as gr -from tlsq_infer.app_ui import CUSTOM, HEAVY, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn -from tlsq_infer.app_v2 import PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fn -from tlsq_infer.layout import INK, UNMODELLED_COLOR, WINDOW_COLOR, LayoutError, prepare -from tlsq_infer.predict import matrix_csv -from tlsq_infer.registry import load_registry - -from . import __version__ -from . import access as AC -from . import api as A -from . import bundle -from . import ground_ui as GU -from . import flagship as FS -from . import ui as UI -from . import usage as U - -bundle.install() -ORDER = ["accurate", "balanced", "fast"] -MIN_THICKNESS_UM = 1.0 -SI = "Si (cryogenic, training)" -READY = threading.Event() # cleared by the Space entry while the tiers load in the background; every predict waits for it -READY.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. - -```python -from gradio_client import Client, handle_file -c = 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} - -geomgnn {__version__}, tlsq_infer {TLSQ_VERSION}, registry v{reg['version']}.""" - - -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"

{html.escape(x)}

" 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 demo diff --git a/geomgnn/app_gnn.py b/geomgnn/app_gnn.py deleted file mode 100644 index 06ccec6274684be86505f3f24866a35d0137b6f5..0000000000000000000000000000000000000000 --- a/geomgnn/app_gnn.py +++ /dev/null @@ -1,314 +0,0 @@ -"""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 json -import time -from pathlib import Path - -from tlsq_infer import __version__ as TLSQ_VERSION -from tlsq_infer import final as F -from tlsq_infer.app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn, matrix_table -from tlsq_infer.app_v2 import NETWORK_CAP, PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fn -from tlsq_infer.app_v2 import report_md as report_md_v2 -from tlsq_infer.layout import LayoutError, prepare -from tlsq_infer.predict import matrix_csv -from tlsq_infer.registry import load_registry - -from . import __version__ -from . import api as A -from . 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"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).") - return demo diff --git a/geomgnn/app_paper.py b/geomgnn/app_paper.py deleted file mode 100644 index 2f208baf08b8ea1fc5b6707e98402fa01aa3e044..0000000000000000000000000000000000000000 --- a/geomgnn/app_paper.py +++ /dev/null @@ -1,325 +0,0 @@ -"""Gradio front end of the paper Space (deploy/GNN_SPACE.md "Paper Space"; registry paper_hub, paper_arms): one selector over every -arm 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 json -import time -from pathlib import Path - -from tlsq_infer import __version__ as TLSQ_VERSION -import gradio as gr -from tlsq_infer.app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _path, _safe, inspect_fn -from tlsq_infer.app_v2 import NETWORK_CAP, PURGE_AGE_S, _margin_api, _outdir, _prepare, prepare_fn -from tlsq_infer.app_v2 import report_md as report_md_v2 -from tlsq_infer.layout import LayoutError, prepare -from tlsq_infer.predict import matrix_csv -from tlsq_infer.registry import load_registry - -from . import __version__ -from . import api as A -from . import ground_ui as GU -from . import paper as PA -from . 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 the model (the default arm); each arm's paper numbers are under How accurate is this " - "arm?") - - -def header(reg) -> str: - h = reg["paper_hub"] - return UI.header(h["title"], LEDE, "Private preview (paper in preparation). Programmatic use: /predict_gds 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"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.") - return demo diff --git a/geomgnn/bundle.py b/geomgnn/bundle.py deleted file mode 100644 index 551ac41fd78afbdcfe57acee58affb9bf6f16f21..0000000000000000000000000000000000000000 --- a/geomgnn/bundle.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Integrity check of a Space bundle's checkpoint copies. deploy/sync.py --flagship ships each checkpoint without its train_keys (unused at -inference) and records both hashes in models//info.json: _sha256 = the published checkpoint (= registry, the provenance) and -_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 json -from 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 = _check diff --git a/geomgnn/farfield.py b/geomgnn/farfield.py deleted file mode 100644 index 09c356fd375c0472b41f34c0263b8521e9d7c6e3..0000000000000000000000000000000000000000 --- a/geomgnn/farfield.py +++ /dev/null @@ -1,73 +0,0 @@ -"""farfield arms (agents/farfield/PROTOCOL.md sec. 2): the far-pair dipole form, installed on top of an installed v2m -prior (priorv2.installed(policy='fc', dip=True, margin=True)). install(arm, F, P, PV) patches the bound vendor modules -F (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 pair -Slab factor (1 + eps_r R(d)) / (1 + eps_r), R = PV.slab_R at the substrate thickness of P.SUBSTRATE, d = centroid -distance: PV.dipole_far_slab's expression, applied per pair.""" -import time - -import numpy as np -import 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 undo diff --git a/geomgnn/fastmom.py b/geomgnn/fastmom.py deleted file mode 100644 index 6500ae97672071def8cd0ccf599369d544f30636..0000000000000000000000000000000000000000 --- a/geomgnn/fastmom.py +++ /dev/null @@ -1,147 +0,0 @@ -"""Vectorised drop-in replacements for the H-matrix kernel of tlsq.embed.proxy (same mathematics, no per-row scipy -sparse 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() diff --git a/geomgnn/fastprior_pkg.py b/geomgnn/fastprior_pkg.py deleted file mode 100644 index f834e9944cde430fab9b0ec6e4544a936ab849b0..0000000000000000000000000000000000000000 --- a/geomgnn/fastprior_pkg.py +++ /dev/null @@ -1,1297 +0,0 @@ -"""fastprior_pkg: switchable speed components for the FROZEN physical prior of the P2d GNN (micro_mom_loc at ppg 1.5 -and 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 verbatim -where 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), certified -Parallel windows fork (the vendor's pool); on macOS they are always off (Accelerate is not fork-safe) and the prior -runs 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 contextlib -import inspect -import json -import os -import sys -import tempfile -import time - -import numpy as np -from 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-7 -COMPONENTS = ("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 counters -LOG: 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 workers -try: - 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.contextmanager -def 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) diff --git a/geomgnn/flagship.py b/geomgnn/flagship.py deleted file mode 100644 index 9a152bc5efb72065e123cc9d1927916a4b3ca931..0000000000000000000000000000000000000000 --- a/geomgnn/flagship.py +++ /dev/null @@ -1,69 +0,0 @@ -"""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; every -result, 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 the -learned prior surrogate -> networks), unchanged. `view(reg)` is the registry seen with paper_arms / paper_hub replaced by -flagship_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) diff --git a/geomgnn/ground_ui.py b/geomgnn/ground_ui.py deleted file mode 100644 index bcadf77d70bce82345e337cce70589693e87c85d..0000000000000000000000000000000000000000 --- a/geomgnn/ground_ui.py +++ /dev/null @@ -1,246 +0,0 @@ -"""'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 switch -pieces between ground and conductor. Predict stays disabled until the pick is confirmed.""" - -from __future__ import annotations - -import gradio as gr -import numpy as np -import shapely -from tlsq_infer.app_ui import _path, _roles -from 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("", 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") diff --git a/geomgnn/infer.py b/geomgnn/infer.py deleted file mode 100644 index 6b0c92be5adc0320e6a7ace880b58585e228694c..0000000000000000000000000000000000000000 --- a/geomgnn/infer.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Label-free standalone prediction for geomfast checkpoints. -Only checkpoints, geometry, and optional priors are accepted; never Q3D labels. -""" -import os -os.environ.setdefault('PYTHONDONTWRITEBYTECODE','1') -import sys,importlib.util,time -from pathlib import Path -import numpy as np -import torch -W=Path(__file__).resolve().parent -from .pilot_p2 import build_model -from ._tlsq.uge.scene import scene_from_gds,tlsq_namer -from ._tlsq.uge.graph import scene_graph -from ._tlsq.uge.blocks import edge_matrix -from ._tlsq.uge.proxies import CapacitanceMoM -from ._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)) diff --git a/geomgnn/learned_prior.py b/geomgnn/learned_prior.py deleted file mode 100644 index ce0c22d4a88c843113e8dcc419e1311493b046a0..0000000000000000000000000000000000000000 --- a/geomgnn/learned_prior.py +++ /dev/null @@ -1,49 +0,0 @@ -"""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 the -network: pack the scene-graph row with the P2d schema (scripts/learnedprior/lp_label.py `pack`), predict log P at 1.5 and 3 -panels per gap with lp_surrogate.predict_bucket (one layout), and return the symmetric positive mutual matrices that -infer.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 S -from ._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 out diff --git a/geomgnn/levelpar.py b/geomgnn/levelpar.py deleted file mode 100644 index 9cee556d74095c94c8175d5e58dfa82572429b64..0000000000000000000000000000000000000000 --- a/geomgnn/levelpar.py +++ /dev/null @@ -1,97 +0,0 @@ -"""Mesh levels of the prior concurrently (agents/embedspeed). The two thin-film solves (e.g. 1.5 and 3 panels per gap) are -independent; on macOS each runs its windows serially and keeps only ~2-5 cores busy, so the extra levels run in spawned -worker processes that install the same prior stack (geomgnn.api.set_prior_stack with the recorded registry prior and -threads) 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 os -import sys -import time -from concurrent.futures import ProcessPoolExecutor -from 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)} diff --git a/geomgnn/lp_surrogate.py b/geomgnn/lp_surrogate.py deleted file mode 100644 index 94c1294f5ca74de155a3dbb65fbd6a1f7daa3f62..0000000000000000000000000000000000000000 --- a/geomgnn/lp_surrogate.py +++ /dev/null @@ -1,396 +0,0 @@ -"""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 argparse -import glob -import hashlib -import json -import platform -import time -from pathlib import Path - -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - -HERE = Path(__file__).resolve().parent -SCHEMA = 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"} - - -# ----------------------------------------------------------------------------------------------------------- data -def 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 - - -# ---------------------------------------------------------------------------------------------------------- model -def 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) - - -# ------------------------------------------------------------------------------------------------------- training -def 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) diff --git a/geomgnn/overlap.py b/geomgnn/overlap.py deleted file mode 100644 index 80ac99d1e537512418c095f9368411e4a5a7b61f..0000000000000000000000000000000000000000 --- a/geomgnn/overlap.py +++ /dev/null @@ -1,80 +0,0 @@ -"""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 the -prior 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 process -and reused. TLSQ_OVERLAP=0 turns it off; layouts with fewer than TLSQ_OVERLAP_MIN_N conductors (default 30), and machines with fewer than -TLSQ_OVERLAP_MIN_THREADS threads (default 4), stay sequential. -""" -from __future__ import annotations - -import os -import sys -from concurrent.futures import Future, ProcessPoolExecutor -from 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()) diff --git a/geomgnn/paper.py b/geomgnn/paper.py deleted file mode 100644 index 1546df4c1352baa2a9281cbb058b00e12ea3be4f..0000000000000000000000000000000000000000 --- a/geomgnn/paper.py +++ /dev/null @@ -1,439 +0,0 @@ -"""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 hashlib -import json -import os -import time -from collections import OrderedDict -from pathlib import Path - -import numpy as np - -from . import __version__ -from . import api as A -from . import infer as I -from . import x1_core as X -from ._tlsq.embed import fastprior, proxy -from ._tlsq.uge.graph import scene_graph - -lt = I.lt -ALPHA = 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 (//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) diff --git a/geomgnn/pilot_p2.py b/geomgnn/pilot_p2.py deleted file mode 100644 index 5cd7702720fcc5bb9e1985c95aa4430ce0089031..0000000000000000000000000000000000000000 --- a/geomgnn/pilot_p2.py +++ /dev/null @@ -1,214 +0,0 @@ -"""Isolated P1 pilot. No external-test loaders or paths are implemented.""" -import os -os.environ.setdefault('PYTHONDONTWRITEBYTECODE','1') -import argparse, hashlib, json, pickle, time, platform, sys -from pathlib import Path -import numpy as np -ARMS=['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) diff --git a/geomgnn/priorv2.py b/geomgnn/priorv2.py deleted file mode 100644 index e216c68d79ecf4709ea3e6c167bbf2000646ae7a..0000000000000000000000000000000000000000 --- a/geomgnn/priorv2.py +++ /dev/null @@ -1,215 +0,0 @@ -"""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; everything -else runs the frozen code path.""" -import time -import contextlib -import numpy as np -import shapely -from ._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 pairs -MARGIN = [] # 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.contextmanager -def 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) diff --git a/geomgnn/rejtail_fv.py b/geomgnn/rejtail_fv.py deleted file mode 100644 index e1f3e9a1c4d168780cd664c493e7e4c87cd11a75..0000000000000000000000000000000000000000 --- a/geomgnn/rejtail_fv.py +++ /dev/null @@ -1,115 +0,0 @@ -"""rejtail fix fv (agents/rejtail/RESULTS.md, scripts/rejtail/rt.py; user approval 2026-10-17): value-preserving removal of -the rejection tail of the windowed micro-MoM prior (`fastprior._window_solve`, all_rhs=False, layouts with > 8 conductors). - -A window attempt whose mesh leaves a metal without a panel is always rejected, whatever its solve returns. The frozen code -still solves it, and above DENSE_MAX panels the H-matrix PCG cannot converge: the panel-less metal has a zero right-hand -side, so the residual is 0/0 = NaN, and it runs 1,000 iterations before raising. fv meshes such attempts but does not -solve them. If the loop ends without an accepted attempt, the result the unpatched code returns is rebuilt by solving -the deferred dense attempts lazily: - keep_last_solved=True (frozen geomfast stage): the latest attempt whose solve succeeded, newest first; - keep_last_solved=False (tlsq_infer vendor): the last attempt's own solve, else the same RuntimeError. -Every accepted solve is the same call on the same mesh, so the result is bit-identical (621 layouts in RESULTS.md; -deploy/tests/test_gnn_space.py re-checks it). all_rhs=True calls (single window, N <= 8) run the original function. -The same file is shipped as geomgnn/rejtail_fv.py and tlsq_infer/_vendor/rejtail_fv.py; only the import line differs. -""" -from __future__ import annotations - -import time - -import numpy as np - -from ._tlsq.embed import fastprior as F -from ._tlsq.embed import proxy as P - -KEEP_LAST_SOLVED = True -_ORIG = {} - - -def _solve(c, wh, o, metals, cols, eps_r): - """One attempt solved exactly as the original loop does (windowed: LDL^T dense, H-matrix PCG above DENSE_MAX). - Returns (R, assemble seconds).""" - 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 window_solve(metals: list, n_core: int, h: float, budget: float, eps_r: float, all_rhs: bool, levels: tuple = ()) -> tuple: - 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 = [] # per attempt, oldest first: ("R", R) | ("err",) | ("mesh", c, wh, o) deferred dense | ("doomed",) deferred H-matrix - 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) > P.DENSE_MAX else ("mesh", c, wh, o)) - ok = False - else: - t = time.perf_counter() - try: - R, ta = _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 KEEP_LAST_SOLVED else hist[-1:]): - 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)[0] - break - except np.linalg.LinAlgError: - continue - t_sol += time.perf_counter() - t - if R is None: - raise RuntimeError(f"window solve failed: no positive-definite system after {refined} refinements (h={hh:.4g} um); " - "the window has no valid solution at this mesh") - 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 install() -> None: - """Replace fastprior._window_solve (a module global, looked up at call time, also in the forked window workers).""" - if not _ORIG: - _ORIG["window_solve"] = F._window_solve - F._window_solve = window_solve - - -def uninstall() -> None: - if _ORIG: - F._window_solve = _ORIG.pop("window_solve") - - -def installed() -> bool: - return bool(_ORIG) diff --git a/geomgnn/respcache.py b/geomgnn/respcache.py deleted file mode 100644 index a815d8161891934e45df11582bd908cc2e5235ef..0000000000000000000000000000000000000000 --- a/geomgnn/respcache.py +++ /dev/null @@ -1,96 +0,0 @@ -"""In-memory response cache of the Spaces (agents/embedspeed; user decision 2026-10-20): a size-bounded LRU of finished -predictions keyed by the prepared layout (ground and conductor geometry, names) and every setting of the request. Entries live -only in this process's memory while the Space runs. TLSQ_RESPONSE_CACHE = max entries (0 = off), TLSQ_RESPONSE_CACHE_MB = -max total size of the pickled entries.""" -from __future__ import annotations - -import copy -import hashlib -import os -import pickle -import threading -from collections import OrderedDict -from pathlib import Path - -_LRU: OrderedDict = OrderedDict() -_LOCK = threading.Lock() -_BYTES = [0] - - -def _limits() -> tuple: - return int(os.environ.get("TLSQ_RESPONSE_CACHE", "0")), float(os.environ.get("TLSQ_RESPONSE_CACHE_MB", "1024")) * 2**20 - - -def key(lay, *settings) -> str: - import shapely - h = hashlib.sha256(repr((settings, list(lay.names))).encode()) - for g in [lay.ground, *lay.conductors]: - h.update(shapely.to_wkb(g)) - return h.hexdigest() - - -def has(lay, settings: tuple) -> bool: - if _limits()[0] <= 0: - return False - k = key(lay, *settings) - with _LOCK: - return k in _LRU - - -def cached(lay, settings: tuple, fn): - """fn() through the cache (a deep copy is stored and returned, so callers may modify their result).""" - n, mb = _limits() - if n <= 0: - return fn() - k = key(lay, *settings) - with _LOCK: - if k in _LRU: - _LRU.move_to_end(k) - res = copy.deepcopy(_LRU[k][0]) - if isinstance(res.get("timing_s"), dict): - res["timing_s"]["response_cache_hit"] = True - return res - res = fn() - size = len(pickle.dumps(res, protocol=5)) - if size > mb: - return res - with _LOCK: - _LRU[k] = (copy.deepcopy(res), size) - _BYTES[0] += size - while len(_LRU) > n or _BYTES[0] > mb: - _, (_, s) = _LRU.popitem(last=False) - _BYTES[0] -= s - return res - - -def dump(path) -> int: - """Pickle the entries (image build: the bundled examples, loaded back by load_items + put_many at start).""" - with _LOCK: - items = list(_LRU.items()) - Path(path).parent.mkdir(parents=True, exist_ok=True) - Path(path).write_bytes(pickle.dumps(items, protocol=5)) - return len(items) - - -def load_items(path) -> list: - return pickle.loads(Path(path).read_bytes()) - - -def put_many(items) -> int: - n, mb = _limits() - if n <= 0: - return 0 - with _LOCK: - for k, (res, size) in items: - if k not in _LRU: - _LRU[k] = (res, size) - _BYTES[0] += size - while len(_LRU) > n or _BYTES[0] > mb: - _, (_, s) = _LRU.popitem(last=False) - _BYTES[0] -= s - return len(_LRU) - - -def stats() -> dict: - with _LOCK: - return {"entries": len(_LRU), "mb": _BYTES[0] / 2**20} diff --git a/geomgnn/schema_p2d.json b/geomgnn/schema_p2d.json deleted file mode 100644 index 13943022ba85c7b66321f18b38e8bd08303d022c..0000000000000000000000000000000000000000 --- a/geomgnn/schema_p2d.json +++ /dev/null @@ -1,123 +0,0 @@ -{ - "nodekeys": [ - "compactness", - "fourier_00", - "fourier_01", - "fourier_02", - "fourier_03", - "fourier_04", - "fourier_05", - "fourier_06", - "fourier_07", - "fourier_08", - "fourier_09", - "fourier_10", - "fourier_11", - "fourier_12", - "fourier_13", - "fourier_14", - "fourier_15", - "fourier_16", - "fourier_17", - "fourier_18", - "fourier_19", - "fourier_20", - "fourier_21", - "fourier_22", - "fourier_23", - "fourier_24", - "fourier_25", - "fourier_26", - "fourier_27", - "fourier_28", - "fourier_29", - "fourier_30", - "fourier_31", - "fourier_32", - "gran_00", - "gran_01", - "gran_02", - "gran_03", - "gran_04", - "gran_05", - "gran_06", - "gran_07", - "gran_08", - "gran_09", - "gran_10", - "gran_11", - "gran_12", - "gran_13", - "gran_14", - "gran_15", - "log_Imajor_over_A2", - "log_area", - "log_aspect", - "log_elongation", - "log_min_halfwidth", - "log_perimeter", - "log_width", - "n_holes", - "role_ground", - "solidity", - "missing_log_min_halfwidth" - ], - "edgekeys": [ - "is_ground_pair", - "lg_log_cps", - "lg_log_dmin", - "lg_mom_0.5", - "lg_mom_1", - "lg_mom_2", - "lg_sep_00", - "lg_sep_01", - "lg_sep_02", - "lg_sep_03", - "lg_sep_04", - "lg_sep_05", - "lg_sep_06", - "lg_sep_07", - "lg_sep_08", - "lg_sep_09", - "log_cps", - "log_dmin", - "lt_e150", - "lt_e400", - "lt_e50", - "lt_g150", - "lt_g400", - "lt_g50", - "lt_o150", - "lt_o400", - "lt_o50", - "mom_0.5", - "mom_1", - "mom_2", - "sep_00", - "sep_01", - "sep_02", - "sep_03", - "sep_04", - "sep_05", - "sep_06", - "sep_07", - "sep_08", - "sep_09", - "share_absdiff", - "share_mean" - ], - "globkeys": [ - "log_chip_area", - "log_pocket_area", - "log_substrate_t", - "eps_eff" - ], - "base_sha": "03edcbc72325f1522ad3998aff25b9b0ec86e0af4f479a872c76b144c45605bc", - "extra_sha": "b72762b01169a9e754265a7fc256c4f8a11930a235da340ebc948e04463007c1", - "physics": { - "prior_method": "local_gap", - "alpha": 0.49685219816506904, - "ensemble": "arithmetic mean of complete predicted Maxwell matrices", - "audit": "prior_audit.json" - } -} \ No newline at end of file diff --git a/geomgnn/static/qcap_badge16_light_32px.png b/geomgnn/static/qcap_badge16_light_32px.png deleted file mode 100644 index a06cc9efb3bbdf85d8e575d77024f015f408c58e..0000000000000000000000000000000000000000 Binary files a/geomgnn/static/qcap_badge16_light_32px.png and /dev/null differ diff --git a/geomgnn/static/qcap_compact_dark.svg b/geomgnn/static/qcap_compact_dark.svg deleted file mode 100644 index f054aca515004b91137697c4a669b54b7e6b8e3b..0000000000000000000000000000000000000000 --- a/geomgnn/static/qcap_compact_dark.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/geomgnn/static/qcap_compact_light.svg b/geomgnn/static/qcap_compact_light.svg deleted file mode 100644 index 2b4a09b13fffe9e14d5a2998c64d5706a1a32674..0000000000000000000000000000000000000000 --- a/geomgnn/static/qcap_compact_light.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/geomgnn/static/qcap_favicon.svg b/geomgnn/static/qcap_favicon.svg deleted file mode 100644 index 5efa09a0417d6b62d4e10523c054ecb159cca8f9..0000000000000000000000000000000000000000 --- a/geomgnn/static/qcap_favicon.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/geomgnn/static/squadds_dark.png b/geomgnn/static/squadds_dark.png deleted file mode 100644 index fa602dccae671ca9f9e931c3ee2f9155220f8786..0000000000000000000000000000000000000000 Binary files a/geomgnn/static/squadds_dark.png and /dev/null differ diff --git a/geomgnn/static/squadds_light.png b/geomgnn/static/squadds_light.png deleted file mode 100644 index c730dcc80bba15be8de3b7d67119d5eabfac0c76..0000000000000000000000000000000000000000 Binary files a/geomgnn/static/squadds_light.png and /dev/null differ diff --git a/geomgnn/train_mf.py b/geomgnn/train_mf.py deleted file mode 100644 index 96ac63251e7dd46abb5432f7c22bd278c173868f..0000000000000000000000000000000000000000 --- a/geomgnn/train_mf.py +++ /dev/null @@ -1,190 +0,0 @@ -"""multifid arms (agents/multifid/PROTOCOL.md): P2d recipe (geomfast ragged.py fit) with a chosen MoM level set, an optional -learned convergence-curve extrapolation with a MoM-limit anchor, and a detached variance head. TRAIN fits; VAL predicted. - prepare: prepared_p2d shards + fresh levels -> multifid/prepared/n*.npz (lv: B x F x 4 at ppg 0.375, 0.75, 1.5, 3) - fit --arm R|L2|L2x|L3|L3x --seed s""" -import os -os.environ.setdefault('PYTHONDONTWRITEBYTECODE', '1') -import argparse, json, pickle, time, hashlib, platform -from pathlib import Path -import numpy as np - -GF = Path(os.environ.get('MF_GF', '/project2/shaas_31/shanto/geomfast')) -OUT = Path(os.environ.get('MF_OUT', '/project2/shaas_31/shanto/multifid')) -PPG = [0.375, 0.75, 1.5, 3.0] -ARMS = {'R': ([1.5, 3.0], False), 'L2': ([0.375, 0.75], False), 'L2x': ([0.375, 0.75], True), - 'L3': ([0.375, 0.75, 1.5], False), 'L3x': ([0.375, 0.75, 1.5], True)} - - -def digest(p): - return hashlib.sha256(Path(p).read_bytes()).hexdigest() - - -def prepare(a): - recs = {} - for f in sorted(list((OUT / 'levels_hpc').glob('*.pkl')) + list((OUT / 'levels').glob('*.pkl'))): - if f.name.endswith('.partial.pkl'): - continue - d = pickle.load(f.open('rb')) - assert not d['meta']['errors'], (f, d['meta']['errors']) - recs.update(d['records']) - out = OUT / 'prepared' - out.mkdir(exist_ok=False) - for p in sorted((GF / 'prepared_p2d').glob('n*.npz')): - z = dict(np.load(p, allow_pickle=False)) - B, F = z['pri'].shape[:2] - lv = np.zeros((B, F, 4), np.float32) - for b, k in enumerate(z['key']): - r = recs[str(k)]['levels'] - lv[b, :, 0] = r[0.375]['mutual'] - lv[b, :, 1] = r[0.75]['mutual'] - lv[b, :, 2:] = z['pri'][b] # cached P2d priors at 1.5, 3 (parity-checked on VAL) - assert np.isfinite(lv).all() and (lv > 0).all() - z['lv'] = lv - np.savez_compressed(out / p.name, **z) - (out / 'schema.json').write_text((GF / 'prepared_p2d/schema.json').read_text()) - print('PREPARED', len(recs), flush=True) - - -def build(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, 2) - self.var = mlp(3 * width, 1) - self.closure = mlp(width, 1) - for m in [self.head, self.closure]: - nn.init.zeros_(m[-1].weight); nn.init.zeros_(m[-1].bias) - - def forward(self, X, E, G, M, PM, pairs, anchor, slope, bbase, curve): - 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) - deg = torch.zeros_like(M, dtype=X.dtype); deg.index_add_(1, i, PM.float()); deg.index_add_(1, j, PM.float()) - h = (h + up(torch.cat([h, agg / deg.clamp_min(1)[:, :, None]], -1))) * M[:, :, None] - feat = torch.cat([h[:, i] + h[:, j], abs(h[:, i] - h[:, j]), e], -1) - out = self.head(feat) - r, q = out[..., 0], out[..., 1] - p = 0.25 + 2.25 * torch.sigmoid(q) - m = anchor + slope / (2.0 ** p - 1.0) if curve else anchor - logc = (m + 0.2 * torch.tanh(r)).clamp(-25, 20) - logvar = self.var(feat.detach()).squeeze(-1).clamp(-16, 4) - 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 - C = C + torch.diag_embed(-C.sum(-1) + b) - return C, logc, m, p, logvar - 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) - levels, curve = ARMS[a.arm] - li = [PPG.index(p) for p in levels] - out = OUT / 'runs' / f'{a.arm}_s{a.seed}' - out.mkdir(parents=True, exist_ok=False) - root = OUT / 'prepared' - schema = json.loads((root / 'schema.json').read_text()) - ds = [dict(np.load(p, allow_pickle=False)) for p in sorted(root.glob('n*.npz'))] - ei = schema['edgekeys'].index('is_ground_pair') - closure = {} - for flag in [0, 1]: - bs = [] - for d in ds: - tr = d['split'] == 'train' - bs.extend(np.log(d['C'].sum(-1).clip(1e-8)[(d['sig'] == bool(flag)) & tr[:, None]]).tolist()) - closure[str(flag)] = float(np.median(bs)) - for d in ds: - L = np.log(d['lv'].astype(np.float64)) - lf, lc = L[:, :, li[-1]], L[:, :, li[-2]] - d['slope'] = (lf - lc).astype(np.float32) - d['anchor'] = (lf if curve else 2 * lf - lc).astype(np.float32) - d['fine'] = (2 * L[:, :, 3] - L[:, :, 2]).astype(np.float32) # MoM-limit proxy (anchor target, TRAIN only) - d['E'] = np.concatenate([d['E']] + [(L[:, :, li[k + 1]] - L[:, :, li[k]])[:, :, None].astype(np.float32) - for k in range(len(li) - 1)], -1) - d['bbase'] = np.where(d['sig'], closure['1'], closure['0']).astype(np.float32) - scales = {} - for name in ['X', 'E', 'G']: - v = np.concatenate([d[name][d['split'] == 'train'].reshape(-1, d[name].shape[-1]) for d in ds]) - med = np.nanmedian(v, 0); iq = np.nanpercentile(v, 75, 0) - np.nanpercentile(v, 25, 0); iq = np.where(iq > 1e-6, iq, 1) - scales[name] = dict(median=med.tolist(), iqr=iq.tolist()) - for d in ds: - d[name] = np.clip((np.where(np.isfinite(d[name]), d[name], med) - med) / iq, -10, 10).astype(np.float32) - tensors = []; groups = {} - for k, d in enumerate(ds): - z = {n: torch.from_numpy(d[n]) for n in ['X', 'E', 'G', 'C', 'sig', 'pairs', 'anchor', 'slope', 'fine', 'bbase']} - z['M'] = torch.ones(d['sig'].shape, dtype=torch.bool); z['PM'] = torch.ones(d['anchor'].shape, dtype=torch.bool) - tensors.append(z) - for fam in set(d['family']): - idx = np.flatnonzero((d['family'] == fam) & (d['split'] == 'train')) - if len(idx): - groups.setdefault(fam, []).append((k, idx)) - families = sorted(groups) - model = build(ds[0]['X'].shape[-1], ds[0]['E'].shape[-1], ds[0]['G'].shape[-1], 2) - 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) - - def fwd(k, b): - z = tensors[k] - return model(z['X'][b], z['E'][b], z['G'][b], z['M'][b], z['PM'][b], z['pairs'], z['anchor'][b], z['slope'][b], - z['bbase'][b], curve) - hist = []; start = time.perf_counter() - for step in range(a.steps): - fam = families[rng.integers(len(families))]; gs = groups[fam]; w = np.array([len(v) for _, v in gs]) - k, idx = gs[rng.choice(len(gs), p=w / w.sum())]; z = tensors[k]; i, j = z['pairs'].T - b = rng.choice(idx, max(1, min(64, 8192 // len(z['pairs'])))) - pred, logc, m, p, logvar = fwd(k, b); C = z['C'][b] - y = (-C[:, i, j]).clamp_min(1e-12).log() - pl = F.huber_loss(logc, y, delta=.05) - dl = F.huber_loss(pred.diagonal(dim1=-2, dim2=-1).log(), C.diagonal(dim1=-2, dim2=-1).log(), delta=.05, reduction='none') - sig = z['sig'][b] - loss = pl + .1 * dl[sig].mean() + .02 * dl[~sig].mean() - if curve: - loss = loss + .5 * F.huber_loss(m, z['fine'][b], delta=.05) - res = (logc - y).detach() - loss = loss + .1 * (0.5 * (logvar + res ** 2 / logvar.exp())).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 % 1000 == 0: - hist.append(dict(step=step, loss=float(loss.detach()), seconds=time.perf_counter() - start)); print(hist[-1], flush=True) - train_s = time.perf_counter() - start - torch.save(dict(state=model.state_dict(), arm=a.arm, levels=levels, curve=curve, scales=scales, closure=closure, - seed=a.seed, schema=schema, data_sha={p.name: digest(p) for p in root.glob('*.npz')}, code_sha=digest(__file__)), - out / 'model.pt') - model.eval(); preds = {} - with torch.inference_mode(): - for k, d in enumerate(ds): - for b in np.flatnonzero(d['split'] == 'val'): - C, logc, m, p, logvar = fwd(k, [b]) - preds[str(d['key'][b])] = dict(C=C[0].numpy(), logc=logc[0].numpy(), m=m[0].numpy(), p=p[0].numpy(), - logvar=logvar[0].numpy()) - pickle.dump(preds, (out / 'validation_predictions.pkl').open('wb')) - ci = Path('/proc/cpuinfo') - cpu = next((s.split(':', 1)[1].strip() for s in ci.read_text().splitlines() if s.startswith('model name')), '?') if ci.exists() else platform.processor() - (out / 'run.json').write_text(json.dumps(dict(arm=a.arm, seed=a.seed, steps=a.steps, host=platform.node(), cpu=cpu, - threads=a.threads, train_seconds=train_s, history=hist), indent=2)) - print('DONE', a.arm, a.seed, train_s, flush=True) - - -if __name__ == '__main__': - ap = argparse.ArgumentParser(); sub = ap.add_subparsers(dest='cmd', required=True) - sub.add_parser('prepare') - q = sub.add_parser('fit'); q.add_argument('--arm', choices=list(ARMS), required=True); q.add_argument('--seed', type=int, default=0) - q.add_argument('--steps', type=int, default=18000); q.add_argument('--threads', type=int, default=2) - a = ap.parse_args(); {'prepare': prepare, 'fit': fit}[a.cmd](a) diff --git a/geomgnn/ui.py b/geomgnn/ui.py deleted file mode 100644 index ed62cffb84b5d3075b9e15754373a1d4d4d1f584..0000000000000000000000000000000000000000 --- a/geomgnn/ui.py +++ /dev/null @@ -1,447 +0,0 @@ -"""Shared look and result rendering of the flagship and paper Spaces (deploy/GNN_SPACE.md): SQuADDS theme and CSS, the header, -the Maxwell matrix view (conductor names as headers, 3 decimals shown; the CSV / JSON downloads keep full precision), the status -callout above the matrix, stale-result marking, inline errors and the layer-role editor.""" - -from __future__ import annotations - -import base64 -import html -import re -import traceback -import warnings -from pathlib import Path - -import gradio as gr -import numpy as np -from tlsq_infer.layout import LayoutError - -from . import api as A - -STATIC = Path(__file__).parent / "static" -ROLES = ["ground", "conductor", "ground+conductor", "ignore"] -MAT = ["tl-matrix"] -REEXPORT = ("Re-export the layout as GDSII (.gds) from KLayout (File > Save As, format GDS2) or gdstk (Library.write_gds), then " - "upload it again.") -EMPTY = "

The matrix appears here after Predict.

" -STALE = ("
Inputs changed. The matrix shown is for the previous inputs. " - "Press Predict to update it.
") -MATRIX_NOTE = ("

The diagonal holds the self capacitances and the off-diagonal entries are minus the mutual " - "capacitances, in fF. The table shows 3 decimals, and the CSV and JSON keep full precision. † " - "The ground self term is only indicative, since it depends on the chip boundary.

" - "Swipe the matrix sideways for more columns.

") -GROUND_FLAG = "† The ground self term is only indicative, since it depends on the chip boundary." - - -INK = gr.themes.Color(c50="#f3f6fa", c100="#e4eaf2", c200="#c9d5e4", c300="#a3b6cf", c400="#7590b3", c500="#4f6d94", c600="#3b5a80", - c700="#2d4a6e", c800="#1e3a5f", c900="#152b47", c950="#0c1a2d", name="ink") - -CSS = """ -.gradio-container { --tl-ok: #14532d; --tl-ok-bg: #effaf3; --tl-ok-line: #9fd8b4; --tl-warn: #6b3d0a; --tl-warn-bg: #fff8e6; - --tl-warn-line: #e9c46a; --tl-bad: #7f1d1d; --tl-bad-bg: #fdf1f1; --tl-bad-line: #eba3a3; --tl-mute: #4b5563; --tl-mute-bg: #f3f4f6; - --tl-mute-line: #d1d5db; --tl-subtle: #4b5563; } -.dark .gradio-container, .gradio-container.dark { --tl-ok: #bbf0cf; --tl-ok-bg: #0f2a1b; --tl-ok-line: #2f6b47; --tl-warn: #f8dfa4; - --tl-warn-bg: #2d2208; --tl-warn-line: #7a5a17; --tl-bad: #f9c8c8; --tl-bad-bg: #2f1212; --tl-bad-line: #7f2d2d; --tl-mute: #cbd5e1; - --tl-mute-bg: #1f2937; --tl-mute-line: #374151; --tl-subtle: #b6bfcc; } -::selection { background: #c9d5e4; color: #0c1a2d; } -.gradio-container input, .gradio-container textarea { caret-color: #1e3a5f; } -#tl-header { display: flex; flex-direction: column; gap: 6px; margin-bottom: 4px; } -#tl-header .tl-brand { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; } -#tl-header img { height: 34px; width: auto; } -#tl-header .tl-logo-dark, .dark #tl-header .tl-logo-light { display: none; } -.dark #tl-header .tl-logo-dark { display: inline-block; } -#tl-header h1 { font-family: "Source Serif 4", Georgia, serif; font-weight: 600; font-size: 1.9rem; letter-spacing: -0.01em; - margin: 0; line-height: 1.15; border-left: 1px solid var(--border-color-primary); padding-left: 14px; } -#tl-header .tl-marks { gap: 0; } -#tl-header .tl-marks img.tl-product { height: 34px; margin-left: 16px; padding-left: 16px; border-left: 1px solid var(--border-color-primary); - box-sizing: content-box; } -#tl-header h1.tl-title { border-left: none; padding-left: 0; margin-top: 10px; } -#tl-header p { margin: 0; max-width: 78ch; line-height: 1.55; } -#tl-header .tl-meta { font-size: 0.875rem; color: var(--tl-subtle); } -#tl-header a { padding: 0; margin: 0; text-underline-offset: 2px; } -.gradio-container .label-wrap { text-align: left; align-items: center; gap: 12px; } -.gradio-container .label-wrap .icon { flex: 0 0 auto; } -.gradio-container button.secondary { border: 1px solid var(--button-secondary-border-color); font-size: 0.875rem; font-weight: 500; - padding: 0 16px; } -.tl-flush .html-container { padding: 0 !important; } -.gradio-container h2 { font-family: "Source Serif 4", Georgia, serif; font-weight: 600; margin-top: 18px; } -.gradio-container .prose p, .gradio-container .prose li, .gradio-container .prose blockquote { max-width: 80ch; } -.tl-status { border: 1px solid var(--tl-mute-line); background: var(--tl-mute-bg); color: var(--tl-mute); border-radius: 8px; - padding: 12px 16px; line-height: 1.5; } -.tl-status p { margin: 0; max-width: 80ch; } -.tl-status p + p { margin-top: 4px; } -.tl-status.ok { border-color: var(--tl-ok-line); background: var(--tl-ok-bg); color: var(--tl-ok); } -.tl-status.warn { border-color: var(--tl-warn-line); background: var(--tl-warn-bg); color: var(--tl-warn); } -.tl-status.bad { border-color: var(--tl-bad-line); background: var(--tl-bad-bg); color: var(--tl-bad); } -.tl-matrix table { font-variant-numeric: tabular-nums; } -.tl-matrix th:not(:first-child) .cell-wrap, .tl-matrix th:not(:first-child) .header-content { justify-content: flex-end; text-align: right; - width: 100%; } -.tl-stale { opacity: 0.4; filter: grayscale(1); transition: opacity 0.2s ease-out; } -.tl-note { font-size: 0.875rem; color: var(--tl-subtle); margin: 6px 0 0; max-width: 80ch; } -.tl-flag { font-weight: 600; } -.tl-scroll-hint { display: none; } -.gradio-container input[type=radio]:focus-visible, .gradio-container input[type=checkbox]:focus-visible { - outline: 2px solid #1e3a5f !important; outline-offset: 2px !important; } -.dark .gradio-container input[type=radio]:focus-visible, .dark .gradio-container input[type=checkbox]:focus-visible { - outline-color: #a3b6cf !important; } -.gradio-container label:has(input[type=radio]:focus-visible), .gradio-container label:has(input[type=checkbox]:focus-visible) { - box-shadow: 0 0 0 2px #1e3a5f; } -.gradio-container button:focus-visible { outline: 2px solid #1e3a5f; outline-offset: 2px; } -#tl-footer { margin-top: 1.5rem; padding-top: .8rem; border-top: 1px solid var(--border-color-primary); font-size: .85rem; color: var(--body-text-color-subdued); text-align: center; } -#tl-footer p { margin: .15rem 0; display: block !important; width: 100% !important; max-width: none !important; } -#tl-footer a { display: inline !important; margin: 0 !important; padding: 0 !important; min-height: 0 !important; } -#tl-tier label, .tl-check label, .tl-touch button, .gradio-container button.primary, .gradio-container button.secondary { - min-height: 44px !important; } -@media (max-width: 640px) { /* Gradio prefixes rules inside @media with its container: no .gradio-container here */ - #tl-header h1 { font-size: 1.5rem; border-left: none; padding-left: 0; } - .tl-login > * { flex: 1 1 100% !important; } /* sign-in note under the button, full width */ - .tl-login > .tl-note { padding-top: 0 !important; margin-top: 0 !important; } - .tl-scroll-hint { display: block; } - .tl-matrix table { font-size: 0.8125rem; } - .label-wrap, .gallery-item, button.sm, input[type=number] { min-height: 44px !important; } - button.icon-button { min-width: 44px !important; min-height: 44px !important; } - #tl-viewer:not(:has(img)) { display: none !important; } - #tl-viewer, #tl-ground-img { padding-top: 52px !important; } - #tl-viewer .image-container > .icon-button-wrapper, #tl-ground-img .image-container > .icon-button-wrapper { top: -52px !important; } -} -#tl-viewer:not(:has(img)) { height: 340px !important; } -.gradio-container footer, .gradio-container footer a, .gradio-container footer button, .gradio-container footer .divider { - color: var(--tl-subtle) !important; } -.gradio-container footer img { opacity: 0.75; } -.gradio-container .wrap .or { color: var(--tl-subtle) !important; } -#tl-view { flex-grow: 0; } -#tl-view .wrap { gap: 0; } -#tl-view label { min-height: 44px; border-radius: 0; margin: 0; padding: 0 16px; } -#tl-view label:first-child { border-radius: 6px 0 0 6px; } -#tl-view label:last-child { border-radius: 0 6px 6px 0; } -#tl-view input { position: absolute; opacity: 0; width: 1px; height: 1px; } -.tl-viewbar { align-items: center; gap: 8px; } -.tl-viewbar { flex-wrap: nowrap !important; } -.tl-viewbar > fieldset, .tl-viewbar > button { flex: 0 0 auto !important; width: auto !important; min-width: 0 !important; } - -""" - - -def theme(): - return gr.themes.Default(primary_hue=INK, secondary_hue=INK, neutral_hue=gr.themes.colors.gray, - font=[gr.themes.GoogleFont("Source Sans 3"), "ui-sans-serif", "system-ui", "sans-serif", - gr.themes.GoogleFont("Source Serif 4", (600,))], - font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace"]).set( - button_primary_background_fill="*primary_800", button_primary_background_fill_hover="*primary_900", - button_primary_border_color="*primary_800", button_primary_border_color_hover="*primary_900", - button_primary_text_color="white", button_primary_text_color_hover="white", - button_primary_background_fill_dark="*primary_200", button_primary_background_fill_hover_dark="*primary_100", - button_primary_border_color_dark="*primary_200", button_primary_border_color_hover_dark="*primary_100", - button_primary_text_color_dark="*primary_950", button_primary_text_color_hover_dark="*primary_950", - checkbox_background_color_selected="*primary_800", checkbox_border_color_selected="*primary_800", - checkbox_background_color_selected_dark="*primary_300", checkbox_border_color_selected_dark="*primary_300", - checkbox_label_background_fill_selected="*primary_50", checkbox_label_border_color_selected="*primary_800", - checkbox_label_text_color_selected="*primary_950", checkbox_label_background_fill_selected_dark="*primary_900", - checkbox_label_border_color_selected_dark="*primary_300", checkbox_label_text_color_selected_dark="*primary_50", - link_text_color="*primary_800", link_text_color_hover="*primary_950", link_text_color_visited="*primary_800", - link_text_color_dark="*primary_300", link_text_color_hover_dark="*primary_200", link_text_color_visited_dark="*primary_300", - color_accent="*primary_800", color_accent_soft="*primary_50", color_accent_soft_dark="*primary_900", loader_color="*primary_800", - slider_color="*primary_800", input_border_color_focus="*primary_700", - button_secondary_background_fill="*background_fill_primary", button_secondary_background_fill_hover="*primary_50", - button_secondary_border_color="*primary_300", button_secondary_border_color_hover="*primary_800", - button_secondary_text_color="*primary_900", button_secondary_text_color_hover="*primary_950", - button_secondary_background_fill_dark="*background_fill_primary", button_secondary_background_fill_hover_dark="*primary_900", - button_secondary_border_color_dark="*primary_500", button_secondary_border_color_hover_dark="*primary_300", - button_secondary_text_color_dark="*primary_100", button_secondary_text_color_hover_dark="*primary_50") - - -def blocks(title: str, **kw): - """gr.Blocks with the theme and CSS (Gradio 6 reads them at launch; passing them here keeps app.py's plain launch()).""" - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", message="The parameters have been moved", category=UserWarning) - return gr.Blocks(title=title, theme=theme(), css=CSS, **kw) - - -def _img(name: str, kind: str, alt: str, cls: str = "") -> str: - f = STATIC / name - mime = "image/svg+xml" if f.suffix == ".svg" else "image/png" - b = base64.b64encode(f.read_bytes()).decode() - return f"{alt}" - - -def _logo(kind: str) -> str: - return _img(f"squadds_{kind}.png", kind, "SQuADDS") - - -FAVICON_PNG = STATIC / "qcap_badge16_light_32px.png" # /favicon.ico (launch favicon_path): browsers without SVG icons - - -def favicon_head() -> str: - """The QCap badge as the page icon: an SVG that follows the browser's light / dark scheme (badge16 light and dark fills).""" - b = base64.b64encode((STATIC / "qcap_favicon.svg").read_bytes()).decode() - return f"" - - -def header(title: str, lede: str, meta: str | None = None, product: str | None = None) -> str: - """Logo + title, a short lede (HTML) and an optional small meta line. product = 'qcap': the QCap lockup beside the SQuADDS - logo, with the title on its own line below.""" - marks = _logo("light") + _logo("dark") - if product == "qcap": - marks += _img("qcap_compact_light.svg", "light", "QCap", " tl-product") + _img("qcap_compact_dark.svg", "dark", "QCap", " tl-product") - top = f"
{marks}

{html.escape(title)}

" - else: - top = f"
{marks}

{html.escape(title)}

" - return f"
{top}

{lede}

" + (f"

{meta}

" if meta else "") + "
" - - -CITE_MD = r"""If you use SQuADDS or QCap in your work, please cite: - -- S. Shanto *et al.*, "SQuADDS: A validated design database and simulation workflow for superconducting qubit design," *Quantum* **8**, 1465 (2024), [doi:10.22331/q-2024-09-09-1465](https://doi.org/10.22331/q-2024-09-09-1465). -- S. A. Shanto, S. Das and E. Levenson-Falk, "QCap: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout," [arXiv:2611.22057](https://arxiv.org/abs/2611.22057) (2026). - -```bibtex -@article{Shanto2024squaddsvalidated, - doi = {10.22331/q-2024-09-09-1465}, - url = {https://doi.org/10.22331/q-2024-09-09-1465}, - title = {{SQ}u{ADDS}: {A} validated design database and simulation workflow for superconducting qubit design}, - author = {Shanto, Sadman and Kuo, Andre and Miyamoto, Clark and Zhang, Haimeng and Maurya, Vivek and Vlachos, Evangelos and Hecht, Malida and Shum, Chung Wa and Levenson-Falk, Eli}, - journal = {{Quantum}}, - issn = {2521-327X}, - publisher = {{Verein zur F{\"{o}}rderung des Open Access Publizierens in den Quantenwissenschaften}}, - volume = {8}, - pages = {1465}, - month = sep, - year = {2024} -} - -@misc{Shanto2026planarcapacitance, - title = {{QCap}: a physics-corrected graph neural network for the capacitance matrix of any planar superconducting device layout}, - author = {Shanto, Sadman Ahmed and Das, Saikat and Levenson-Falk, Eli}, - year = {2026}, - eprint = {2611.22057}, - archivePrefix = {arXiv}, - primaryClass = {quant-ph}, - url = {https://arxiv.org/abs/2611.22057} -} -``` -""" - - -def footer() -> str: - """Credit and copyright, as on the SQuADDS paper page.""" - site = "Sadman Ahmed Shanto" - return (f"") - - -def examples(comp, paths, **kw): - """gr.Examples whose cached copies survive delete_cache. Gradio 6.29 copies a File example into the cache with - Blocks.temp_files but does not add it to keep_in_cache (the Dataset only stores the file name), so the delete_cache sweep - removed the copy PURGE_AGE_S after startup (at the first sweep when the copy was left by an earlier run) and every later - click on the example failed with FileNotFoundError.""" - e = gr.Examples([[str(p)] for p in paths], inputs=[comp], **kw) - for v in e.non_none_processed_examples.values(): - for d in v: - if isinstance(d, dict) and d.get("path"): - comp.keep_in_cache.add(d["path"]) - return e - - -def fig_files(fig, d: Path, stem: str) -> tuple[str, str]: - """A matplotlib figure as PNG (shown, downloadable) and SVG (download), closed afterwards.""" - import matplotlib.pyplot as plt - - png, svg = d / f"{stem}.png", d / f"{stem}.svg" - fig.savefig(png, dpi=130) - fig.savefig(svg) - plt.close(fig) - return str(png), str(svg) - - -def matrix_note(res) -> str: - flag = "indicative" in str(res.get("self_capacitance", "")) and list(res.get("names") or [])[:1] == ["G"] - return ("

The diagonal holds the self capacitances and the off-diagonal entries are minus the mutual capacitances, " - "in fF. The table shows 3 decimals, and the CSV and JSON keep full precision." + (f" {GROUND_FLAG}" if flag else "") + - "

" - "Swipe the matrix sideways for more columns.

") - - -def md(s) -> str: - """Markdown-safe text: a pair of '~' renders as strikethrough, so approximate values use '≈'.""" - return str(s or "").replace("~", "≈") - - -def pct(e) -> str: - """'1.05 % median (MAE 0.132 fF, RMSE 0.188 fF)': every % with its MAE / RMSE.""" - return f"{e['median_pct']:g} % median (MAE {e['mae_ff']:g} fF, RMSE {e['rmse_ff']:g} fF)" - - -def _inline(s: str) -> str: - return re.sub(r"\*\*(.+?)\*\*", r"\1", html.escape(s)) - - -def callout(kind: str, head: str, lines) -> str: - body = "".join(f"

{x}

" for x in lines if x) - return f"

{html.escape(head)}

{body}
" - - -def checks_of(res) -> dict | None: - """The result's physical checks; for arms that report none, the same checks on the matrix (entries that are None skipped).""" - c = res.get("checks") or {} - if "symmetric_max_abs" in c: - return c - C = np.array([[np.nan if x is None else float(x) for x in r] for r in res.get("matrix_fF") or []], float) - if C.ndim != 2 or len(C) < 2: - return None - off = C[~np.eye(len(C), dtype=bool)] - sig = C[1:, 1:] - return {"symmetric_max_abs": float(np.nanmax(np.abs(C - C.T))), "offdiag_all_negative": bool(np.all(off[np.isfinite(off)] < 0)), - "signal_block_min_eig": float(np.linalg.eigvalsh(sig).min()) if np.isfinite(sig).all() else None} - - -def _checks(c) -> str: - eig = c.get("signal_block_min_eig") - return (f"Symmetric (max |C − Cᵀ| {c['symmetric_max_abs']:.2g} fF), every off-diagonal negative" - + (f", signal block positive definite (smallest eigenvalue {eig:.4g} fF)." if eig is not None else - ". There are no self terms, so positive definiteness is not checked.")) - - -def _offstack(res) -> str: - sub = res.get("substrate_route") or {} - e, t = res.get("eps_r"), res.get("thickness_um") - if sub.get("route") == A.FAST_ROUTE: - return (f"Substrate eps_r {e:g}, {t:g} µm. This model does not solve the physics prior at your stack. It rescales its " - f"training-stack prediction by (1 + eps_r) / (1 + 11.45) = {sub['eps_rescale_factor']:.4f} and does not model thickness. " - "Off the training stack we measured a median error of 6.4 % (MAE 1.7 fF, RMSE 2.4 fF), so use QCap for other substrates.") - head = (f"Substrate eps_r {e:g}, {t:g} µm. The physics prior was solved at this stack, and the networks (trained on Si, eps_r " - "11.45, 350 µm) are unchanged.") - if not sub.get("tested", True): - return head + f" This is outside the tested range ({A.TESTED_RANGE}), so its error is unknown." - return head + f" This combination was tested. {A.CALIBRATED_SCORE}" - - -def status_html(res, expected: str | None = None) -> str: - """Callout above the matrix: red when a physical check fails (the physical_banner text), yellow off the training stack, green - otherwise with the one expected-error line for a new design.""" - bad = A.physical_banner(res) - c = checks_of(res) - if not bad and c and "checks" not in res: - C = np.nan_to_num(np.array([[np.nan if x is None else float(x) for x in r] for r in res["matrix_fF"]], float)) - w = A.physical_warning({**c, "signal_block_min_eig": c["signal_block_min_eig"] if c["signal_block_min_eig"] is not None else 1.0}, C) - bad = [f"> **Not a physical matrix.** {w}"] if w else [] - if bad: - return callout("bad", "Not a physical matrix: do not use it", [_inline(bad[0].lstrip("> ").replace("**Not a physical matrix.** ", ""))]) - chk = _checks(c) if c else None - if (res.get("substrate_route") or {}).get("route", "training stack") != "training stack": - return callout("warn", "Off the training stack" + (": physical checks passed" if chk else ""), [chk, html.escape(_offstack(res))]) - if chk: - return callout("ok", "Physical checks passed", [chk, html.escape(expected) if expected else None]) - return callout("", "Result", [html.escape(expected) if expected else None]) - - -def error_text(e: BaseException) -> str: - if isinstance(e, MemoryError): - return "Out of memory: crop the layout to the region of interest and try again." - if not isinstance(e, (LayoutError, ValueError, KeyError, FileNotFoundError)): - traceback.print_exception(e) - return f"Internal error ({type(e).__name__}): {e}. Please report it with the file if you can." - msg = str(e).strip() - if msg == "upload a GDS file first": - return "No layout yet: upload a GDS file (or pick an example) in step 1, then press Predict." - if msg.startswith("not a readable GDS"): - return f"This file could not be read as GDSII ({msg.rstrip('.')}). {REEXPORT}" - return msg[:1].upper() + msg[1:] - - -def error_html(e: BaseException, head: str = "Could not predict") -> str: - if getattr(e, "limit_html", None): # a limit of the demo (geomgnn.access.LimitReached): its own head and the local-use link - return callout("warn", e.head, [e.limit_html]) - return callout("bad", head, [html.escape(error_text(e))]) - - -def matrix_view(res): - """The matrix for the UI: conductor names as headers (blank top-left), 3 decimals shown, the ground self term flagged when the - result calls it indicative. The underlying values are the 4-decimal table the /predict endpoint always returned.""" - if not res: - return None - import pandas as pd - - names = list(res["names"]) - rows = [[a] + [np.nan if x is None else round(float(x), 4) for x in row] for a, row in zip(names, res["matrix_fF"])] - df = pd.DataFrame(rows, columns=["", *names]) - st = df.style.format("{:.3f}", subset=names, na_rep="").set_properties(subset=names, **{"text-align": "right"}) - st = st.set_properties(subset=[""], **{"font-weight": "600"}) - if "indicative" in str(res.get("self_capacitance", "")) and names and names[0] == "G" and np.isfinite(rows[0][1]): - st = st.format(lambda v: f"{v:.3f} †", subset=pd.IndexSlice[[0], [names[0]]]) - return st - - -def stale(res): - if res is None: - return gr.update(), gr.update(), gr.update() - return STALE, gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(elem_classes=["tl-stale"]) - - -def mark_stale(res_state, status, mat, report, events): - for ev in events: - ev(stale, res_state, [status, mat, report], api_visibility="private", show_progress="hidden") - - -def predict_ui(fn, expected, note: bool = False): - """Visible Predict: the /predict function plus the status callout and the result group (hidden until the first result); errors - become an inline callout instead of a toast and grey out an earlier result. note = also return the matrix note (last output).""" - def run(*a): - try: - mat, csv_f, json_f, rep, res = fn(*a) - except Exception as e: # noqa: BLE001 - return (gr.update(elem_classes=MAT + ["tl-stale"]), gr.update(), gr.update(), gr.update(elem_classes=["tl-stale"]), gr.update(), - error_html(e), gr.update()) + ((gr.update(),) if note else ()) - return (gr.update(value=mat, elem_classes=MAT), csv_f, json_f, gr.update(value=rep, elem_classes=[]), res, - status_html(res, expected(res)), gr.update(visible=True)) + ((matrix_note(res),) if note else ()) - run.__name__ = fn.__name__ + "_ui" - return run - - -def _rows(table) -> list: - if table is None: - return [] - rows = table.values.tolist() if hasattr(table, "values") else list(table) - return [list(r) for r in rows if len(r) >= 3 and str(r[0]).strip() not in ("", "nan", "None")] - - -def _key(r) -> str: - return f"{int(float(r[0]))}/{int(float(r[1]))}" - - -def inspect_ui(inspect_fn): - """Inspect on every file change (upload, example, clear): layer table, plot, inline message, layer picker, role.""" - def run(f): - none = gr.update(choices=[], value=None) - if f is None: - return [], None, "", none, gr.update(value=None) - try: - table, fig = inspect_fn(f) - except Exception as e: # noqa: BLE001 - return [], None, error_html(e, "Could not read this file"), none, gr.update(value=None) - keys = [_key(r) for r in table] - return table, fig, "", gr.update(choices=keys, value=keys[0] if keys else None), gr.update(value=table[0][2] if table else None) - return run - - -def layer_editor(): - with gr.Row(elem_classes="tl-roles"): - pick = gr.Dropdown([], label="layer", interactive=True, min_width=140) - role = gr.Dropdown(ROLES, value=None, label="role", interactive=True, min_width=200) - return pick, role - - -def wire_editor(layers, pick, role): - """Fixed role choices instead of free text: pick a layer (or click its row), choose its role. Returns the edit event.""" - def show(table, key): - r = next((r for r in _rows(table) if _key(r) == key), None) - return gr.update(value=r[2] if r else None) - - def choose(table, evt: gr.SelectData): - rows = _rows(table) - return gr.update(value=_key(rows[evt.index[0]])) if rows and evt.index[0] < len(rows) else gr.update() - - def edit(table, key, new): - return [r[:2] + [new] + r[3:] if _key(r) == key else r for r in _rows(table)] - - pick.change(show, [layers, pick], role, api_visibility="private", show_progress="hidden") - layers.select(choose, layers, pick, api_visibility="private", show_progress="hidden") - return role.input(edit, [layers, pick, role], layers, api_visibility="private", show_progress="hidden") diff --git a/geomgnn/usage.py b/geomgnn/usage.py deleted file mode 100644 index 7019b787b76971504a2cbb8ee9a6c5fb284c187f..0000000000000000000000000000000000000000 --- a/geomgnn/usage.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Aggregate daily usage counters of the SQuADDS Spaces (the planar-capacitance demo and the ML API). This file exists twice, byte -for byte: deploy/geomgnn/src/geomgnn/usage.py and deploy/squadds_ml_api/squadds_ml_api/usage.py (build.py and the tests check it). - -Only counts leave memory: one small JSON row per UTC day per service (and per process start), written to a private dataset through -huggingface_hub.CommitScheduler when the Space secret USAGE_STATS_TOKEN is set. Identities (Hugging Face usernames, client -addresses) reach this module only as keyed hashes (keyed()), used to count distinct users and dropped at the end of the day. No -usernames, hashes, addresses, file names, geometry or per-request rows are ever written.""" - -from __future__ import annotations - -import datetime as dt -import hashlib -import hmac -import json -import logging -import os -import secrets -import statistics -import tempfile -import threading -from pathlib import Path - -REPO = "SQuADDS/squadds-usage-stats" -MAX_LATENCIES = 50_000 -log = logging.getLogger(__name__) -_SALT = (os.environ.get("USAGE_HASH_SALT") or "").encode() or secrets.token_bytes(32) - - -def keyed(*parts) -> str: - """Keyed hash of an identity (secret salt from USAGE_HASH_SALT, else random per process); kept in memory only.""" - return hmac.new(_SALT, "\x1f".join(map(str, parts)).encode(), hashlib.sha256).hexdigest() - - -def today() -> str: - return dt.datetime.now(dt.timezone.utc).date().isoformat() - - -def _now() -> str: - return dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds") - - -class Usage: - """inc(group[, label]) counts, latency(s) collects response times, seen(group, key) counts distinct keyed hashes; row() is - what gets persisted. scheduler: a CommitScheduler-like object (folder_path, lock); built from USAGE_STATS_TOKEN when None.""" - - def __init__(self, service: str, repo_id: str = REPO, every_min: float = 10, scheduler=None): - self.service, self.started, self.lock = service, _now(), threading.Lock() - self._reset(today()) - self.scheduler = scheduler - if scheduler is None: - token = os.environ.get("USAGE_STATS_TOKEN") - if not token: - log.warning("usage stats: USAGE_STATS_TOKEN is not set, so the daily counts stay in memory (persistence off)") - return - try: - from huggingface_hub import CommitScheduler - - folder = Path(tempfile.mkdtemp(prefix="usage_stats_")) / service - self.scheduler = CommitScheduler(repo_id=repo_id, repo_type="dataset", folder_path=folder, path_in_repo=service, - every=every_min, private=True, token=token) - except Exception as e: # noqa: BLE001 - log.warning("usage stats: persistence off (%s: %s), the daily counts stay in memory", type(e).__name__, e) - - def _reset(self, day: str) -> None: - self.day, self.counts, self.latencies, self.distinct = day, {}, [], {} - - def _roll(self) -> None: - d = today() - if d != self.day: - self._write() - self._reset(d) - - def inc(self, group: str, label: str | None = None, n: int = 1) -> None: - with self.lock: - self._roll() - if label is None: - self.counts[group] = self.counts.get(group, 0) + n - else: - g = self.counts.setdefault(group, {}) - g[label] = g.get(label, 0) + n - self._write() - - def latency(self, seconds: float) -> None: - with self.lock: - self._roll() - if len(self.latencies) < MAX_LATENCIES: - self.latencies.append(float(seconds)) - self._write() - - def seen(self, group: str, key: str | None) -> None: - if not key: - return - with self.lock: - self._roll() - self.distinct.setdefault(group, set()).add(key) - - def row(self) -> dict: - s = sorted(self.latencies) - lat = {"n": len(s), "median": round(statistics.median(s), 3) if s else None, - "p90": round(s[min(len(s) - 1, int(round(0.9 * (len(s) - 1))))], 3) if s else None} - return {"service": self.service, "date": self.day, "process_started_utc": self.started, "updated_utc": _now(), - **{k: (dict(sorted(v.items())) if isinstance(v, dict) else v) for k, v in sorted(self.counts.items())}, - "latency_s": lat, **{k: len(v) for k, v in sorted(self.distinct.items())}} - - def _write(self) -> None: - if self.scheduler is None: - return - f = Path(self.scheduler.folder_path) / f"{self.day}_{self.started.replace(':', '').replace('+0000', 'Z')}.json" - with self.scheduler.lock: - f.write_text(json.dumps(self.row(), indent=1) + "\n") diff --git a/geomgnn/winpool.py b/geomgnn/winpool.py deleted file mode 100644 index 4aaee0bea107f1921297c7b0f11e6fd198ad5e00..0000000000000000000000000000000000000000 --- a/geomgnn/winpool.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Window solves of the prior on spawned workers (agents/embedspeed; macOS). The vendor's window pool forks, which macOS -cannot do with Accelerate, so on macOS fastprior_pkg runs the windows serially (a few cores busy). Here the vendor's own -micro_mom runs with `workers` > 1 and its ProcessPoolExecutor / get_context("fork") are swapped, for that call only, for a -spawn pool whose workers install the same prior stack (geomgnn.api.set_prior_stack with the recorded registry prior), copy the -running call's layout (fastprior._LITE, the k-d tree rebuilt) and the module settings, and run fastprior_pkg's window job. -Each window is the same statements; BLAS threads per window differ (one per worker), so the result is numerically exact, -not bitwise (gate: <= 1e-9 relative vs the serial windows). - -TLSQ_WINDOW_PROCS: auto (default: macOS, CPUs from TLSQ_NUM_THREADS / os.cpu_count()), (force n workers), 0 (off). -""" -from __future__ import annotations - -import os -import sys -from concurrent.futures import ProcessPoolExecutor -from multiprocessing import get_context - -_ON: dict = {"n": 0} - - -def workers() -> int: - v = os.environ.get("TLSQ_WINDOW_PROCS", "auto") - if v == "0": - return 0 - if v != "auto": - return int(v) - return (os.cpu_count() or 1) if sys.platform == "darwin" else 0 - - -def _init(paths, impl, pr, state): - os.environ["TLSQ_WINDOW_PROCS"] = "0" - os.environ.update({k: "1" for k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS", - "TLSQ_NUM_THREADS", "VECLIB_MAXIMUM_THREADS")}) - for p in reversed(paths): - if p not in sys.path: - sys.path.insert(0, p) - import shapely - import torch - torch.set_num_threads(1) - from geomgnn import api as A - from geomgnn._tlsq.embed import fastprior as F - from geomgnn._tlsq.embed import proxy - A.set_prior_impl(impl) - A.set_prior_stack(pr, 1) - A._thread_limits(1) - proxy.NUM_THREADS = 1 - proxy.SUBSTRATE.clear() - proxy.SUBSTRATE.update(state["substrate"]) - for k in ("ALPHA_GAP_SHARE", "LITE_WINDOW_BUDGET", "LITE_REFINE", "LITE_GROWTH", "FORMULA_STEP_UM", "ROW_SUM_EPS"): - setattr(F, k, state["F"][k]) - F.LITE_WINDOW_PPG[:] = state["F"]["LITE_WINDOW_PPG"] - F.LITE_MAX_CORE[:] = state["F"]["LITE_MAX_CORE"] - lite = dict(state["lite"]) - lite["tree"] = shapely.STRtree(lite["conds"]) - F._LITE.clear() - F._LITE.update(lite) - - -class _SpawnPool(ProcessPoolExecutor): - def __init__(self, max_workers, mp_context=None): - from . import api as A - from ._tlsq.embed import fastprior as F - from ._tlsq.embed import proxy - here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - state = dict(substrate=dict(proxy.SUBSTRATE), lite={k: v for k, v in F._LITE.items() if k != "tree"}, - F={k: getattr(F, k) for k in ("ALPHA_GAP_SHARE", "LITE_WINDOW_BUDGET", "LITE_REFINE", "LITE_GROWTH", - "FORMULA_STEP_UM", "ROW_SUM_EPS")} - | {"LITE_WINDOW_PPG": list(F.LITE_WINDOW_PPG), "LITE_MAX_CORE": list(F.LITE_MAX_CORE)}) - main = sys.modules["__main__"] - self._saved = main.__dict__.pop("__file__", None) # spawn would otherwise re-run the calling script - super().__init__(max_workers, mp_context=get_context("spawn"), initializer=_init, - initargs=([here], A._STATE["prior_impl"], A._STATE["pr"], state)) - - def shutdown(self, *a, **k): - try: - super().shutdown(*a, **k) - finally: - if self._saved is not None: - sys.modules["__main__"].__file__ = self._saved - self._saved = None - - -class _Serial: - """In-process stand-in for the other pools of the call (formula_prior's rows): what macOS runs today.""" - - def __init__(self, *a, **k): - pass - - def __enter__(self): - return self - - def __exit__(self, *e): - return False - - def map(self, fn, *its, **k): - return map(fn, *its) - - -def _pool(max_workers, mp_context=None): - """Spawned workers for the windows of a call with >= TLSQ_WINDOW_MIN_CORES windows (default 5; measured on the Mac: the - 1q lattice's 2 windows 3.4 -> 5.9 s with the spawn, the 9q lattice's 9 windows 23.8 -> 18.1 s); in-process otherwise.""" - from ._tlsq.embed import fastprior as F - big = len(F._LITE.get("cores", ())) >= int(os.environ.get("TLSQ_WINDOW_MIN_CORES", "5")) - return _SpawnPool(max_workers) if F._LITE and big else _Serial() - - -def install() -> bool: - """Wrap the installed stack's micro_mom so that its windows run on spawned workers (idempotent; macOS by default).""" - from . import api as A - from . import fastprior_pkg as fp - from ._tlsq.embed import fastprior as F - n = workers() - if n < 2 or not A._STATE.get("pr") or not A._STATE.get("mode") or "micro_mom" not in fp._ORIG: - return False - if getattr(F.micro_mom, "_winpool", False): - _ON["n"] = n - return True - vendor = fp._ORIG["micro_mom"] - sig = fp._ORIG["micro_mom_sig"] - - def micro_mom(*args, **kw): - ba = sig.bind(*args, **kw) - if _ON["n"] < 2: - return fp._micro_mom(*args, **kw) - ba.arguments["workers"] = _ON["n"] - fp._PARENT[0] = os.getpid() - old = F.ProcessPoolExecutor, F.get_context - F.ProcessPoolExecutor, F.get_context = _pool, (lambda method=None: None) - try: - return vendor(*ba.args, **ba.kwargs) - finally: - F.ProcessPoolExecutor, F.get_context = old - - micro_mom._winpool = True - F.micro_mom = micro_mom - _ON["n"] = n - return True diff --git a/geomgnn/x1_core.py b/geomgnn/x1_core.py deleted file mode 100644 index 812f6c236d28772038835056f0773ec4d236c2b6..0000000000000000000000000000000000000000 --- a/geomgnn/x1_core.py +++ /dev/null @@ -1,116 +0,0 @@ -"""X1 shared model code (agents/v4test/PROTOCOL.md): row -> arrays, multifid forward, surrogate priors. No solver, no labels.""" -import numpy as np - -from ._tlsq.uge.blocks import edge_matrix - -PPG = (0.375, 0.75, 1.5, 3.0) - - -def schema_of(ck): - s = ck.get('schema', ck) - return s['nodekeys'], s['edgekeys'], s.get('globkeys', ['log_chip_area', 'log_pocket_area', 'log_substrate_t', 'eps_eff']) - - -def raw_arrays(row, nk, ek, gk): - """Unnormalised X (n, nk), E (P, ek), G (gk) exactly as geomfast infer.Predictor.from_features builds them.""" - n = len(row['names']) - pairs = np.array([(i, j) for i in range(n) for j in range(i + 1, n)]) - 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'], ek, n) - G = np.array([row['global'][k] for k in gk], np.float32) - return X, E, G, pairs - - -def norm(z, scale): - med, iqr = np.array(scale['median']), np.array(scale['iqr']) - return np.clip((np.where(np.isfinite(z), z, med) - med) / iqr, -10, 10).astype(np.float32) - - -class Multifid: - """multifid residual arm (scripts/multifid/train_mf.py Net), seeds averaged as full matrices (analyze.py).""" - - 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 not 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): - """levels: {ppg: positive mutual matrix (n, n)} in row order.""" - nk, ek, gk = schema_of(self.models[0][0]) - X, E, G, pairs = raw_arrays(row, nk, ek, gk) - i, j = pairs.T - sig = np.array([nm != 'G' for nm in row['names']]) - return self.predict_arrays(X, E, G, pairs, sig, {p: np.asarray(levels[p], float)[i, j] for p in self.levels}) - - def predict_arrays(self, X0, E0, G0, pairs, sig, lev): - """raw (unnormalised) X (n, f), E (P, f), G (g), pairs (P, 2), sig (n,), lev {ppg: positive mutual (P,)}.""" - import torch - out = [] - for c, m in self.models: - assert schema_of(c) == schema_of(self.models[0][0]) - L = [np.log(np.asarray(lev[p], float)) for p in self.levels] - assert all(np.isfinite(v).all() for v in L) - X, E, G = X0, E0, G0 - lf, lc = L[-1], L[-2] - anchor, slope = 2 * lf - lc, lf - lc - E = np.concatenate([E] + [(L[k + 1] - L[k])[:, None].astype(np.float32) for k in range(len(L) - 1)], -1) - X, E, G = norm(X, c['scales']['X'])[None], norm(E, c['scales']['E'])[None], norm(G[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(X), T(E), T(G), torch.ones((1, n), dtype=torch.bool), torch.ones((1, len(pairs)), dtype=torch.bool), - torch.from_numpy(pairs), T(anchor[None]), T(slope[None]), T(bbase), False)[0] - out.append(C[0].numpy().astype(np.float64)) - r = np.mean(out, 0) - assert np.isfinite(r).all() - return r - - -class Surrogate: - """learnedprior surrogate (lp_surrogate.predict_bucket on lp_label.pack(row)) -> priors at ppg 1.5, 3.""" - - def __init__(self, path): - from . import lp_surrogate as S - self.S = S - self.model, self.prep, _ = S.load_model(path, 'cpu') - sch = S.SCHEMA - self.nk, self.ek, self.gk = sch['nodekeys'], sch['edgekeys'], sch['globkeys'] - - def priors(self, row): - X, E, G, pairs = raw_arrays(row, self.nk, self.ek, self.gk) - n = len(row['names']) - lp = self.S.predict_bucket(self.model, self.prep, dict(n=n, X=X[None], E=E[None], G=G[None]), 'cpu')[0] - iu = np.triu_indices(n, 1) - pri = {} - for k, p in enumerate((1.5, 3.0)): - M = np.zeros((n, n)) - M[iu] = np.exp(lp[:, k]) - pri[p] = M + M.T - return pri - - -def c0(levels, lo=1.5, hi=3.0): - """Richardson extrapolation in log of positive mutual / self matrices: exp(2 log c(hi) - log c(lo)); Maxwell form.""" - a, b = np.abs(np.asarray(levels[lo], float)), np.abs(np.asarray(levels[hi], float)) - m = np.exp(2 * np.log(np.maximum(b, 1e-300)) - np.log(np.maximum(a, 1e-300))) - n = len(m) - off = ~np.eye(n, dtype=bool) - C = np.where(off, -m, m) - return C - - -def to_maxwell(P): - """stored prior P = -C (positive mutuals) -> Maxwell C.""" - return -np.asarray(P, float) diff --git a/index.html b/index.html new file mode 100644 index 0000000000000000000000000000000000000000..aa42c9fbfa18ab1cfcb67bd3081112682a344429 --- /dev/null +++ b/index.html @@ -0,0 +1,42 @@ + + + + + + +QCap demo + + + + + + +
+ +

QCap demo

+

The demo has moved to SQuADDS. It opens in this tab.

+ Open the QCap demo +
+ + diff --git a/models/accurate/acc_v2m_sf_s0.pt b/models/accurate/acc_v2m_sf_s0.pt deleted file mode 100644 index 887768ba777276fd5d75d3fb63e5851348a85279..0000000000000000000000000000000000000000 --- a/models/accurate/acc_v2m_sf_s0.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1c7a9e3be100f083ee9418695525ae54c8469f8a82e8da4d8c728da5e0cd2ca3 -size 381223 diff --git a/models/accurate/acc_v2m_sf_s1.pt b/models/accurate/acc_v2m_sf_s1.pt deleted file mode 100644 index b44b491d0291bd18bb79f4693990f2a4dc7edf15..0000000000000000000000000000000000000000 --- a/models/accurate/acc_v2m_sf_s1.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:857b75095a29d8fa0b12d27a161750cdc89611c2227a1545e1ac447518d0c414 -size 381223 diff --git a/models/accurate/acc_v2m_sf_s2.pt b/models/accurate/acc_v2m_sf_s2.pt deleted file mode 100644 index 2619fb8348adaa02fb53414095ba57740882d888..0000000000000000000000000000000000000000 --- a/models/accurate/acc_v2m_sf_s2.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6e86e6d1e42df20fc7255974b7f739d59317148d2b16be93f012425819f309ac -size 381223 diff --git a/models/accurate/info.json b/models/accurate/info.json deleted file mode 100644 index 1e9c45f96e7e5bcbf59aac415f36e0c1f82c62b8..0000000000000000000000000000000000000000 --- a/models/accurate/info.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "accurate", - "model": "QCap", - "kind": "gnn", - "checkpoints": [ - "acc_v2m_sf_s0.pt", - "acc_v2m_sf_s1.pt", - "acc_v2m_sf_s2.pt" - ], - "checkpoints_sha256": [ - "cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5", - "2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57", - "d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed" - ], - "checkpoints_bundle_sha256": [ - "1c7a9e3be100f083ee9418695525ae54c8469f8a82e8da4d8c728da5e0cd2ca3", - "857b75095a29d8fa0b12d27a161750cdc89611c2227a1545e1ac447518d0c414", - "6e86e6d1e42df20fc7255974b7f739d59317148d2b16be93f012425819f309ac" - ], - "checkpoints_source": [ - "data_local/flagship_v4/hpc/runs/acc_v2m_sf_s0/model.pt", - "data_local/flagship_v4/hpc/runs/acc_v2m_sf_s1/model.pt", - "data_local/flagship_v4/hpc/runs/acc_v2m_sf_s2/model.pt" - ], - "surrogate": [], - "surrogate_sha256": [], - "surrogate_bundle_sha256": [], - "surrogate_source": [] -} \ No newline at end of file diff --git a/models/balanced/bal_v2m_sf_s0.pt b/models/balanced/bal_v2m_sf_s0.pt deleted file mode 100644 index efaec511cedef9e59e0ca96daace8644d0bad737..0000000000000000000000000000000000000000 --- a/models/balanced/bal_v2m_sf_s0.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7a0353f2e8875c73c4188eccb641d15e8279a65870535a78cabf94f2e410f3ab -size 381223 diff --git a/models/balanced/bal_v2m_sf_s1.pt b/models/balanced/bal_v2m_sf_s1.pt deleted file mode 100644 index 85b1f9d92738977c28c9102ba979d084fd66168b..0000000000000000000000000000000000000000 --- a/models/balanced/bal_v2m_sf_s1.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:79654f3fe6a647e0e678eb027ae5f11590ba2ec588deb127d3d1e0c468283b4e -size 381223 diff --git a/models/balanced/bal_v2m_sf_s2.pt b/models/balanced/bal_v2m_sf_s2.pt deleted file mode 100644 index 447ea0057753b4969572ddecf2a91f9ee7b5245a..0000000000000000000000000000000000000000 --- a/models/balanced/bal_v2m_sf_s2.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f4fa6514b7f2740c376f664105c6fe723aca1c7c76a5eadec625e9685d721a30 -size 381223 diff --git a/models/balanced/info.json b/models/balanced/info.json deleted file mode 100644 index c58028e33f8f6cecaa268f74a36e64e1824cd283..0000000000000000000000000000000000000000 --- a/models/balanced/info.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "balanced", - "model": "QCap-Lite", - "kind": "gnn", - "checkpoints": [ - "bal_v2m_sf_s0.pt", - "bal_v2m_sf_s1.pt", - "bal_v2m_sf_s2.pt" - ], - "checkpoints_sha256": [ - "aa742ab93b1e3ffcd86a753bda5cc4a68812acbe8140a6b0e311c11d1f36b4b2", - "486466473eba61c090f4e3fa7988bf880fc183570c5d02bd78f4c1356691f926", - "1b55ded04fd624585eeeccf2ab6e4a8e9354a9b96694131e1737dde43ad3ff58" - ], - "checkpoints_bundle_sha256": [ - "7a0353f2e8875c73c4188eccb641d15e8279a65870535a78cabf94f2e410f3ab", - "79654f3fe6a647e0e678eb027ae5f11590ba2ec588deb127d3d1e0c468283b4e", - "f4fa6514b7f2740c376f664105c6fe723aca1c7c76a5eadec625e9685d721a30" - ], - "checkpoints_source": [ - "data_local/flagship_v4/hpc/runs/bal_v2m_sf_s0/model.pt", - "data_local/flagship_v4/hpc/runs/bal_v2m_sf_s1/model.pt", - "data_local/flagship_v4/hpc/runs/bal_v2m_sf_s2/model.pt" - ], - "surrogate": [], - "surrogate_sha256": [], - "surrogate_bundle_sha256": [], - "surrogate_source": [] -} \ No newline at end of file diff --git a/models/fast/acc_v1_s0.pt b/models/fast/acc_v1_s0.pt deleted file mode 100644 index cf7168e9c9d9018e80e600641b2487a6f68d8d3a..0000000000000000000000000000000000000000 --- a/models/fast/acc_v1_s0.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e2909bd0bf06d3cd07be27160050e323a69700de732ef54c9afa00c38b7521e0 -size 380559 diff --git a/models/fast/acc_v1_s1.pt b/models/fast/acc_v1_s1.pt deleted file mode 100644 index ebef8cb80024d0ee5a9d1085599f7d8816a1b5be..0000000000000000000000000000000000000000 --- a/models/fast/acc_v1_s1.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:085a7819d86f66962a840e1279017f23487d8d3b12fa9773a1fd0f884621b241 -size 380559 diff --git a/models/fast/acc_v1_s2.pt b/models/fast/acc_v1_s2.pt deleted file mode 100644 index e9a8d4fc8226adfd46ea8070d692583170af702c..0000000000000000000000000000000000000000 --- a/models/fast/acc_v1_s2.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5b607329a83a938911d4ebbd8d801b9c58306ce3c96b34cd82ed502a8fb588fc -size 380559 diff --git a/models/fast/info.json b/models/fast/info.json deleted file mode 100644 index bfddb88da873855fc19c1551bda2054c972a6c9a..0000000000000000000000000000000000000000 --- a/models/fast/info.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "fast", - "model": "QCap-Fast", - "kind": "gnn", - "checkpoints": [ - "acc_v1_s0.pt", - "acc_v1_s1.pt", - "acc_v1_s2.pt" - ], - "checkpoints_sha256": [ - "9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba", - "f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe", - "8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4" - ], - "checkpoints_bundle_sha256": [ - "e2909bd0bf06d3cd07be27160050e323a69700de732ef54c9afa00c38b7521e0", - "085a7819d86f66962a840e1279017f23487d8d3b12fa9773a1fd0f884621b241", - "5b607329a83a938911d4ebbd8d801b9c58306ce3c96b34cd82ed502a8fb588fc" - ], - "checkpoints_source": [ - "data_local/flagship_v4/hpc/runs/acc_v1_s0/model.pt", - "data_local/flagship_v4/hpc/runs/acc_v1_s1/model.pt", - "data_local/flagship_v4/hpc/runs/acc_v1_s2/model.pt" - ], - "surrogate": [ - "sall_all_s0.pt" - ], - "surrogate_sha256": [ - "132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac" - ], - "surrogate_bundle_sha256": [ - "132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac" - ], - "surrogate_source": [ - "data_local/flagship_v4/hpc/sur/sall_all_s0/model.pt" - ] -} \ No newline at end of file diff --git a/models/fast/sall_all_s0.pt b/models/fast/sall_all_s0.pt deleted file mode 100644 index fa4fa120dd9577ccebca5b29e551e4ca7a5e4e88..0000000000000000000000000000000000000000 --- a/models/fast/sall_all_s0.pt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac -size 4172218 diff --git a/registry.yaml b/registry.yaml deleted file mode 100644 index 48af3e0310897110bfc5a666bd79d0dfdd9e7999..0000000000000000000000000000000000000000 --- a/registry.yaml +++ /dev/null @@ -1,1590 +0,0 @@ -# Single source of truth for every released name, link and paper number of the tl-squadds capacitance models. -# Everything else (tlsq_infer model loader, Space apps, model cards, paper_ml/deploy_links.tex, the sync workflow) -# reads this file. Renaming a repo or Space = edit one line here, then run `python deploy/sync.py` (dry run) / -# `python deploy/sync.py --push`. -# -# Paths are relative to the repository root. Metrics: median |relative error| (%) / MAE (fF) / RMSE (fF) over all -# mutual entries, as in the paper (paper_ml/floats/tab_candidates.tex, paper_ml/tables/cost_rows.tex). - -version: 2 # 2: corrected prior with substrate far field (2026-10-20, agents/farfield/ADOPTION.md); 1: before -package_version: "0.1.0" - -hub: - org: SQuADDS - private: true # create every repo private; flip deliberately when the paper is public - space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM - flagship_space: shanto268/PlanarCapacitanceModel # org Gradio Spaces need a paid HF plan; move to SQuADDS/ by editing this line - # ("flagship" here = the default Space; the tiers are "coarse" / "fine"; since - # 2026-10-10 the fine tier runs on the "flagship prior", PRIOR_SCHEME.md Part II) - flagship_title: Planar Capacitance Model - paper_models_space: shanto268/2026PaperModels - paper_models_title: 2026 Paper Models - collection: "Zero-shot planar capacitance models (2026)" - collection_slug: null # filled in by sync.py --push after the collection is created - code_url: null # public source repository of the training code, when released - -paper: - short: "Zero-shot capacitance of planar superconducting layouts" - draft_dir: paper_ml - links_tex: paper_ml/deploy_links.tex - arxiv: null # set when posted; cards and Spaces pick it up - -training_stack: - substrate: Si (cryogenic) - eps_r: 11.45 - thickness_um: 350 - metal: zero-thickness sheet (Q3D thin conductor) - layers: {ground: [1, 0], conductor: [1, 10]} - training_designs: 40153 - training_families: [interdigital (CapNInterdigital), paddle, concentric, star, multi-pad star] - -eval_sets: - never_seen: - name: never-seen components (Xmon, TransmonPocket, shielded concentric) - designs: 926 - entries: all mutual entries - ood60: - name: OOD-60 (procedural near / intermediate / alien shapes) - designs: 60 - -blend: - weights_gnn_side: {signal-signal: 0.6, signal-ground: 0.7, pad: 0.8} # log-space; rest = charge-corrected prior - note: "pad = any entry involving the third or later signal body (file order), as in the paper" - kinds: invariant # deployment: order-invariant kinds (deploy/MODEL_SELECTION.md amendment 3); "published" = paper file-order kinds - weights_gnn_side_invariant: {conductor-conductor: 0.6, conductor-ground: 0.9} # LOFO on the 5 training families (scripts/blend_lofo.py --kinds invariant) - note_invariant: "conductor-conductor = any pair of floating conductors, conductor-ground = pairs with ground; independent of polygon order" - -self_capacitance: - row_sum_eps: 0.0143 # C_ii = sum_j |C_ij| / (1 - eps) (IMPROVE_IDEAS.md, training median) - -substrates: # dropdown of the Spaces; the 11 materials of the stack DoE + the training substrate - Si (cryogenic, training): 11.45 - sapphire (c-plane, isotropic eq.): 10.34 - GaAs: 12.9 - fused silica: 3.8 - Si (room temperature): 11.7 - SiC: 9.7 - MgO: 9.8 - InP: 12.4 - Ge: 16.0 - quartz (crystalline): 4.5 - diamond: 5.7 - LaAlO3: 24.0 - -artifacts: - charge_gbm: deploy/artifacts/charge_gbm.joblib # built once by `python -m tlsq_infer.charge fit` - charge_gbm_train_cells: data_local/charge_p1/train_cells.parquet - stack_error: deploy/artifacts/stack_error.json # built by `python deploy/stack_error.py fit` - # per-entry error model (ERROR_MODEL.md): NOT ENABLED in the release (user decision 2026-10-08: no intervals until the - # pre-declared v2 is evaluated on the fresh atlas + >7-conductor labels). To enable, set e.g. - # error_model: {all-data-v3s: error_model_fast.joblib, all-data-v3-rich: error_model_accurate.joblib, - # pair-local-fast: error_model_pair-local-fast.joblib} - # (files in deploy/artifacts/, built by `python scripts/error_model.py fit`; tests: deploy/tests/test_error_model.py) - error_model: {} - -defaults: - flagship_model: all-data-lite1500 # fast tier = flagship-fast, DEFAULT since 2026-10-10 (user decision; deploy/MODEL_SELECTION.md Results 4) - coarse_model: all-data-v3s # coarse tier (default until 2026-10-10; deploy/MODEL_SELECTION.md, amendment 1 rule) - flagship_accurate_model: all-data-flagship # fine tier (key name kept). 2026-10-10, user-approved: all-data-v3-rich -> all-data-flagship - # (same weights, flagship prior; PRIOR_SCHEME.md section 8.1, deploy/MODEL_SELECTION.md Results 3) - large_layout_model: all-data-flagship # (PRIOR_SCHEME.md Part II): layouts on which the capped coarse prior would - # resolve < 0.75 panels across the smallest gap (outside the training regime; the grids of - # GRID_SCALING.md returned zero entries) are predicted with this flagship-prior model instead - # (predict(large_layouts="route"), reported in model_used / warnings). In-regime layouts unchanged. - paper_space_model: pair-local-fast # this work's headline (paper abstract) - tiers: # shown in the flagship UI; keys = tier names (alias accurate -> fine accepted by predict); - fast: {latency_s: 1, median_pct: 2.67, mae_ff: 0.768, rmse_ff: 1.874, set: "212 held-out designs (OOD-60, random TransmonPocket-3, 6 new Qiskit Metal classes)", - note: "flagship-fast (default): cheap micro-MoM prior (<= 1,500 merged panels; core-graded windows and screened-dipole far pairs beyond 8 conductors) and a network retrained on it. Less accurate than the coarse and fine tiers (large-N 40: 4.96 % vs 2.93 % / 1.63 %), several times faster, and the only tier that runs multi-qubit chips. On this free CPU Space (2026-10-10): 0.2-0.3 s for the Xmon and TransmonPocket examples, 8.5 s for a 200-finger comb, 14 s for a 66-qubit-grid layout, about 4 min for a 780-conductor chip (18 Mac cores: 15 s). PRIOR_SCHEME.md Part III section 15.3."} - # held-out = OOD-60 + pocket3 random-36 + Qiskit Metal new 116, pooled mutual entries - coarse: {latency_s: 4, median_pct: 1.75, mae_ff: 0.534, rmse_ff: 1.173, set: "212 held-out designs (OOD-60, random TransmonPocket-3, 6 new Qiskit Metal classes)", - note: "On this free CPU Space: 1-5 s for single components (measured on the examples, 2026-10-10). Layouts whose coarse mesh would fall below the training resolution (e.g. the TransmonPocket example, long combs) are predicted with the fine tier instead (reported under model used)."} - fine: {latency_s: 10, median_pct: 1.13, mae_ff: 0.374, rmse_ff: 0.836, set: "212 held-out designs (OOD-60, random TransmonPocket-3, 6 new Qiskit Metal classes)", - note: "Flagship prior: strip-merged Richardson (6 and 3 panels across the smallest gap on every layout), H-matrix solve for large systems. On this free CPU Space (2026-10-10): 1-2 s for the Xmon and interdigital examples, 20 s for the TransmonPocket, 80 s for the shielded concentric example; large layouts several minutes (200-finger comb 220 s). One fine-tier solve runs at a time; other requests are not blocked."} - -models: - # ---------------------------------------------------------------- learned, released - pair-local: - title: "Pair-local network + earlier standard MoM prior (R=0, published v2 mesh)" - repo_id: SQuADDS/2026PaperModels-pair-local - kind: gnn - prior: standard - rounds: 0 - status: available - checkpoints: [data_local/mega/ckpt/ALL_mom_r0_s0.pt, data_local/mega/ckpt/ALL_mom_r0_s1.pt, data_local/mega/ckpt/ALL_mom_r0_s2.pt] - parameters: 209410 - summary: "Earlier prior (published v2 mesh). Former flagship; superseded by the coarse-prior models of this work." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:splits, fig:zs-arch, fig:stack, tab:stack] - never_seen: {median_pct: 1.73, mae_ff: 0.83, rmse_ff: 1.62} - ood60: {median_pct: 1.81, mae_ff: 0.78, rmse_ff: 1.63} - in_family_id: {median_pct: 0.91, mae_ff: 0.063, rmse_ff: 0.181, note: grouped in-distribution split, signal-signal} - cost_s_per_design: {never_seen: 8.75, ood60: 0.60, note: one CPU core, all stages from the GDS} - - message-passing: - title: "Message-passing network + earlier standard MoM prior (R=3, published v2 mesh)" - repo_id: SQuADDS/2026PaperModels-message-passing - kind: gnn - prior: standard - rounds: 3 - status: available - checkpoints: [data_local/mega/ckpt/ALL_mom_s0.pt, data_local/mega/ckpt/ALL_mom_s1.pt, data_local/mega/ckpt/ALL_mom_s2.pt] - parameters: 752386 - summary: "Earlier prior (published v2 mesh). Transfers slightly worse than pair-local." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:sota, fig:zs-arch, fig:infamily] - never_seen: {median_pct: 2.08, mae_ff: 0.97, rmse_ff: 1.88} - ood60: {median_pct: 2.45, mae_ff: 0.98, rmse_ff: 1.94} - in_family_full: {median_pct: "0.21-1.05", mae_ff: "0.017-0.40", rmse_ff: "0.022-0.84", note: C_NS, range over the 5 families} - cost_s_per_design: {never_seen: 8.77, ood60: 0.61} - - charge-corrected-prior: - title: "Charge-corrected earlier MoM prior (cell GBM, published v2 mesh)" - repo_id: SQuADDS/2026PaperModels-charge-corrected-prior - kind: charge_prior - prior: standard - status: available - checkpoints: [deploy/artifacts/charge_gbm.joblib] - summary: "Earlier prior (published v2 mesh): MoM cell charges corrected by a gradient-boosted model of local geometry; no capacitance labels." - paper: - appears_in: [tab:candidates, tab:costacc, fig:zs-cell, tab:splits] - never_seen: {median_pct: 2.18, mae_ff: 0.95, rmse_ff: 1.62} - ood60: {median_pct: 4.05, mae_ff: 1.30, rmse_ff: 2.33} - cost_s_per_design: {never_seen: 17.5, ood60: 1.06, note: "paper timing re-solves the MoM; tlsq_infer reuses the prior's solve"} - - blend-pair-local: - title: "Blended model (earlier prior): pair-local network x charge-corrected earlier prior" - repo_id: SQuADDS/2026PaperModels-blend-pair-local - kind: blend - components: [pair-local, charge-corrected-prior] - status: available - summary: "Earlier prior (published v2 mesh); was the headline of the first draft. Deployed with order-invariant blend weights." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc, fig:blend, fig:stack, tab:stack, fig:invdesign, tab:invdes] - never_seen: {median_pct: 1.64, mae_ff: 0.71, rmse_ff: 1.36} - ood60: {median_pct: 2.36, mae_ff: 0.87, rmse_ff: 1.75} - cost_s_per_design: {never_seen: 17.5, ood60: 1.06} - - blend-message-passing: - title: "Blended model (earlier prior): message-passing network x charge-corrected earlier prior" - repo_id: SQuADDS/2026PaperModels-blend-message-passing - kind: blend - components: [message-passing, charge-corrected-prior] - status: available - summary: "Earlier prior (published v2 mesh); blend with the R=3 network." - paper: - appears_in: [tab:costacc, fig:costacc, fig:blend] - never_seen: {median_pct: 1.84, mae_ff: 0.82, rmse_ff: 1.56} - ood60: {median_pct: 2.37, mae_ff: 0.90, rmse_ff: 1.87} - cost_s_per_design: {never_seen: 17.5, ood60: 1.07} - - geometry-only: - title: "Geometry-only network (no physics prior; earlier ablation)" - repo_id: SQuADDS/2026PaperModels-geometry-only - kind: gnn - prior: none - rounds: 3 - status: available - checkpoints: [data_local/mega/ckpt/ALL_none_s0.pt] - summary: "Ablation. Accurate in family, fails on unseen geometry: do NOT use for new layouts. Released for reproducibility (seed 0 of 3)." - warning: "Not for unseen geometry (19 % median on never-seen components, single entries off by >10x)." - paper: - appears_in: [tab:candidates, tab:splits, tab:sota] - never_seen: {median_pct: 19.4, mae_ff: 6.1, rmse_ff: 9.8} - ood60: {median_pct: "4.7-15.0", mae_ff: "1.7-3.4", rmse_ff: "2.2-4.6", note: range of per-class medians} - in_family_full: {median_pct: "0.45-1.54", mae_ff: "0.011-0.90", rmse_ff: "0.015-1.32"} - - # ---------------------------------------------------------------- training-free - mom-prior: - title: "Earlier standard MoM prior alone (training-free, published v2 mesh)" - repo_id: null - kind: prior - prior: standard - status: available - summary: "Untrained thin-film method of moments (default 8,000-cell cap). Physics baseline." - paper: - appears_in: [tab:candidates, tab:costacc, tab:prior, fig:prior-parity] - never_seen: {median_pct: 6.55, mae_ff: 3.03, rmse_ff: 4.62} - ood60: {median_pct: 8.09, mae_ff: 2.26, rmse_ff: 3.56} - - fine-mom-prior: - title: "Earlier 16k MoM prior alone (training-free, published chip-anchored v2 mesh, 16k cells)" - repo_id: null - kind: prior - prior: fine - status: available - summary: "Untrained MoM, gap/6 with a default 16,000-cell cap. Physics baseline at ~3-5x the cost." - paper: - appears_in: [tab:costacc] - never_seen: {median_pct: 4.99, mae_ff: 2.38, rmse_ff: 3.60} - - # ---------------------------------------------------------------- pending (trained on HPC; copy checkpoints, flip status) - pair-local-fine: - title: "Pair-local network + earlier 16k MoM prior (R=0, published chip-anchored v2 mesh, 16k cells)" - repo_id: SQuADDS/2026PaperModels-pair-local-fine - kind: gnn - prior: fine - rounds: 0 - status: available - checkpoints: [data_local/mega/ckpt_fine/ALL_mom_r0_s0.pt, data_local/mega/ckpt_fine/ALL_mom_r0_s1.pt, data_local/mega/ckpt_fine/ALL_mom_r0_s2.pt] - summary: "Earlier 16k prior (published chip-anchored v2 mesh, 16k cells; was called the earlier fine prior). Trained on 35,283 designs (star families subsampled to 300 each)." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:wonky-shape-main] - never_seen: {median_pct: 1.74, mae_ff: 0.98, rmse_ff: 1.87} - ood60: {median_pct: 0.95, mae_ff: 0.41, rmse_ff: 0.75} - cost_s_per_design: {never_seen: 38.0, ood60: 1.84} - - message-passing-fine: - title: "Message-passing network + earlier 16k MoM prior (R=3, published chip-anchored v2 mesh, 16k cells)" - repo_id: SQuADDS/2026PaperModels-message-passing-fine - kind: gnn - prior: fine - rounds: 3 - status: available - checkpoints: [data_local/mega/ckpt_fine/ALL_mom_s0.pt, data_local/mega/ckpt_fine/ALL_mom_s1.pt, data_local/mega/ckpt_fine/ALL_mom_s2.pt] - summary: "Earlier 16k prior (published chip-anchored v2 mesh, 16k cells; was called the earlier fine prior). Trained on 35,283 designs (star families subsampled to 300 each)." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc] - never_seen: {median_pct: 1.74, mae_ff: 0.74, rmse_ff: 1.39} - ood60: {median_pct: 1.11, mae_ff: 0.47, rmse_ff: 0.91} - in_family_full: {median_pct: "0.18-1.04", mae_ff: "0.015-0.30", rmse_ff: "0.020-0.46"} - cost_s_per_design: {never_seen: 38.0, ood60: 1.85} - - all-data: - title: "All-data pair-local network + earlier 16k MoM prior (R=0, published chip-anchored v2 mesh)" - repo_id: SQuADDS/2026PaperModels-all-data - kind: gnn - prior: fine - rounds: 0 - status: available - checkpoints: [data_local/mega/alldata/fine_r0_s0.pt, data_local/mega/alldata/fine_r0_s1.pt, data_local/mega/alldata/fine_r0_s2.pt] - summary: "Trained on every labelled design (no held-out family). Not zero-shot on any paper test set. Candidate E of deploy/MODEL_SELECTION.md." - validation: {median_pct: 2.25, mae_ff: 0.778, rmse_ff: 2.27, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - paper: - appears_in: [sec:res-opt (All-data model paragraph)] - - all-data-base: - title: "All-data pair-local network + earlier standard MoM prior (R=0)" - repo_id: SQuADDS/2026PaperModels-all-data-base - kind: gnn - prior: standard - rounds: 0 - status: available - checkpoints: [data_local/mega/alldata/base_r0_s0.pt, data_local/mega/alldata/base_r0_s1.pt, data_local/mega/alldata/base_r0_s2.pt] - summary: "Trained on every labelled design, earlier standard 8k-cell MoM prior. Safety fallback of the coarse tier if its v3 prior cannot be solved (not needed on any test layout since the non-positive-definite fix). Candidate D of deploy/MODEL_SELECTION.md." - validation: {median_pct: 2.77, mae_ff: 0.96, rmse_ff: 2.657, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - - all-data-v3s: - title: "All-data pair-local network + coarse prior (v3, one gap/3 solve, R=0)" - repo_id: SQuADDS/2026PaperModels-all-data-v3s - kind: gnn - prior: v3 - rounds: 0 - status: available - fallback: all-data-base - checkpoints: [data_local/mega/alldata/v3s_r0_s0.pt, data_local/mega/alldata/v3s_r0_s1.pt, data_local/mega/alldata/v3s_r0_s2.pt] - summary: "Deployed coarse tier (default; fastest). Trained on every labelled design on the conductor-anchored v3 MoM prior (one gap/3 solve). Candidate V3S-PLall of deploy/MODEL_SELECTION.md." - validation: {median_pct: 1.75, mae_ff: 0.534, rmse_ff: 1.173, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - paper: - appears_in: [tab:candidates, tab:wonky-shape-main] - ood60: {median_pct: 1.06, mae_ff: 0.45, rmse_ff: 0.90, note: "OOD-60 not in training; never-seen families are"} - heldout: - ood60: {median_pct: 1.06, mae_ff: 0.449, rmse_ff: 0.898} - pocket3_random36: {median_pct: 1.90, mae_ff: 0.319, rmse_ff: 0.563} - qiskit_metal_new116: {median_pct: 1.84, mae_ff: 0.654, rmse_ff: 1.416} - pocket3_biased20: {median_pct: 3.10, mae_ff: 0.503, rmse_ff: 0.836} - cost_s_per_design: {median: 3.0, p90: 8.0, max: 12.8, note: "end to end from the GDS, 2 threads, HPC main-partition node"} - - all-data-v3-rich: - title: "All-data pair-local network + fine prior (v3-rich, gap/3 + gap/6 Richardson, R=0)" - repo_id: SQuADDS/2026PaperModels-all-data-v3-rich - kind: gnn - prior: v3-rich - rounds: 0 - status: available - fallback: all-data - checkpoints: [data_local/mega/alldata/v3_r0_s0.pt, data_local/mega/alldata/v3_r0_s1.pt, data_local/mega/alldata/v3_r0_s2.pt] - summary: "Fine tier until 2026-10-10 (now all-data-flagship: same weights, flagship prior). Trained on every labelled design on the Richardson-extrapolated v3 MoM prior (gap/3 + gap/6). Candidate V3R-PLall of deploy/MODEL_SELECTION.md." - validation: {median_pct: 1.31, mae_ff: 0.403, rmse_ff: 0.877, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - paper: - appears_in: [tab:candidates, tab:wonky-shape-main] - ood60: {median_pct: 0.66, mae_ff: 0.23, rmse_ff: 0.48, note: "OOD-60 not in training; never-seen families are"} - heldout: - ood60: {median_pct: 0.66, mae_ff: 0.230, rmse_ff: 0.481} - pocket3_random36: {median_pct: 1.75, mae_ff: 0.268, rmse_ff: 0.506} - qiskit_metal_new116: {median_pct: 1.40, mae_ff: 0.505, rmse_ff: 1.064} - pocket3_biased20: {median_pct: 3.15, mae_ff: 0.536, rmse_ff: 1.017} - cost_s_per_design: {median: 12.8, p90: 33.3, max: 50.4, note: "end to end from the GDS, 2 threads, HPC node; stress layouts up to 293 s (400-finger comb)"} - - all-data-lite500: - title: "All-data pair-local network retrained on the flagship-fast lite500 prior (R=0)" - kind: gnn - prior: lite500 - rounds: 0 - status: candidate - checkpoints: [data_local/mega/alldata/lite500_r0_s0.pt, data_local/mega/alldata/lite500_r0_s1.pt, data_local/mega/alldata/lite500_r0_s2.pt] - summary: "flagship-fast candidate (PRIOR_SCHEME.md Part III): micro-MoM at <= 500 merged panels (one window up to 8 conductors; core-graded windows + screened-dipole far pairs beyond); network retrained on every labelled design on this prior (HPC 10-10). Not deployable until the user decides." - - all-data-lite1500: - title: "flagship-fast: all-data pair-local network retrained on the lite-1500 micro-MoM prior (R=0)" - display_name: flagship-fast - repo_id: SQuADDS/2026PaperModels-all-data-lite1500 - kind: gnn - prior: lite1500 - rounds: 0 - status: available - checkpoints: [data_local/mega/alldata/lite1500_r0_s0.pt, data_local/mega/alldata/lite1500_r0_s1.pt, data_local/mega/alldata/lite1500_r0_s2.pt] - summary: "Default released tier since 2026-10-10 (flagship-fast). Cheap physics prior: the flagship mesh family at <= 1,500 merged panels in a canonical frame (one window up to 8 conductors; beyond, core-graded windows of <= 8 conductors with closed-form / screened-dipole far pairs), network retrained on every labelled design on this prior (PRIOR_SCHEME.md Part III). Faster but less accurate than the coarse and fine tiers; the only tier that handles multi-qubit chips." - validation: {median_pct: 2.67, mae_ff: 0.768, rmse_ff: 1.874, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - heldout: - largen40: {median_pct: 4.96, mae_ff: 0.406, rmse_ff: 1.303} - pocket3_biased20: {median_pct: 5.75, mae_ff: 0.641, rmse_ff: 1.076} - cost_s_per_design: {median: 0.23, p90: 0.68, note: "end to end from the GDS, 2 threads, Mac M5 Pro, 212 held-out designs; 780-conductor grid ~15 s on 18 Mac cores"} - - all-data-lite1500td16: - title: "flagship-fast candidate: all-data pair-local network on the lite-1500 prior with approximate pair tokens td16 (R=0)" - kind: gnn - prior: lite1500 - tokens: td16 - rounds: 0 - status: candidate - checkpoints: [data_local/mega/alldata/lite1500td16_r0_s0.pt, data_local/mega/alldata/lite1500td16_r0_s1.pt, data_local/mega/alldata/lite1500td16_r0_s2.pt] - summary: "Token-variant candidate (PRIOR_SCHEME.md 14.3): far boundary samples block-decimated (td16); network retrained on these tokens. Not deployable until the user decides." - - all-data-lite1500td64: - title: "flagship-fast candidate: all-data pair-local network on the lite-1500 prior with approximate pair tokens td64 (R=0)" - kind: gnn - prior: lite1500 - tokens: td64 - rounds: 0 - status: candidate - checkpoints: [data_local/mega/alldata/lite1500td64_r0_s0.pt, data_local/mega/alldata/lite1500td64_r0_s1.pt, data_local/mega/alldata/lite1500td64_r0_s2.pt] - summary: "Token-variant candidate (PRIOR_SCHEME.md 14.3): far boundary samples block-decimated (td64); network retrained on these tokens. Not deployable until the user decides." - - all-data-lite1500tc600: - title: "flagship-fast candidate: all-data pair-local network on the lite-1500 prior with approximate pair tokens tc600 (R=0)" - kind: gnn - prior: lite1500 - tokens: tc600 - rounds: 0 - status: candidate - checkpoints: [data_local/mega/alldata/lite1500tc600_r0_s0.pt, data_local/mega/alldata/lite1500tc600_r0_s1.pt, data_local/mega/alldata/lite1500tc600_r0_s2.pt] - summary: "Token-variant candidate (PRIOR_SCHEME.md 14.3): far boundary samples block-decimated (tc600); network retrained on these tokens. Not deployable until the user decides." - - all-data-formula: - title: "All-data pair-local network retrained on the flagship-fast formula prior (R=0)" - kind: gnn - prior: formula - rounds: 0 - status: candidate - checkpoints: [data_local/mega/alldata/formula_r0_s0.pt, data_local/mega/alldata/formula_r0_s1.pt, data_local/mega/alldata/formula_r0_s2.pt] - summary: "flagship-fast candidate (PRIOR_SCHEME.md Part III): closed-form edge-coupling prior (no mesh); network retrained on every labelled design on this prior (HPC 10-10). Not deployable until the user decides." - - # ---------------------------------------------------------------- flagship prior (PRIOR_SCHEME.md Part II, 2026-10-09): same - # network as all-data-v3-rich, fed with the strip-merged, resolution-controlled Richardson prior (H-matrix solver for large - # layouts). all-data-flagship = released fine tier since 2026-10-10 (user-approved; PRIOR_SCHEME.md section 8.1). - all-data-flagship: - title: "All-data pair-local network + fine prior (flagship: strip-merged Richardson gap/6 + gap/3, resolution-controlled, H-matrix solve; R=0)" - repo_id: SQuADDS/2026PaperModels-all-data-flagship - kind: gnn - prior: flagship - rounds: 0 - status: available - checkpoints: [data_local/mega/alldata/v3_r0_s0.pt, data_local/mega/alldata/v3_r0_s1.pt, data_local/mega/alldata/v3_r0_s2.pt] - summary: "Deployed fine tier (most accurate) since 2026-10-10. The all-data-v3-rich network (unchanged weights, trained on every labelled design) with the flagship prior: 6 + 3 panels across the smallest gap on every layout, Richardson-extrapolated, dense Cholesky below 12k panels and an H-matrix / PCG solve above. Scale-invariant: the same resolution from one capacitor to a multi-qubit grid. Also the model that the coarse tier routes large layouts to." - validation: {median_pct: 1.13, mae_ff: 0.374, rmse_ff: 0.836, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md; PRIOR_SCHEME.md section 8.1)"} - paper: - appears_in: [tab:flagship, fig:flagship, tab:flagship-cost, sec:res-opt (released models)] - ood60: {median_pct: 0.60, mae_ff: 0.204, rmse_ff: 0.367, note: "OOD-60 not in training"} - heldout: - never_seen926_in_training: {median_pct: 0.50, mae_ff: 0.235, rmse_ff: 0.420, note: "the all-data network trained on these families: not zero-shot"} - ood60: {median_pct: 0.60, mae_ff: 0.204, rmse_ff: 0.367} - pocket3_random36: {median_pct: 1.29, mae_ff: 0.234, rmse_ff: 0.488} - qiskit_metal_new116: {median_pct: 1.28, mae_ff: 0.478, rmse_ff: 1.021} - pocket3_biased20: {median_pct: 2.51, mae_ff: 0.477, rmse_ff: 0.988} - cost_s_per_design: {median: 0.87, p90: 11.6, max: 14.0, note: "212 held-out designs, end to end from the GDS, 2 threads, Mac M5 Pro (PRIOR_SCHEME.md 8.1); 1,158 held-out designs incl. never-seen: median 1.51, p90 27.6, max 78.4 s; peak RSS <= 8.3 GB (grid_qubit_9, 220k panels)"} - all-data-flagship-coarse: - title: "All-data pair-local network + flagship-coarse prior (strip-merged Richardson gap/3 + 2 gap/3, resolution-controlled; R=0)" - repo_id: SQuADDS/2026PaperModels-all-data-v3-rich - kind: gnn - prior: flagship-coarse - rounds: 0 - status: candidate - pending_reason: "not released: fails the PRIOR_SCHEME.md section 7 accuracy criterion on the in-family test split (section 8.1); evaluation candidate only" - checkpoints: [data_local/mega/alldata/v3_r0_s0.pt, data_local/mega/alldata/v3_r0_s1.pt, data_local/mega/alldata/v3_r0_s2.pt] - summary: "The fine-tier network (unchanged weights) with the cheaper flagship pair (3 + 1.5 panels across the smallest gap, Richardson-extrapolated)." - validation: {median_pct: 1.22, mae_ff: 0.418, rmse_ff: 0.908, set: "212 deploy held-out designs (PRIOR_SCHEME.md section 8.1)"} - - # ---------------------------------------------------------------- this work: conductor-anchored v3 priors (paper_ml, 2026-10-08) - # coarse prior = v3s (one gap/3 solve; was "fast"), fine prior = v3-rich (gap/3 + gap/6, Richardson; was "accurate"). - # Model ids and repo names keep the old words (*-fast, *-accurate): they are published links. Metrics: paper tab:candidates - # (median % / MAE fF / RMSE fF, all mutual entries); in_family_test = held-out test split of the 5 families. - pair-local-fast: - title: "Pair-local network + coarse prior (v3, R=0) - paper headline" - repo_id: SQuADDS/2026PaperModels-pair-local-fast - kind: gnn - prior: v3 - rounds: 0 - status: available - fallback: pair-local - checkpoints: [data_local/mega/v3s/ALL_mom_r0_s0.pt, data_local/mega/v3s/ALL_mom_r0_s1.pt, data_local/mega/v3s/ALL_mom_r0_s2.pt] - summary: "This work's headline: zero-shot on never-seen components 1.23 % median. Five training families, coarse conductor-anchored prior (one gap/3 solve)." - paper: - appears_in: [abstract, tab:candidates, tab:costacc, fig:costacc, tab:infamily-v3, tab:wonky-shape-main, fig:newtopo-all] - never_seen: {median_pct: 1.23, mae_ff: 0.57, rmse_ff: 1.02} - ood60: {median_pct: 1.33, mae_ff: 0.47, rmse_ff: 0.92} - in_family_test: {median_pct: 0.30, mae_ff: 0.047, rmse_ff: 0.144} - deploy_heldout: {median_pct: 2.63, mae_ff: 0.616, rmse_ff: 1.193, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - - message-passing-fast: - title: "Message-passing network + coarse prior (v3, R=3)" - repo_id: SQuADDS/2026PaperModels-message-passing-fast - kind: gnn - prior: v3 - rounds: 3 - status: available - fallback: message-passing - checkpoints: [data_local/mega/v3s/ALL_mom_s0.pt, data_local/mega/v3s/ALL_mom_s1.pt, data_local/mega/v3s/ALL_mom_s2.pt] - summary: "Five training families, coarse prior, three message-passing rounds." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:infamily-v3, fig:newtopo-all] - never_seen: {median_pct: 1.67, mae_ff: 0.72, rmse_ff: 1.32} - ood60: {median_pct: 1.33, mae_ff: 0.64, rmse_ff: 1.48} - in_family_test: {median_pct: 0.21, mae_ff: 0.032, rmse_ff: 0.078} - deploy_heldout: {median_pct: 2.70, mae_ff: 0.638, rmse_ff: 1.259, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - - pair-local-accurate: - title: "Pair-local network + fine prior (v3-rich, R=0)" - repo_id: SQuADDS/2026PaperModels-pair-local-accurate - kind: gnn - prior: v3-rich - rounds: 0 - status: available - fallback: pair-local-fine - checkpoints: [data_local/mega/v3/ALL_mom_r0_s0.pt, data_local/mega/v3/ALL_mom_r0_s1.pt, data_local/mega/v3/ALL_mom_r0_s2.pt] - summary: "Five training families, fine (Richardson-extrapolated, gap/3 + gap/6) prior." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:infamily-v3, tab:wonky-shape-main, fig:newtopo-all] - never_seen: {median_pct: 1.57, mae_ff: 0.92, rmse_ff: 1.57} - ood60: {median_pct: 1.02, mae_ff: 0.35, rmse_ff: 0.66} - in_family_test: {median_pct: 0.23, mae_ff: 0.040, rmse_ff: 0.140} - deploy_heldout: {median_pct: 1.91, mae_ff: 0.484, rmse_ff: 1.022, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - - message-passing-accurate: - title: "Message-passing network + fine prior (v3-rich, R=3)" - repo_id: SQuADDS/2026PaperModels-message-passing-accurate - kind: gnn - prior: v3-rich - rounds: 3 - status: available - fallback: message-passing-fine - checkpoints: [data_local/mega/v3/ALL_mom_s0.pt, data_local/mega/v3/ALL_mom_s1.pt, data_local/mega/v3/ALL_mom_s2.pt] - summary: "Five training families, fine prior, three message-passing rounds. Best in family (0.18 % on the held-out test split)." - paper: - appears_in: [tab:candidates, tab:costacc, fig:costacc, tab:infamily-v3, fig:newtopo-all] - never_seen: {median_pct: 1.34, mae_ff: 0.60, rmse_ff: 1.07} - ood60: {median_pct: 1.22, mae_ff: 0.43, rmse_ff: 0.82} - in_family_test: {median_pct: 0.18, mae_ff: 0.031, rmse_ff: 0.100} - deploy_heldout: {median_pct: 2.11, mae_ff: 0.695, rmse_ff: 2.074, set: "212 deploy held-out designs (deploy/MODEL_SELECTION.md)"} - - charge-corrected-prior-fast: - title: "Charge-corrected coarse prior (v3c cell GBM)" - repo_id: SQuADDS/2026PaperModels-charge-corrected-prior-fast - kind: charge_prior - prior: v3 - status: available - checkpoints: [deploy/artifacts/charge_gbm_v3c.joblib] - summary: "Coarse (gap/3 v3) prior with its panel charges corrected by a gradient-boosted model of local geometry fit on the training families' surface charge; no capacitance labels." - paper: - appears_in: [tab:candidates] - never_seen: {median_pct: 2.67, mae_ff: 0.96, rmse_ff: 1.50} - ood60: {median_pct: 1.22, mae_ff: 0.43, rmse_ff: 0.75} - in_family_test: {median_pct: 0.87, mae_ff: 0.24, rmse_ff: 0.76} - - blend-pair-local-fast: - title: "Blended model: pair-local coarse-prior network x charge-corrected coarse prior" - repo_id: SQuADDS/2026PaperModels-blend-pair-local-fast - kind: blend - components: [pair-local-fast, charge-corrected-prior-fast] - status: available - summary: "Log-space blend. Paper numbers use the published file-order weights (0.6 / 0.7 / 0.8); the package uses the order-invariant weights (0.6 / 0.9), see deploy_heldout." - paper: - appears_in: [tab:candidates] - never_seen: {median_pct: 1.28, mae_ff: 0.52, rmse_ff: 0.90, note: published file-order weights} - ood60: {median_pct: 0.98, mae_ff: 0.36, rmse_ff: 0.74, note: published file-order weights} - in_family_test: {median_pct: 0.35, mae_ff: 0.082, rmse_ff: 0.264} - deploy_heldout: {median_pct: 2.33, mae_ff: 0.547, rmse_ff: 1.097, ood60: "1.09 / 0.405 / 0.799", set: "212 deploy held-out designs, order-invariant weights"} - - blend-pair-local-accurate: - title: "Blended model: pair-local fine-prior network x charge-corrected coarse prior" - repo_id: SQuADDS/2026PaperModels-blend-pair-local-accurate - kind: blend - components: [pair-local-accurate, charge-corrected-prior-fast] - status: available - summary: "Log-space blend. Paper numbers use the published file-order weights (0.6 / 0.7 / 0.8); the package uses the order-invariant weights (0.6 / 0.9), see deploy_heldout." - paper: - appears_in: [tab:candidates] - never_seen: {median_pct: 1.75, mae_ff: 0.87, rmse_ff: 1.48, note: published file-order weights} - ood60: {median_pct: 0.96, mae_ff: 0.31, rmse_ff: 0.54, note: published file-order weights} - in_family_test: {median_pct: 0.32, mae_ff: 0.081, rmse_ff: 0.266} - deploy_heldout: {median_pct: 2.02, mae_ff: 0.485, rmse_ff: 1.048, ood60: "1.11 / 0.329 / 0.594", set: "212 deploy held-out designs, order-invariant weights"} - - fast-prior: - title: "Coarse prior alone (v3, one gap/3 solve, training-free)" - repo_id: null - kind: prior - prior: v3 - status: available - summary: "Untrained thin-film MoM on the conductor-anchored v3 mesh, one gap/3 solve (default 8,000-panel cap)." - paper: - appears_in: [tab:candidates, tab:prior] - never_seen: {median_pct: 5.68, mae_ff: 2.67, rmse_ff: 3.91} - ood60: {median_pct: 6.35, mae_ff: 1.66, rmse_ff: 2.56} - in_family_test: {median_pct: 4.38, mae_ff: 0.70, rmse_ff: 1.73} - - accurate-prior: - title: "Fine prior alone (v3-rich, gap/3 + gap/6 Richardson, training-free)" - repo_id: null - kind: prior - prior: v3-rich - status: available - summary: "Untrained thin-film MoM, gap/3 and gap/6 solves on the v3 mesh with Richardson extrapolation." - paper: - appears_in: [tab:candidates, tab:prior] - never_seen: {median_pct: 2.71, mae_ff: 1.42, rmse_ff: 2.34} - ood60: {median_pct: 5.05, mae_ff: 1.30, rmse_ff: 2.08} - in_family_test: {median_pct: 2.71, mae_ff: 0.53, rmse_ff: 1.54} - - # ---------------------------------------------------------------- baselines (paper comparison; not deployable on a GDS) - parameter-mlp: - title: "Parameter MLP (published surrogate, MLQubitDesign)" - repo_id: null - kind: baseline - status: not-released - deployable: false - summary: "Per-family MLP on Qiskit Metal design parameters; input undefined on a new layout." - paper: - appears_in: [tab:candidates, tab:sota, fig:infamily, tab:fewshot] - in_family_full: {median_pct: "1.78-2.62", mae_ff: "0.041-1.32", rmse_ff: "0.055-1.87", note: C_NS} - - parameter-gbt: - title: "Parameter GBT (gradient-boosted trees on design parameters)" - repo_id: null - kind: baseline - status: not-released - deployable: false - summary: "Per-family GBT on design parameters; input undefined on a new layout." - paper: - appears_in: [tab:candidates, fig:infamily] - in_family_full: {median_pct: "0.35-3.36", mae_ff: "0.010-1.93", rmse_ff: "0.015-2.92"} - - neural-operator: - title: "Fourier neural operator on conductor masks (no prior)" - repo_id: null - kind: baseline - status: not-released - deployable: false - summary: "Image model; most accurate in distribution, fails on held-out families." - paper: - appears_in: [tab:candidates] - in_family_id: {median_pct: 0.24, mae_ff: 0.082, rmse_ff: 0.40} - - edge-nn-mom: - title: "Edge nearest-neighbour + MoM (training-free correction)" - repo_id: null - kind: baseline - status: not-released - deployable: false - summary: "Nearest-neighbour correction of the MoM prior in embedding space; needs the training index." - paper: - appears_in: [tab:candidates, tab:lofo] - never_seen: {median_pct: 4.02, mae_ff: 1.5, rmse_ff: 2.4} - ood60: {median_pct: "3.1-6.0", mae_ff: "1.2-1.6", rmse_ff: "1.5-2.2", note: range of per-class medians} - -# --------------------------------------------------------------------------------------------------------------------------- -# paper_v3 final recipes (tlsq_infer.final; parity with scripts/tm_final.py: deploy/tests/test_final_parity.py) and the new -# Space (PLAN_HF_SPACE_V2.md; user decisions 2026-10-14: one PRIVATE Space with a model toggle, built as a new copy, the -# 2026-10-10 Spaces above never overwritten; geometry = training geometry, no ground crop by default). Separate from -# `models` (the 2026-10-10 tiers) so the existing apps and tests are unchanged. Accuracy = the paper's test-once numbers of -# the REPORTED model (data_local/train_matrix/eval/final/summary.parquet; median % / MAE fF / RMSE fF over mutual entries). -v2_hub: - space: shanto268/PlanarCapModel # NEW private repo (user, 2026-10-14); never the 2026-10-10 Spaces above - title: Planar Capacitance (paper models) - private: true # stays private until the paper is out (user, 2026-10-14) - -final_defaults: - model: E3 - trust_rule: true # APPLIED by default to E3 and E3-D (user decision 2026-10-14); trust_rule=False switches it off - trust_rule_note: "Trust rule (applied by default to E3 and E3-D). The E3 model is three independently trained networks. When they agree, their answer is used for pairs of conductors closer than 100 um, and the physics-only C0 value for all other pairs. When they disagree (median spread of log C over the close pairs above tau = 1.254e-3, a threshold fixed in the paper before its blind test), the whole matrix falls back to the physics-only C0 recipe. Every E3 result shows the spread, the threshold and whether the fallback happened. On the paper's blind 9-qubit grid the networks disagreed (spread 2.28e-3) and the rule chose C0: 0.453 % (MAE 0.247 / RMSE 0.473 fF) on the 135 close pairs, against 1.153 % (0.235 / 0.319 fF) for E3 alone. The test results listed for E3 are those of E3 without the rule. Switch the rule off with the 'apply the trust rule' box (UI), trust_rule=False (/predict_gds) or predict_final(..., trust_rule=False) in the package." - -final_models: - E3: - title: "Model (E3): extrapolated physics + per-kind offsets + bounded learned correction" - recipe: E3 - pair: [1.5, 3.0] - role: reported model (paper_v3) - ledger_id: em_1_p1.5 - source: data_local/e13/em/runs/1 # info_p1.5.json + s{0,1,2}_p1.5.pt (training checkpoints); bundles carry an export - summary: "log-Richardson R(1.5, 3) of the slab lite micro-MoM, per-entry-kind offsets and a bounded (+-3 %) SceneGNN correction; mean log C of 3 seeds. Trained on exp6-12 train + exp13-15 + random 200." - accuracy: - in_family_test_exp6_11: {set: "in-family test exp6-11 (3,819 designs; test-once)", median_pct: 0.110, mae_ff: 0.017, rmse_ff: 0.093} - in_family_test_exp12: {set: "in-family test exp12 (190)", median_pct: 0.089, mae_ff: 0.009, rmse_ff: 0.016} - ood60: {set: "OOD-60 freeform (60)", median_pct: 0.393, mae_ff: 0.195, rmse_ff: 0.437} - qm116: {set: "qm116 unseen qubits / couplers (116)", median_pct: 0.761, mae_ff: 0.227, rmse_ff: 0.591} - p3rand36: {set: "p3rand36 (36)", median_pct: 0.690, mae_ff: 0.099, rmse_ff: 0.180} - largen: {set: "large-N 8-12 conductors (40)", median_pct: 0.972, mae_ff: 0.058, rmse_ff: 0.158} - atlas: {set: "quantum-metal atlas (348)", median_pct: 1.240, mae_ff: 7.102, rmse_ff: 11.734} - grid_qubit_5_near: {set: "grid_qubit_5, pairs within 100 um (67 entries)", median_pct: 1.135, mae_ff: 0.247, rmse_ff: 0.319} - E1: - title: "Fast (E1): extrapolated physics + per-kind offsets (no network)" - recipe: E1 - pair: [0.75, 1.5] - role: reported model (paper_v3), fast mode - ledger_id: em_1_E1_p0.75 - source: data_local/e13/em/1/info_E1_p0.75.json - summary: "log-Richardson R(0.75, 1.5) of the slab lite micro-MoM plus the model's per-entry-kind offsets c_kind; no network, about 3x cheaper solves." - accuracy: - in_family_test_exp6_11: {set: "in-family test exp6-11 (3,819 designs; test-once)", median_pct: 0.656, mae_ff: 0.105, rmse_ff: 0.366} - in_family_test_exp12: {set: "in-family test exp12 (190)", median_pct: 0.964, mae_ff: 0.058, rmse_ff: 0.110} - ood60: {set: "OOD-60 freeform (60)", median_pct: 1.175, mae_ff: 0.503, rmse_ff: 1.159} - qm116: {set: "qm116 unseen qubits / couplers (116)", median_pct: 1.788, mae_ff: 0.568, rmse_ff: 1.135} - p3rand36: {set: "p3rand36 (36)", median_pct: 1.681, mae_ff: 0.380, rmse_ff: 0.652} - largen: {set: "large-N 8-12 conductors (40)", median_pct: 1.894, mae_ff: 0.154, rmse_ff: 0.326} - atlas: {set: "quantum-metal atlas (348)", median_pct: 1.386, mae_ff: 9.423, rmse_ff: 16.172} - grid_qubit_5_near: {set: "grid_qubit_5, pairs within 100 um (67 entries)", median_pct: 0.544, mae_ff: 0.360, rmse_ff: 0.822} - C0: - title: "Physics only (C0): extrapolated micro-MoM, no fitted parameter" - recipe: C0 - pair: [1.5, 3.0] - role: reported model (paper_v3), physics only - ledger_id: C0_p1.5 - summary: "log-Richardson R(1.5, 3) = 2 log MoM(3) - log MoM(1.5) of the slab lite micro-MoM; zero fitted parameters." - accuracy: - in_family_test_exp6_11: {set: "in-family test exp6-11 (3,819 designs; test-once)", median_pct: 1.259, mae_ff: 0.172, rmse_ff: 0.312} - in_family_test_exp12: {set: "in-family test exp12 (190)", median_pct: 1.374, mae_ff: 0.114, rmse_ff: 0.226} - ood60: {set: "OOD-60 freeform (60)", median_pct: 1.065, mae_ff: 0.303, rmse_ff: 0.572} - qm116: {set: "qm116 unseen qubits / couplers (116)", median_pct: 1.260, mae_ff: 0.255, rmse_ff: 0.591} - p3rand36: {set: "p3rand36 (36)", median_pct: 0.836, mae_ff: 0.111, rmse_ff: 0.181} - largen: {set: "large-N 8-12 conductors (40)", median_pct: 0.955, mae_ff: 0.081, rmse_ff: 0.215} - atlas: {set: "quantum-metal atlas (348)", median_pct: 0.609, mae_ff: 3.262, rmse_ff: 5.882} - newfam926: {set: "never-seen 926", median_pct: 0.597, mae_ff: 0.231, rmse_ff: 0.390} - grid_qubit_5_near: {set: "grid_qubit_5, pairs within 100 um (67 entries)", median_pct: 0.735, mae_ff: 0.238, rmse_ff: 0.460} - E3-D: - title: "Deployment model (E3 recipe, D weights): trained on every labelled design" - recipe: E3 - pair: [1.5, 3.0] - role: deployment model (never a paper claim, never test-scored) - ledger_id: null - source: data_local/e13/em/runs/D - summary: "E3 recipe retrained on 42,967 designs (exp6-12 train + val + test, exp13-15 (all 1,754), random 1,000, OOD-60). Its scores on those sets would be in-sample; held-out scoring (atlas, qm116, p3rand36, large-N, grids) not yet run." - warning: "Deployment model D: trained on the in-family test split, exp13-15 and OOD-60, so no test number of the paper applies to it; its held-out scoring is pending. The paper's independently tested model is 'E3'." - scoring_note: &d_scoring "Scoring note for D (2026-10-14, documentation only, no set scored): IN-SAMPLE for D (trained on them, any score would not be a test): in-family test exp6-11 and exp12 (D trained on train + val + test), never-seen 926 (exp13-15, all 1,754 trained), OOD-60 (unusual), random 1,000. HELD OUT from D (no rows of these in its training data): quantum-metal atlas (348), qm116 (116), p3rand36 (36), large-N (40), grid_qubit_1 / 5 / 9, multi-stack, margin. D has not been scored on any of them; numbers shown are the paper's reported model, never D's." - accuracy: {} - E1-D: - title: "Deployment fast (E1 recipe, D constants): per-kind offsets fitted on every labelled design" - recipe: E1 - pair: [0.75, 1.5] - role: deployment model, fast mode (never a paper claim, never test-scored) - ledger_id: null - source: data_local/e13/em/D/info_E1_p0.75.json # scripts/em_matrix.py e1 --models D --pair 0.75 (2026-10-14; train_keys_md5 = D's E3 rows) - summary: "log-Richardson R(0.75, 1.5) of the slab lite micro-MoM plus per-entry-kind offsets c_kind fitted (median log residual, the E1 rule of scripts/em_matrix.py) on D's 42,967 training designs; no network." - warning: "Deployment fast model (D constants): fitted on the in-family test split, exp13-15 and OOD-60, so no test number of the paper applies to it; its held-out scoring is pending. The paper's independently tested fast model is 'E1'." - scoring_note: *d_scoring - accuracy: {} - -# ---------------------------------------------------------------- GNN Space (deploy/GNN_SPACE.md; user 2026-10-16) -# Built by `python deploy/sync.py --gnn` (dry run) / `--gnn --push`; gated by deploy/tests/test_gnn_space.py. New models: add an -# entry below, keep the old one with status: retired (never delete), point gnn_hub.default_model at the new id. -gnn_hub: - space: shanto268/PlanarCapGNN # NEW private repo (user, 2026-10-16); never the Spaces above - status: retired # paused 2026-10-20 (HfApi.pause_space; private, files kept, Space sha 4193e5a7), superseded by the flagship + paper Spaces; restore = HfApi().restart_space - title: Planar Capacitance (GNN preview) - private: true # Spaces stay private (CLAUDE.md rule 11) - space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM - default_model: GNN - compare_models: [E3, C0] # final_models entries served next to the GNN (tlsq_infer.final, as in the v2 Space) - finalization: agents/geomfast/FINALIZATION_V1.json # frozen checkpoint SHA256s; sync.py refuses checkpoints not listed there - parity_reference: data_local/geomfast/raw_parity.json # the 14 TRAIN layouts of the raw-GDS parity gate - frozen_stage: /Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage # frozen inference code (parity reference; local) - fastprior_status: agents/geomfast/FASTPRIOR_STATUS.md # cpu_fast allowed only with a "PASSED for ... cpu_fast" line there (2026-10-16: cpu_fast FAILED, 9.6e-6) - comparison_note: "Paired against E3 on twelve held-out cohorts (paper_v4; equivalence margin 0.25 percentage points of layout-mean median error or 0.05 fF of MAE, set after the results were seen): equivalent on eight, materially better on four (two-net test, component atlas, the three added families against the five-family E3 that never saw them while the GNN trained on 828 other designs of them, sealed synthetic layouts on the median only), materially worse on none; equal end-to-end latency (the two prior solves dominate both)." - -gnn_models: - GNN: - title: "Accurate (physics + network, ~1 s): corrected prior v2m + 3-seed GNN ensemble" - status: available - tier: accurate - arm: full_gnn - role: "accurate tier, default (since 2026-10-17; arm Bm of agents/priorv2): the frozen P2d full_gnn weights (FINALIZATION_V1, unchanged) + prior v2m solved by the compiled exact solver" - ensemble: arithmetic mean of the three full Maxwell matrices - checkpoints: - - {path: data_local/geomfast/runs/p2d_full_gnn_s0/model.pt, sha256: fcb5db5d8237436d546aca0e7463a2f1d4f2e1b18757b2a35eff646c03f3bc5c} - - {path: data_local/geomfast/runs/p2d_full_gnn_s1/model.pt, sha256: 9aef64adfaf99cad35da891a2329d43eac46b2768cd133b5313085891a4fed92} - - {path: data_local/geomfast/runs/p2d_full_gnn_s2/model.pt, sha256: 357c16539967404b0a7eea514ef3ff3dc763c764da192b219d919cb01f697669} - prior: - method: local_gap # micro_mom_loc (slab, local-gap mesh); base = 2 log C(3) - log C(1.5) - ppg: [1.5, 3.0] - alpha: 0.49685219816506904 # unchanged (TRAIN-fitted) - prior_impl: frozen - version: v2m_fc_dipfill_margin # agents/priorv2/FINALIZATION_V2.json "prior" - patches: [priorv2m] # VALUE-CHANGING: geomgnn/priorv2.py = scripts/priorv2/priorv2.py, installed(policy='fc', dip=True, margin=True) - module_sha256: 1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c - mode: exact_compiled # geomgnn.fastprior_pkg solver mode (fv + hmat_vec + mixed + numba compiled H-matrix); TLSQ_GNN_PRIOR_MODE overrides - speed_package_sha256: 4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a # scripts/fastprior_pkg/fastprior_pkg.py, vendored verbatim - speed_approved: "user 2026-10-17 ('faster at equal accuracy is a win'): fastprior_pkg 'Ready to deploy' (agents/fastprior_pkg/RESULTS.md); exact_compiled VAL tie on all 13 families; deploy-path parity gate in deploy/tests/test_gnn_space.py (<= 1e-6 vs the v2m exact path)" - certified_opt_in: "mode certified (+ Rayleigh-Ritz windows with an error certificate) is gated on VAL (tie) but not enabled here; set TLSQ_GNN_PRIOR_MODE=certified (Space variable) to opt in" - value_changing_approved: "user 2026-10-17 ('do whatever to make the models faster and better'); prior v2 PASSED its pre-declared protocol, arm Bm (frozen nets + v2m) recommended for deployment (agents/priorv2/RESULTS.md verdict 4, FINALIZATION_V2.json)" - summary: "The paper_v4 GNN (same frozen weights) on prior v2m: the frozen prior with three fixes of its windowed path (layouts with more than 8 conductors): rescue panels for metals the window mesh leaves without a panel (fc; also removes the rejection tail), the dipole fill for same-pocket far pairs (a physics bug of the frozen fill) and a wider window ground margin. Predictions for N <= 9 are bit-identical to the v1-prior model." - accuracy_note: "Validation split (VAL, development; NOT a test set), arm Bm of agents/priorv2 (data_local/priorv2/val_summary.csv): layout-mean median relative error, MAE and RMSE over mutual entries, 0.1 fF floor; priors computed on the GH200 CPU. v1 prior on the same VAL: all 0.337 % (0.0750 / 0.0997 fF), N > 9 3.468 % (0.2360 / 0.7004 fF). Test numbers (paper_v4, v2m): accuracy_test; the prior-v1 test scoring is kept as accuracy_test_prior_v1." - accuracy: - all_val: {set: "VAL, all layouts", layouts: 4608, median_pct: 0.2287, mae_ff: 0.06737, rmse_ff: 0.0792} - val_n_le_9: {set: "VAL, N <= 9 (bit-identical to the v1-prior model)", layouts: 4428, median_pct: 0.2096, mae_ff: 0.06846, rmse_ff: 0.07529} - val_n_gt_9: {set: "VAL, N > 9", layouts: 180, median_pct: 0.6979, mae_ff: 0.04063, rmse_ff: 0.1752} - val_b3_n_gt_9: {set: "VAL, campaign B3, N > 9", layouts: 115, median_pct: 0.8698, mae_ff: 0.04342, rmse_ff: 0.1724} - val_synth_n_gt_9: {set: "VAL, synthetic, N > 9", layouts: 65, median_pct: 0.3938, mae_ff: 0.0357, rmse_ff: 0.1801} - val_fc_tail: {set: "VAL, rejection-tail layouts (fc fires)", layouts: 16, median_pct: 0.6802, mae_ff: 0.03806, rmse_ff: 0.1842} - val_fill: {set: "VAL, same-pocket dipole fill fires", layouts: 54, median_pct: 1.092, mae_ff: 0.06035, rmse_ff: 0.2571} - val_margin: {set: "VAL, window margin widening fires", layouts: 40, median_pct: 1.207, mae_ff: 0.07865, rmse_ff: 0.3569} - val_twonet: {set: "VAL, two-net", layouts: 98, median_pct: 0.9075, mae_ff: 2.105, rmse_ff: 2.105} - accuracy_signal_self: - all_val: {set: "VAL, all layouts, signal self terms", layouts: 4608, median_pct: 0.2873, mae_ff: 0.1205, rmse_ff: 0.141} - val_n_gt_9: {set: "VAL, N > 9, signal self terms", layouts: 180, median_pct: 1.108, mae_ff: 0.2903, rmse_ff: 0.5737} - accuracy_test_note: "TEST (paper_v4 Table tab:ladder-test and SM Table tab:ladder-cohort, column 'model' = corrected prior v2m, compiled solver; read once): layout-mean median relative error %, MAE and RMSE fF over mutual entries, 0.1 fF floor. Zero-shot macro = mean of the nine component cohorts' layout means (1,878 layouts)." - accuracy_test: - infamily_test: {set: "in-family test (exp6-12 test split)", layouts: 4009, median_pct: 0.177, mae_ff: 0.0203, rmse_ff: 0.0250} - zeroshot_macro: {set: "zero-shot macro (9 component cohorts below)", layouts: 1878, median_pct: 0.587, mae_ff: 1.092, rmse_ff: 1.152} - newfam926: {set: "added families: Xmon, TransmonPocket, shielded concentric (926)", layouts: 926, median_pct: 0.264, mae_ff: 0.1164, rmse_ff: 0.1657} - twonet_test: {set: "two-net test", layouts: 147, median_pct: 0.594, mae_ff: 2.387, rmse_ff: 2.387} - random_sealed: {set: "random layouts, sealed", layouts: 98, median_pct: 0.559, mae_ff: 0.0903, rmse_ff: 0.1216} - synth_sealed: {set: "procedurally generated layouts, sealed", layouts: 107, median_pct: 0.651, mae_ff: 0.0462, rmse_ff: 0.1583} - p3rand36: {set: "held-out TransmonPocket + 3 couplers", layouts: 36, median_pct: 0.326, mae_ff: 0.0686, rmse_ff: 0.1152} - unusual: {set: "freeform geometries", layouts: 60, median_pct: 0.570, mae_ff: 0.2197, rmse_ff: 0.2873} - qm116: {set: "unseen qubits and couplers", layouts: 116, median_pct: 0.672, mae_ff: 0.2103, rmse_ff: 0.3522} - atlas: {set: "quantum-metal component atlas", layouts: 348, median_pct: 0.993, mae_ff: 6.621, rmse_ff: 6.631} - largen: {set: "large N, 8-12 conductors", layouts: 40, median_pct: 0.657, mae_ff: 0.0662, rmse_ff: 0.1522} - grid_qubit_1: {set: "one-qubit lattice, N = 15", layouts: 1, median_pct: 0.370, mae_ff: 0.0538, rmse_ff: 0.1769} - grid_qubit_5: {set: "five-qubit lattice, N = 35", layouts: 1, median_pct: 1.009, mae_ff: 0.0356, rmse_ff: 0.1449} - grid_qubit_9: {set: "nine-qubit lattice, N = 67", layouts: 1, median_pct: 0.960, mae_ff: 0.0221, rmse_ff: 0.1042} - accuracy_lofo_note: "Held-out component family (leave-one-family-out over the five original families; VAL only, no test cohort read): the shipped recipe (P2d full_gnn on prior v2m, 3-seed mean) retrained without the family, scored on that family's held-out VAL layouts (agents/shipped_lofo/RESULTS_P1.md, row d, protocol PROTOCOL_P1.md frozen 2026-10-18). Layout-mean median relative error %, MAE and RMSE fF over mutual entries, 0.1 fF floor. Better than the physics prior alone C^R = R(1.5, 3) on every family, median, MAE and RMSE (pooled 1.554 %, 0.166 / 0.205 fF). The served weights saw these families; this measures a new component type." - accuracy_lofo: - lofo_pooled: {set: "held-out family, pooled VAL", layouts: 4071, median_pct: 0.408, mae_ff: 0.0494, rmse_ff: 0.0591} - lofo_macro: {set: "held-out family, macro of 5", layouts: 4071, median_pct: 0.390, mae_ff: 0.1065, rmse_ff: 0.1383} - lofo_interdigital: {set: "interdigital held out", layouts: 1931, median_pct: 0.413, mae_ff: 0.0397, rmse_ff: 0.0435} - lofo_paddle: {set: "paddle held out", layouts: 1592, median_pct: 0.417, mae_ff: 0.0274, rmse_ff: 0.0312} - lofo_concentric: {set: "concentric held out", layouts: 170, median_pct: 0.544, mae_ff: 0.3824, rmse_ff: 0.4906} - lofo_star: {set: "star held out", layouts: 202, median_pct: 0.200, mae_ff: 0.0395, rmse_ff: 0.0492} - lofo_multipad: {set: "multipad star held out", layouts: 176, median_pct: 0.376, mae_ff: 0.0435, rmse_ff: 0.0771} - latency_test_note: "paper_v4 Table tab:ladder-test: end to end per layout from the layout file, median / 90th percentile, every arm in the same pass on two CPUs of an x86 cluster node (AMD EPYC 7513 / 7542, Xeon Silver 4116)." - latency_test: - infamily_test: {set: "in-family test", layouts: 4009, median_s: 0.845, p90_s: 5.96} - zeroshot: {set: "zero-shot cohorts, pooled", layouts: 1878, median_s: 1.76, p90_s: 18.1} - all_test: {set: "sum over all test layouts", layouts: 5902, sum_s: 20385} - accuracy_test_prior_v1_note: "paper_v4 Table 2 test cohorts, scored once with the SAME weights on prior v1 (the retired default; kept for the record). Layouts with N <= 9 give bit-identical predictions under v2m; the v2m test numbers are accuracy_test." - accuracy_test_prior_v1: - infamily_test: {set: "in-family test (exp6-12 test split)", layouts: 4009, median_pct: 0.1775, mae_ff: 0.02032, rmse_ff: 0.02502} - unusual: {set: "freeform shapes (OOD-60)", layouts: 60, median_pct: 0.5702, mae_ff: 0.2197, rmse_ff: 0.2873} - newfam926: {set: "added families: Xmon, TransmonPocket, shielded concentric (926 test designs; the GNN trained on 828 others of these families)", layouts: 926, median_pct: 0.2642, mae_ff: 0.1164, rmse_ff: 0.1657} - qm116: {set: "unseen qubits and couplers (qm116)", layouts: 116, median_pct: 0.6722, mae_ff: 0.2103, rmse_ff: 0.3522} - p3rand36: {set: "held-out TransmonPockets (p3rand36)", layouts: 36, median_pct: 0.3262, mae_ff: 0.06864, rmse_ff: 0.1152} - largen: {set: "large N, 8-12 conductors", layouts: 40, median_pct: 0.6575, mae_ff: 0.06625, rmse_ff: 0.1522} - atlas: {set: "quantum-metal component atlas", layouts: 348, median_pct: 0.9929, mae_ff: 6.621, rmse_ff: 6.631} - twonet_test: {set: "two-net test", layouts: 147, median_pct: 0.5945, mae_ff: 2.391, rmse_ff: 2.391} - random_sealed: {set: "random layouts, sealed", layouts: 110, median_pct: 0.5672, mae_ff: 0.09022, rmse_ff: 0.1225} - synth_sealed: {set: "synthetic layouts, sealed (2-68 conductors)", layouts: 107, median_pct: 0.6995, mae_ff: 0.1108, rmse_ff: 0.4076} - grid_qubit_1: {set: "grid unit, N = 15 (one layout)", layouts: 1, median_pct: 0.3703, mae_ff: 0.05383, rmse_ff: 0.1769} - grid_qubit_5: {set: "grid cluster, N = 35 (one layout)", layouts: 1, median_pct: 1.009, mae_ff: 0.0356, rmse_ff: 0.1449} - latency_note: "prior v1 numbers (paper_v4 Table 6). prior v2m: same cost on N <= 9; on the rejection tail the prior is 18-68x faster (agents/priorv2/RESULTS.md: VAL tail 3,609 -> 52.6 s on the GH200 CPU), the margin widening adds ~2 %." - latency: - development: {set: "development: 14 TRAIN layouts, one per source, N <= 18 (job 6492904)", layouts: 14, total_median_s: 1.258, total_p95_s: 53.25, geometry_median_s: 0.1202, prior_median_s: 0.95, network_median_s: 0.0116, paired_speedup_vs_E3: 1.14, speedup_ci95: [1.04, 1.26], machine: "GH200 node c02-13 (aarch64), 2 threads, 3 interleaved invocations per layout, median over layouts"} - external: {set: "external: 9 label-free layouts, N = 2-68 (job 6493337)", layouts: 9, total_median_s: 13.08, total_p95_s: 67.88, geometry_median_s: 1.796, prior_median_s: 10.6, network_median_s: 0.0428, paired_speedup_vs_E3: 0.955, speedup_ci95: [0.924, 0.981], machine: "GH200 node c02-13 (aarch64), 2 threads, 3 interleaved invocations per layout, median over layouts"} - GNN-prior-v1: - title: "GNN, prior v1 (default until 2026-10-17): full geometric embedding + two-resolution MoM prior, 3-seed ensemble" - status: retired # 2026-10-17: replaced as default by GNN (same weights, prior v2m); kept, never deleted - arm: full_gnn - role: retired default (paper_v4 primary; frozen 2026-10-16, FINALIZATION_V1); prior v1 + rejtail_fv - ensemble: arithmetic mean of the three full Maxwell matrices - checkpoints: - - {path: data_local/geomfast/runs/p2d_full_gnn_s0/model.pt, sha256: fcb5db5d8237436d546aca0e7463a2f1d4f2e1b18757b2a35eff646c03f3bc5c} - - {path: data_local/geomfast/runs/p2d_full_gnn_s1/model.pt, sha256: 9aef64adfaf99cad35da891a2329d43eac46b2768cd133b5313085891a4fed92} - - {path: data_local/geomfast/runs/p2d_full_gnn_s2/model.pt, sha256: 357c16539967404b0a7eea514ef3ff3dc763c764da192b219d919cb01f697669} - prior: - method: local_gap # micro_mom_loc (slab, local-gap mesh); base = 2 log C(3) - log C(1.5) - ppg: [1.5, 3.0] - alpha: 0.49685219816506904 # gap-share alpha fitted on TRAIN only - prior_impl: frozen # frozen | cpu_fast (geomgnn.fastmom; cpu_fast FAILED parity 2026-10-16: keep frozen) - patches: [rejtail_fv] # value-preserving rejection-tail fix (geomgnn/rejtail_fv.py; agents/rejtail/RESULTS.md; user 2026-10-17); bit-identical matrices - summary: "Message-passing network (2 rounds, 89,858 parameters per seed) over the full conductor vectors (shape scalars, Fourier contour, width spectrum), pair vectors with local context tokens and the global vector; corrects the log-Richardson extrapolation of the slab micro-MoM at 1.5 and 3 panels per gap by at most +-0.2 in log and predicts every self term through a learned positive row-sum closure, so the output is the complete Maxwell matrix (symmetric, Maxwell-signed, positive-definite signal block by construction). Trained on 35,354 Q3D layouts (all training sources, 2-68 conductors), Si 11.45 / 350 um." - accuracy: # paper_v4 Table 2 (data_local/geomfast/consolidated/layout_macro_summary.csv): layout-mean, 0.1 fF floor - infamily_test: {set: "in-family test (exp6-12 test split)", layouts: 4009, median_pct: 0.1775, mae_ff: 0.02032, rmse_ff: 0.02502} - unusual: {set: "freeform shapes (OOD-60)", layouts: 60, median_pct: 0.5702, mae_ff: 0.2197, rmse_ff: 0.2873} - newfam926: {set: "added families: Xmon, TransmonPocket, shielded concentric (926 test designs; the GNN trained on 828 others of these families)", layouts: 926, median_pct: 0.2642, mae_ff: 0.1164, rmse_ff: 0.1657} - qm116: {set: "unseen qubits and couplers (qm116)", layouts: 116, median_pct: 0.6722, mae_ff: 0.2103, rmse_ff: 0.3522} - p3rand36: {set: "held-out TransmonPockets (p3rand36)", layouts: 36, median_pct: 0.3262, mae_ff: 0.06864, rmse_ff: 0.1152} - largen: {set: "large N, 8-12 conductors", layouts: 40, median_pct: 0.6575, mae_ff: 0.06625, rmse_ff: 0.1522} - atlas: {set: "quantum-metal component atlas", layouts: 348, median_pct: 0.9929, mae_ff: 6.621, rmse_ff: 6.631} - twonet_test: {set: "two-net test", layouts: 147, median_pct: 0.5945, mae_ff: 2.391, rmse_ff: 2.391} - random_sealed: {set: "random layouts, sealed", layouts: 110, median_pct: 0.5672, mae_ff: 0.09022, rmse_ff: 0.1225} - synth_sealed: {set: "synthetic layouts, sealed (2-68 conductors)", layouts: 107, median_pct: 0.6995, mae_ff: 0.1108, rmse_ff: 0.4076} - grid_qubit_1: {set: "grid unit, N = 15 (one layout)", layouts: 1, median_pct: 0.3703, mae_ff: 0.05383, rmse_ff: 0.1769} - grid_qubit_5: {set: "grid cluster, N = 35 (one layout)", layouts: 1, median_pct: 1.009, mae_ff: 0.0356, rmse_ff: 0.1449} - latency: # paper_v4 Table 6 (data_local/geomfast/consolidated/timing_summary.csv) - development: {set: "development: 14 TRAIN layouts, one per source, N <= 18 (job 6492904)", layouts: 14, total_median_s: 1.258, total_p95_s: 53.25, geometry_median_s: 0.1202, prior_median_s: 0.95, network_median_s: 0.0116, paired_speedup_vs_E3: 1.14, speedup_ci95: [1.04, 1.26], machine: "GH200 node c02-13 (aarch64), 2 threads, 3 interleaved invocations per layout, median over layouts"} - external: {set: "external: 9 label-free layouts, N = 2-68 (job 6493337)", layouts: 9, total_median_s: 13.08, total_p95_s: 67.88, geometry_median_s: 1.796, prior_median_s: 10.6, network_median_s: 0.0428, paired_speedup_vs_E3: 0.955, speedup_ci95: [0.924, 0.981], machine: "GH200 node c02-13 (aarch64), 2 threads, 3 interleaved invocations per layout, median over layouts"} - GNN-LP: - title: "Fast (learned prior, ~0.1 s; trained component families only): learned prior surrogate + the same 3-seed GNN ensemble" - status: available - tier: fast - arm: full_gnn - role: "fast tier (2026-10-18; agents/learnedprior final arm): the learned prior surrogate t100_norm in place of the two field solves, feeding the frozen P2d full_gnn weights (FINALIZATION_V1, unchanged); no field solve" - ensemble: arithmetic mean of the three full Maxwell matrices - checkpoints: - - {path: data_local/geomfast/runs/p2d_full_gnn_s0/model.pt, sha256: fcb5db5d8237436d546aca0e7463a2f1d4f2e1b18757b2a35eff646c03f3bc5c} - - {path: data_local/geomfast/runs/p2d_full_gnn_s1/model.pt, sha256: 9aef64adfaf99cad35da891a2329d43eac46b2768cd133b5313085891a4fed92} - - {path: data_local/geomfast/runs/p2d_full_gnn_s2/model.pt, sha256: 357c16539967404b0a7eea514ef3ff3dc763c764da192b219d919cb01f697669} - prior: null # no field solve; the learned prior below predicts both priors - learned_prior: - name: surrogate_t100_norm - checkpoint: {path: data_local/learnedprior/runs/t100_norm/model.pt, sha256: 622fc374cc989bcc5569373787996169b8cde1254efdd118baa7252da0d788ce} # = agents/v4test/HASHES.json surrogate_t100_norm - floor_ff: 1.7161304599611071e-09 # smallest positive prior mutual entry of the surrogate's training data (learnedprior/p2d_prepared TRAIN, both levels): the predicted priors are floored here before the networks' log (agents/embedspeed; grid_full underflowed to 0) - code: "geomgnn/lp_surrogate.py = scripts/learnedprior/lp_surrogate.py (sha256 55804c93..., verbatim) + schema_p2d.json (17eba5f7...); geomgnn/learned_prior.py = lp_bench.py Learned.from_gds after the features" - ppg: [1.5, 3.0] # predicts log P at 1.5 and 3 panels per gap (the priors the networks read) - training: "tri-GNN (1.02M parameters, width 128, 4 rounds) on the exact frozen prior of 35,354 geomfast TRAIN layouts + 384k generated layouts (v1 235k + targeted 149k), 60k steps, H200 job 6497375 (agents/learnedprior/STATUS.md, PROTOCOL.md)" - summary: "The accurate tier's networks (same frozen weights) fed by a learned surrogate of the two field-solve priors instead of the solves: about 0.1 s per layout, no field solve. Its accuracy holds only for the 13 component families its learned prior and networks were trained on: interdigital capacitors, paddle capacitors, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net layouts, random layouts, procedurally generated layouts (2-7 and 8 or more conductors) and the synthetic multi-conductor campaign layouts (up to 18 conductors). On a component family it never saw, the surrogate's prior error rises 3-17x and the fast tier is worse than the physics prior alone (accuracy_lofo). For a new component type use the accurate tier (GNN)." - warning: "Use Fast only for the 13 component families it was trained on: interdigital capacitors, paddle capacitors, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net layouts, random layouts, procedurally generated layouts (2-7 and 8 or more conductors) and synthetic multi-conductor campaign layouts (up to 18 conductors). For any other component type use Accurate (GNN). On a component family held out of its training (learned prior and networks both retrained without it; five families, 4,071 held-out validation layouts) Fast is at 3.11 % (MAE 0.533 / RMSE 0.633 fF), worse than the physics prior alone, 1.55 % (0.166 / 0.205 fF), while Accurate held out the same way is at 0.41 % (0.049 / 0.059 fF); worst on concentric, 11.7 % (6.43 / 7.36 fF). In family (test) Fast is at 0.630 % (0.113 / 0.141 fF) vs Accurate 0.177 % (0.0203 / 0.0250 fF); on the never-seen test components (zero-shot macro) 3.58 % (4.61 / 5.06 fF) vs 0.587 % (1.09 / 1.15 fF). Use Accurate for any number you rely on." - accuracy_note: "Validation split (VAL, development; NOT a test set; agents/learnedprior ladder_val4608, data_local/learnedprior/e2e_phase2_t100/ladder_val4608.json): layout-mean median relative error, MAE and RMSE over mutual entries, 0.1 fF floor. Same VAL, exact prior v1 + the same networks: 0.337 % (0.0750 / 0.0997 fF); accurate tier (v2m): 0.229 % (0.0674 / 0.0792 fF); solver-free network: 1.486 % (0.630 / 0.728 fF)." - accuracy: - all_val: {set: "VAL, all layouts", layouts: 4608, median_pct: 0.8457, mae_ff: 0.4910, rmse_ff: 0.5486} - val_interdigital: {set: "VAL, interdigital", layouts: 1931, median_pct: 0.5782, mae_ff: 0.06004, rmse_ff: 0.06874} - val_paddle: {set: "VAL, paddle", layouts: 1592, median_pct: 0.4224, mae_ff: 0.03180, rmse_ff: 0.03893} - val_star: {set: "VAL, star", layouts: 202, median_pct: 0.7109, mae_ff: 0.1384, rmse_ff: 0.1741} - val_multipad: {set: "VAL, multipad", layouts: 176, median_pct: 1.314, mae_ff: 0.1447, rmse_ff: 0.2437} - val_concentric: {set: "VAL, concentric", layouts: 170, median_pct: 1.778, mae_ff: 1.160, rmse_ff: 1.449} - val_campaign_b3: {set: "VAL, campaign B3 (N up to 18)", layouts: 149, median_pct: 3.926, mae_ff: 0.2707, rmse_ff: 0.8017} - val_twonet: {set: "VAL, two-net", layouts: 98, median_pct: 2.811, mae_ff: 17.14, rmse_ff: 17.14} - val_random: {set: "VAL, random", layouts: 94, median_pct: 2.292, mae_ff: 0.3121, rmse_ff: 0.3924} - val_synth_n_ge_8: {set: "VAL, synthetic N >= 8", layouts: 74, median_pct: 1.417, mae_ff: 0.1628, rmse_ff: 0.7144} - val_synth_n_le_7: {set: "VAL, synthetic N <= 7", layouts: 29, median_pct: 2.422, mae_ff: 0.4819, rmse_ff: 0.8089} - val_transmon_pocket: {set: "VAL, TransmonPocket", layouts: 48, median_pct: 1.290, mae_ff: 0.2917, rmse_ff: 0.4039} - val_shielded_concentric: {set: "VAL, shielded concentric", layouts: 27, median_pct: 3.267, mae_ff: 1.655, rmse_ff: 2.298} - val_xmon: {set: "VAL, Xmon", layouts: 18, median_pct: 1.647, mae_ff: 0.6089, rmse_ff: 0.8233} - accuracy_lofo_note: "Held-out component family (leave-one-family-out over the five original families; VAL only, no test cohort read): the learned prior surrogate AND the networks retrained without the family, scored on that family's held-out VAL layouts (agents/fastlofo_p5/RESULTS_P5.md, row a, protocol PROTOCOL_P5.md frozen 2026-10-18; data_local/fastlofo_p5/metrics/family_table.csv). Layout-mean median relative error %, MAE and RMSE fF over mutual entries, 0.1 fF floor. Same layouts: physics prior alone C^R = R(1.5, 3) 1.554 % (0.166 / 0.205 fF); accurate recipe held out the same way 0.408 % (0.0494 / 0.0591 fF). Mac M5 Pro, 2 threads: fast 0.0835 s median per layout (p90 0.163 s), exact prior + networks 1.891 s (p90 9.53 s)." - accuracy_lofo: - lofo_pooled: {set: "held-out family, pooled VAL", layouts: 4071, median_pct: 3.113, mae_ff: 0.533, rmse_ff: 0.633} - lofo_macro: {set: "held-out family, macro of 5", layouts: 4071, median_pct: 5.413, mae_ff: 1.622, rmse_ff: 1.974} - lofo_interdigital: {set: "interdigital held out", layouts: 1931, median_pct: 2.550, mae_ff: 0.291, rmse_ff: 0.331} - lofo_paddle: {set: "paddle held out", layouts: 1592, median_pct: 2.444, mae_ff: 0.184, rmse_ff: 0.206} - lofo_concentric: {set: "concentric held out", layouts: 170, median_pct: 11.693, mae_ff: 6.431, rmse_ff: 7.358} - lofo_star: {set: "star held out", layouts: 202, median_pct: 1.761, mae_ff: 0.327, rmse_ff: 0.404} - lofo_multipad: {set: "multipad star held out", layouts: 176, median_pct: 8.619, mae_ff: 0.877, rmse_ff: 1.573} - accuracy_test_note: "TEST (paper_v4 Table tab:ladder-test and SM Table tab:ladder-cohort-b, column 'surrogate + networks'; read once): layout-mean median relative error %, MAE and RMSE fF over mutual entries, 0.1 fF floor. Zero-shot macro = mean of the nine component cohorts' layout means (1,878 layouts)." - accuracy_test: - infamily_test: {set: "in-family test (exp6-12 test split)", layouts: 4009, median_pct: 0.630, mae_ff: 0.1130, rmse_ff: 0.1414} - zeroshot_macro: {set: "zero-shot macro (9 component cohorts below)", layouts: 1878, median_pct: 3.576, mae_ff: 4.608, rmse_ff: 5.058} - newfam926: {set: "added families: Xmon, TransmonPocket, shielded concentric (926)", layouts: 926, median_pct: 1.879, mae_ff: 0.795, rmse_ff: 1.103} - twonet_test: {set: "two-net test", layouts: 147, median_pct: 2.453, mae_ff: 15.90, rmse_ff: 15.90} - random_sealed: {set: "random layouts, sealed", layouts: 98, median_pct: 2.136, mae_ff: 0.328, rmse_ff: 0.417} - synth_sealed: {set: "procedurally generated layouts, sealed", layouts: 107, median_pct: 1.449, mae_ff: 0.139, rmse_ff: 0.465} - p3rand36: {set: "held-out TransmonPocket + 3 couplers", layouts: 36, median_pct: 4.014, mae_ff: 1.045, rmse_ff: 2.169} - unusual: {set: "freeform geometries", layouts: 60, median_pct: 5.961, mae_ff: 2.288, rmse_ff: 2.952} - qm116: {set: "unseen qubits and couplers", layouts: 116, median_pct: 4.767, mae_ff: 1.358, rmse_ff: 2.230} - atlas: {set: "quantum-metal component atlas", layouts: 348, median_pct: 5.477, mae_ff: 19.23, rmse_ff: 19.37} - largen: {set: "large N, 8-12 conductors", layouts: 40, median_pct: 4.049, mae_ff: 0.384, rmse_ff: 0.920} - grid_qubit_1: {set: "one-qubit lattice, N = 15", layouts: 1, median_pct: 1.549, mae_ff: 0.548, rmse_ff: 1.649} - grid_qubit_5: {set: "five-qubit lattice, N = 35", layouts: 1, median_pct: 2.471, mae_ff: 0.206, rmse_ff: 0.751} - grid_qubit_9: {set: "nine-qubit lattice, N = 67", layouts: 1, median_pct: 1.408, mae_ff: 0.151, rmse_ff: 0.940} - latency_test_note: "paper_v4 Table tab:ladder-test: end to end per layout from the layout file, median / 90th percentile, every arm in the same pass on two CPUs of an x86 cluster node (AMD EPYC 7513 / 7542, Xeon Silver 4116)." - latency_test: - infamily_test: {set: "in-family test", layouts: 4009, median_s: 0.092, p90_s: 0.26} - zeroshot: {set: "zero-shot cohorts, pooled", layouts: 1878, median_s: 0.30, p90_s: 2.47} - all_test: {set: "sum over all test layouts", layouts: 5902, sum_s: 2635} - latency_note: "agents/learnedprior/STATUS.md (job 6501886, data_local/learnedprior/bench/final_t100): same run, exact prior v1 + the same networks 1.120 s median (p95 31.6 s, max 56.2 s); the surrogate step itself 5.6 ms median." - latency: - development: {set: "development: 14 TRAIN layouts, one per source, N <= 18 (job 6501886)", layouts: 14, total_median_s: 0.1224, total_p95_s: 0.5945, geometry_median_s: 0.1116, prior_median_s: 0.00556, network_median_s: 0.00317, machine: "GH200 node c02-13 CPU (aarch64, shared node), 2 threads, 3 interleaved invocations per layout, median over layouts"} - GNN-fast: - title: "GNN-fast: same network, no physics solve (much less accurate on unseen geometry)" - status: retired # 2026-10-18: superseded by GNN-LP (learned prior) at the same speed; kept, never deleted (restore: status available) - retired: "superseded 2026-10-18 by the fast tier GNN-LP (learned prior + the accurate tier's networks): same speed (test sum 2,635 vs 2,619 s), lower MAE and RMSE on every test cohort and lower median on all but the five- and nine-qubit lattices (2.47 vs 1.95 %, 1.41 vs 1.30 %)" - arm: direct_gnn - role: speed trade-off (paper_v4 solver-free arm; frozen 2026-10-16, FINALIZATION_V1) - ensemble: arithmetic mean of the three full Maxwell matrices - checkpoints: - - {path: data_local/geomfast/runs/p2d_direct_gnn_s0/model.pt, sha256: c3c0b8850d74984ebd6d1d42b63d9f8124bf9029627dda60e7aa0a1bdd9065c9} - - {path: data_local/geomfast/runs/p2d_direct_gnn_s1/model.pt, sha256: 3cc2e71de05e29a18212ad467c664d3219ff853c7522d45c1582b7af4185db25} - - {path: data_local/geomfast/runs/p2d_direct_gnn_s2/model.pt, sha256: 57bc28024fc6c5f0c5db424e313474cd64177b13fb9e3bc3d2044b1a01b8f691} - prior: null # no solve: base = training-median log mutual per pair kind, unbounded head - summary: "The GNN without the physics prior: reads the layout and the geometric embedding only. 5-12x faster, but far less accurate outside the training distribution." - warning: "GNN-fast runs no physics solve and is much less accurate on geometry unlike its training layouts: component atlas median 114.5 % (MAE 53.6 fF, RMSE 56.6 fF), unseen qubits and couplers 9.6 % (MAE 2.02 fF, RMSE 3.28 fF). Use GNN for any number you rely on." - accuracy: - infamily_test: {set: "in-family test (exp6-12 test split)", layouts: 4009, median_pct: 1.219, mae_ff: 0.1872, rmse_ff: 0.229} - unusual: {set: "freeform shapes (OOD-60)", layouts: 60, median_pct: 7.007, mae_ff: 3.358, rmse_ff: 4.731} - newfam926: {set: "added families: Xmon, TransmonPocket, shielded concentric (926 test designs; the GNN trained on 828 others of these families)", layouts: 926, median_pct: 2.381, mae_ff: 0.8933, rmse_ff: 1.194} - qm116: {set: "unseen qubits and couplers (qm116)", layouts: 116, median_pct: 9.572, mae_ff: 2.016, rmse_ff: 3.28} - p3rand36: {set: "held-out TransmonPockets (p3rand36)", layouts: 36, median_pct: 6.208, mae_ff: 1.515, rmse_ff: 3.127} - largen: {set: "large N, 8-12 conductors", layouts: 40, median_pct: 6.089, mae_ff: 0.5381, rmse_ff: 1.324} - atlas: {set: "quantum-metal component atlas", layouts: 348, median_pct: 114.5, mae_ff: 53.57, rmse_ff: 56.6} - twonet_test: {set: "two-net test", layouts: 147, median_pct: 2.724, mae_ff: 17.68, rmse_ff: 17.68} - random_sealed: {set: "random layouts, sealed", layouts: 110, median_pct: 3.282, mae_ff: 0.4278, rmse_ff: 0.5397} - synth_sealed: {set: "synthetic layouts, sealed (2-68 conductors)", layouts: 107, median_pct: 3.862, mae_ff: 0.413, rmse_ff: 1.271} - grid_qubit_1: {set: "grid unit, N = 15 (one layout)", layouts: 1, median_pct: 2.271, mae_ff: 1.163, rmse_ff: 3.212} - grid_qubit_5: {set: "grid cluster, N = 35 (one layout)", layouts: 1, median_pct: 1.948, mae_ff: 0.5229, rmse_ff: 2.736} - latency: - development: {set: "development: 14 TRAIN layouts, one per source, N <= 18 (job 6492904)", layouts: 14, total_median_s: 0.1246, total_p95_s: 0.6876, geometry_median_s: 0.1162, prior_median_s: 0.0, network_median_s: 0.00455, paired_speedup_vs_E3: 12.0, speedup_ci95: [6.58, 21.4], machine: "GH200 node c02-13 (aarch64), 2 threads, 3 interleaved invocations per layout, median over layouts"} - external: {set: "external: 9 label-free layouts, N = 2-68 (job 6493337)", layouts: 9, total_median_s: 1.817, total_p95_s: 6.641, geometry_median_s: 1.799, prior_median_s: 0.0, network_median_s: 0.0188, paired_speedup_vs_E3: 5.28, speedup_ci95: [4.0, 7.08], machine: "GH200 node c02-13 (aarch64), 2 threads, 3 interleaved invocations per layout, median over layouts"} - -# ---------------------------------------------------------------- paper Space (paper_v4 PRX; user decision 2026-10-19; deploy/GNN_SPACE.md "Paper Space") -# Built by `python deploy/sync.py --paper` (dry run) / `--paper --push`; gated by deploy/tests/test_paper_space.py. One live selector per arm -# of the paper's ladder (tab:ladder-test) and routes (tab:routes) tables that runs from a layout file on a CPU; every other study -# checkpoint is in the private model repo paper_hub.checkpoints_repo. Numbers: layout-mean median relative error % (MAE / RMSE fF) -# over mutual entries, 0.1 fF floor; VAL = 4,608 validation layouts (development); test = the paper's test benchmark, read once -# (in family 4,009 layouts; zero-shot macro = mean of the nine component cohorts' layout means, 1,878 layouts); time = end to end per -# layout, median / 90th percentile, two CPUs of an x86 cluster node (tab:ladder-test) unless stated. -paper_hub: - space: shanto268/2026PaperModels # reused (same gradio SDK): its earlier contents are archived (archive below) - retired: {date: 2026-11-06, note: "author decision: no dedicated paper Space; the paper's models stay on HF as model repos only (SQuADDS/PlanarCapacitance-paper, SQuADDS/2026PaperModels-*). The Space itself is not deleted or modified; app_paper.py, sync.py --paper and its gate stay working, not deployed"} - title: Planar Capacitance (paper models) - private: true # Spaces stay private (CLAUDE.md rule 11) - space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM - default_arm: model - checkpoints_repo: shanto268/PlanarCap2026PaperCheckpoints # private model repo: every other checkpoint the paper reports + scripts - companion_space: shanto268/PlanarCapacitanceModel # the flagship Space (fast / balanced / accurate, trained on all data); was PlanarCapGNN until 2026-10-20 - max_conductors: 70 # signal conductors per layout on this Space (the nine-qubit lattice has 66 + ground) - archive: - space: shanto268/2026PaperModels - commit: 6dc21890fa2d8569225ce8be97cb091b87465d0d # last commit of the earlier draft's 21-model Space (2026-10-10); restore = push this revision - local_copy: data_local/hf_archive/2026PaperModels_6dc21890 # snapshot_download of that revision (100 files, 64 MB) - note: "the earlier draft's model repos (SQuADDS/2026PaperModels-*) are untouched" - deployed: {commit: 53ba4502b9697bd65d69f249d71df65c475c863b, date: 2026-10-20, gate: deploy/tests/results/paper_space_gate_20261020.json, - live: deploy/tests/results/paper_space_live_20261020_examples.json} # 24 arms, 156 MB bundle, RUNNING on cpu-basic, private - text_update: {commit: 34091ebf7be6bbc7ebc37e392b7ae527805cbe97, date: 2026-10-20, gate: deploy/tests/results/paper_space_gate_flagshiplink_20261020.json} # README companion link -> flagship Space; outputs unchanged (48/48 live matrices equal) - docker: {commit: fa7caa49ddd11421b04b44ee2d03fbf4ba632d90, date: 2026-10-20, sdk: docker, bundle: deploy/build_paper_docker/2026PaperModels, - live: deploy/tests/results/paper_space_live_after_20261020.json, rollback: {commit: 34091ebf7be6bbc7ebc37e392b7ae527805cbe97, sdk: gradio, - local_copy: data_local/hf_archive/2026PaperModels_34091ebf}} # agents/embedspeed sped-up exact pipeline + baked numba cache; outputs bitwise = the Gradio build (12 live matrices) - farfield: {commit: e0695caed5075ed8df70ffb0933d8e51d6e3b4cd, date: 2026-10-20, rollback: fa7caa49ddd11421b04b44ee2d03fbf4ba632d90, - gate: deploy/tests/results/paper_space_gate_farfield_20261020.json, live: deploy/tests/results/paper_space_live_farfield_20261020.json} # stack 'corrected' = the corrected prior with substrate far field (agents/farfield/ADOPTION.md) - substrate: {commit: 37fe8236dca1a5a332a4097c5525f4f23e91b0f2, date: 2026-11-03, rollback: e0695caed5075ed8df70ffb0933d8e51d6e3b4cd, - gate: deploy/tests/results/paper_space_gate_substrate_20261103.json, live: deploy/tests/results/paper_space_live_substrate_20261103.json, - offstack: deploy/tests/results/paper_space_live_offstack_20261103.json} # calibrated substrate route (tl_squadds e60c67a): prior arms solve at the user's stack, learned-prior arms rescale + warn, solver-free refuses; rollback = the live farfield commit - prior_stacks: # process-wide prior settings (geomgnn.api.set_prior_stack), installed per request - corrected: &stack_corrected # since 2026-10-20: the corrected prior with substrate far field + compiled exact solver = the model's prior; also flagship_hub - title: "corrected prior with substrate far field" - version: v2m_sf_fc_dipfill_margin_slabfar # v2m + far pairs in different ground pockets: substrate (slab) dipole; same pocket: half-space dipole - patches: [priorv2m_sf] # VALUE-CHANGING: geomgnn/priorv2.py installed(policy='fc', dip=True, margin=True) + geomgnn/farfield.py arm 'b' - mode: exact_compiled - module_sha256: 1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c - farfield_sha256: 6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836 # scripts/farfield/farfield.py (agents/farfield), vendored verbatim - speed_package_sha256: 4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a - value_changing_approved: "user 2026-10-17 (v2m, gnn_models.GNN); user 2026-10-20: adopted arm (b) of agents/farfield (substrate dipole for far pairs in different ground pockets; pre-declared rule met, agents/farfield/RESULTS.md; adoption agents/farfield/ADOPTION.md)" - speed_approved: "user 2026-10-17 (gnn_models.GNN)" - previous: corrected_halfspace # the same stack with the half-space far field (before 2026-10-20); process-wide override: TLSQ_FAR_FIELD=halfspace - corrected_halfspace: # the corrected prior before 2026-10-20 (v2m, half-space dipole for every far pair), for reproduction; not served by any arm - title: "corrected prior (half-space far field, before 2026-10-20)" - version: v2m_fc_dipfill_margin - patches: [priorv2m] - mode: exact_compiled - module_sha256: 1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c - speed_package_sha256: 4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a - value_changing_approved: "user 2026-10-17 (gnn_models.GNN)" - speed_approved: "user 2026-10-17 (gnn_models.GNN)" - uncorrected: # prior v1, frozen solver (+ the value-preserving rejection-tail fix, bit-identical) - patches: [rejtail_fv] - version2: # prior version 2 (no window-margin widening), frozen solver: the prior of the 'retrained, version 2' ablation - patches: [priorv2] - module_sha256: 1a0bdcb71500c7f11e63238afe531c18caabd5c9f6f7aaa73d9b7dcd0ad61f8c - value_changing_approved: "paper ablation (SM tab:priorv2 'retrained, version 2'), served for reproduction only (paper Space, 2026-10-19)" - uncorrected_certified: # prior v1, certified solve (Rayleigh-Ritz windows with an error estimate) - patches: [] - mode: certified - speed_package_sha256: 4fff680f35cb8b098de6c9b1b6fc55780064362ffc829bb47bf69a77454ce38a - speed_approved: "VAL tie on all 13 families (agents/fastprior_pkg/RESULTS.md); paper tab:routes (d)" - -_paper_ckpt: - full_gnn: &ck_full_gnn - - {path: data_local/geomfast/runs/p2d_full_gnn_s0/model.pt, sha256: fcb5db5d8237436d546aca0e7463a2f1d4f2e1b18757b2a35eff646c03f3bc5c} - - {path: data_local/geomfast/runs/p2d_full_gnn_s1/model.pt, sha256: 9aef64adfaf99cad35da891a2329d43eac46b2768cd133b5313085891a4fed92} - - {path: data_local/geomfast/runs/p2d_full_gnn_s2/model.pt, sha256: 357c16539967404b0a7eea514ef3ff3dc763c764da192b219d919cb01f697669} - -paper_arms: - # ---------------- (d) good physics - model: - title: "The model: extrapolated physics on the corrected prior + residual networks + closure, compiled solver" - paper_name: "model (corrected prior, compiled solver)" - route: "(d) good physics" - kind: gnn - arm: full_gnn - stack: corrected - ppg: [1.5, 3.0] - checkpoints: *ck_full_gnn - summary: "C^R = R(1.5, 3) of the corrected prior (two thin-film solves) corrected by the 3-seed network ensemble (89,858 parameters per seed, bounded residual +-0.2 in log) with a learned row-sum closure: the complete Maxwell matrix. Trained on 35,354 Q3D layouts of 13 families." - paper: - tables: [tab:ladder-test, tab:routes (d), tab:sota, tab:cohorts, tab:grid, tab:circuit] - val: {median_pct: 0.229, mae_ff: 0.0674, rmse_ff: 0.0792} - test_infamily: {median_pct: 0.177, mae_ff: 0.0203, rmse_ff: 0.0250} - test_zeroshot: {median_pct: 0.587, mae_ff: 1.092, rmse_ff: 1.152} - heldout_family: {median_pct: 0.408, mae_ff: 0.049, rmse_ff: 0.059} - time: "0.845 / 5.96 s in family, 1.76 / 18.1 s zero-shot (test, x86, 2 CPUs); 1.16 / 6.3 s (GH200)" - certified: - title: "The same networks, certified variational solve (uncorrected prior)" - paper_name: "the same, engineered solves: certified variational solve" - route: "(d) good physics" - kind: gnn - arm: full_gnn - stack: uncorrected_certified - ppg: [1.5, 3.0] - checkpoints: *ck_full_gnn - summary: "The model's networks on the uncorrected prior solved with Rayleigh-Ritz windows that carry an error estimate; the paper's speed comparison of the solver modes, scored on the validation set against the exact solve of the same prior." - paper: - tables: [tab:routes (d), S-tab:package] - val: {median_pct: 0.3369, mae_ff: 0.0772, rmse_ff: 0.1018, note: "against 0.3369 % (0.0750 / 0.0997 fF) with the exact solve of the same prior: a tie on every family"} - time: "0.83 / 3.4 s (GH200, 2 CPU threads, 14 timing layouts) against 1.16 / 6.3 s compiled" - networks-uncorrected: - title: "Networks on the uncorrected prior" - paper_name: "networks on the uncorrected prior" - route: "(d) good physics" - kind: gnn - arm: full_gnn - stack: uncorrected - ppg: [1.5, 3.0] - checkpoints: *ck_full_gnn - summary: "The model's networks (same weights) on the uncorrected prior (frozen solver); identical to the model for N <= 9 conductors." - paper: - tables: [tab:ladder-test, S-tab:priorv2 (frozen, original)] - val: {median_pct: 0.337, mae_ff: 0.0750, rmse_ff: 0.0997} - test_infamily: {median_pct: 0.177, mae_ff: 0.0203, rmse_ff: 0.0250} - test_zeroshot: {median_pct: 0.593, mae_ff: 1.099, rmse_ff: 1.180} - time: "0.857 / 7.91 s in family, 1.89 / 41.5 s zero-shot (test)" - physics: - title: "Extrapolated physics C^R = R(1.5, 3), corrected prior (no learned parameter)" - paper_name: "extrapolated physics R(1.5,3), corrected prior" - route: "(d) good physics" - kind: physics - stack: corrected - levels: [1.5, 3.0] - self_note: "Richardson-extrapolated self terms of the thin-film solve (no network); the ground self term depends on the chip boundary" - summary: "2 log C(3) - log C(1.5) of the thin-film method of moments on the corrected prior, every entry; zero fitted parameters (the gap share alpha is TRAIN-fitted once)." - paper: - tables: [tab:ladder-test, tab:routes (d)] - val: {median_pct: 1.508, mae_ff: 0.291, rmse_ff: 0.337} - test_infamily: {median_pct: 1.559, mae_ff: 0.1703, rmse_ff: 0.2114} - test_zeroshot: {median_pct: 0.982, mae_ff: 1.050, rmse_ff: 1.128} - heldout_family: {median_pct: 1.554, mae_ff: 0.166, rmse_ff: 0.205} - time: "0.752 / 5.70 s in family, 1.39 / 15.0 s zero-shot (test)" - physics-uncorrected: - title: "Extrapolated physics R(1.5, 3), uncorrected prior" - paper_name: "extrapolated physics R(1.5,3), uncorrected prior" - route: "(d) good physics" - kind: physics - stack: uncorrected - levels: [1.5, 3.0] - self_note: "Richardson-extrapolated self terms of the thin-film solve (no network)" - summary: "The same extrapolation on the uncorrected prior (frozen solver)." - paper: - tables: [tab:ladder-test, S-tab:multifid] - val: {median_pct: 1.615, mae_ff: 0.2993, rmse_ff: 0.3574} - test_infamily: {median_pct: 1.559, mae_ff: 0.1703, rmse_ff: 0.2114} - test_zeroshot: {median_pct: 0.991, mae_ff: 1.057, rmse_ff: 1.157} - time: "0.767 / 7.71 s in family, 1.48 / 39.5 s zero-shot (test)" - single-3: - title: "Single solve, 3 panels per gap (corrected prior)" - paper_name: "single solve, 3 ppg" - route: "(d) good physics" - kind: physics - stack: corrected - levels: [3.0] - self_note: "self terms of the thin-film solve (no network)" - summary: "One thin-film solve at 3 panels per gap, no extrapolation." - paper: - tables: [tab:ladder-test] - test_infamily: {median_pct: 2.577, mae_ff: 0.2547, rmse_ff: 0.2991} - test_zeroshot: {median_pct: 1.755, mae_ff: 3.736, rmse_ff: 3.847} - time: "0.491 / 4.01 s in family, 0.94 / 10.4 s zero-shot (test)" - retrained-corrected: - title: "Networks retrained on the corrected prior" - paper_name: "retrained, corrected" - route: "(d) good physics" - kind: gnn - arm: full_gnn - stack: corrected - ppg: [1.5, 3.0] - checkpoints: - - {path: data_local/priorv2/hpc/runs/p2d_v2m_full_gnn_s0/model.pt, sha256: 04721d7e7f5c6faa7aea352fe1f9bb2261c5cc6835d169957bd3a1a8e61164dd} - - {path: data_local/priorv2/hpc/runs/p2d_v2m_full_gnn_s1/model.pt, sha256: f2352aa25536776e85daecd6681da697497ce9474c3a2391baeb66ec27ea89a5} - - {path: data_local/priorv2/hpc/runs/p2d_v2m_full_gnn_s2/model.pt, sha256: 4257ff6b4a16f69151d04514b71e922dd2b3a998f4ef550693365fd5415fcd8f} - summary: "The model's recipe retrained from scratch on the corrected prior (ablation; the paper keeps the frozen networks, which take the whole gain)." - paper: - tables: [S-tab:priorv2 (retrained, corrected)] - val: {median_pct: 0.218, mae_ff: 0.0774, rmse_ff: 0.0888} - retrained-version2: - title: "Networks retrained on prior version 2" - paper_name: "retrained, version 2" - route: "(d) good physics" - kind: gnn - arm: full_gnn - stack: version2 - ppg: [1.5, 3.0] - checkpoints: - - {path: data_local/priorv2/hpc/runs/p2d_v2_full_gnn_s0/model.pt, sha256: 0d436573e10a8d102ece6b58fb2a20d6b50e50f1feb653bc435229725f91c2b3} - - {path: data_local/priorv2/hpc/runs/p2d_v2_full_gnn_s1/model.pt, sha256: a22effd6b33a099bd4e633c188e1f428b626f4b51cbf660d68ab1c63d165a3f6} - - {path: data_local/priorv2/hpc/runs/p2d_v2_full_gnn_s2/model.pt, sha256: e6e93fd00d35836f5c18a960fef59e1cb450c9e52042bcd0fd531b892db9a518} - summary: "The model's recipe retrained on prior version 2 (the corrected prior without the window-margin widening; ablation)." - paper: - tables: [S-tab:priorv2 (retrained, version 2)] - val: {median_pct: 0.230, mae_ff: 0.0853, rmse_ff: 0.0997} - control-no-message-passing: - title: "Control: no message passing" - paper_name: "no-message-passing control" - route: "(d) good physics" - kind: gnn - arm: full_mlp - stack: uncorrected - ppg: [1.5, 3.0] - checkpoints: - - {path: data_local/geomfast/runs/p2d_full_mlp_s0/model.pt, sha256: 38be84e67ca58fe60d797f533e0fe7de355c7bf8e707d73268e19638677f94b6} - - {path: data_local/geomfast/runs/p2d_full_mlp_s1/model.pt, sha256: 37b2fefbac1c8191084464d56c3461687e945f8c76078cbbe3a690553a5ba757} - - {path: data_local/geomfast/runs/p2d_full_mlp_s2/model.pt, sha256: 7efe03578f314ae6516b3f6bd210e61caf25f77d57b05d06d3aef65e56747e9f} - summary: "The model's encoders and heads with no message-passing round (same data, loss, optimiser, seeds), on the uncorrected prior it was trained and scored on." - paper: - tables: [S-app:controls, S-fig:ladder-val] - val: {median_pct: 0.367, mae_ff: 0.084, rmse_ff: 0.109} - control-pair-only: - title: "Control: pair vector only" - paper_name: "pair-only control" - route: "(d) good physics" - kind: gnn - arm: pair_mlp - stack: uncorrected - ppg: [1.5, 3.0] - checkpoints: - - {path: data_local/geomfast/runs/p2d_pair_mlp_s0/model.pt, sha256: 67ee4de766ebdc20295534462929835437e3de437d08b54eb1d705d83d97915a} - - {path: data_local/geomfast/runs/p2d_pair_mlp_s1/model.pt, sha256: 2c84421056598c2d551e570f1e2e20ba55144b3c69cdbb9ee40d3170ab9ae4db} - - {path: data_local/geomfast/runs/p2d_pair_mlp_s2/model.pt, sha256: ddcd72c06be3b3cf6c5860cb4d57cba2e1c38888b6a497086381452382da46dc} - summary: "The no-message-passing control with the conductor vector reduced to the ground flag and the global vector removed: the matched ablation of the geometric embedding (uncorrected prior)." - paper: - tables: [S-app:controls, S-fig:ladder-val] - val: {median_pct: 0.417, mae_ff: 0.126, rmse_ff: 0.157} - prior-generation: - title: "Prior-generation model: extrapolated physics + per-kind offsets + bounded learned correction" - paper_name: "prior-generation model" - route: "baseline" - kind: final - final_model: E3 - trust_rule_applies: true - summary: "The baseline of every results table: R(1.5, 3) of the uncorrected prior (alpha 0.52), per-entry-kind offsets and a +-3 % network correction (747,266 parameters per seed), mutual entries only (self terms from row sums). Accepts other substrates (half-space factor). Its trust rule is on by default (box below)." - paper: - tables: [tab:ladder-test, S-tab:earlier-read, tab:sota] - test_infamily: {median_pct: 0.124, mae_ff: 0.0170, rmse_ff: 0.0211} - test_zeroshot: {median_pct: 0.959, mae_ff: 1.914, rmse_ff: 2.014} - time: "not timed in the test pass" - prior-generation-fast: - title: "Prior-generation model, fast mode: R(0.75, 1.5) + per-kind offsets (no network)" - paper_name: "prior-generation model, fast mode" - route: "baseline" - kind: final - final_model: E1 - summary: "The coarser Richardson pair of the uncorrected prior (alpha 0.52) plus the prior-generation model's per-kind offsets; no network." - paper: - tables: [Fig. sota (fast mode)] - note: "the paper shows it only in the k-curve of Fig. sota; the numbers under the model panel are the prior-generation evaluation (pooled over entries)" - # ---------------- (c) cheap physics - single-0.375: - title: "Single solve, 0.375 panels per gap (corrected prior)" - paper_name: "single solve, 0.375 ppg" - route: "(c) cheap physics" - kind: physics - stack: corrected - levels: [0.375] - self_note: "self terms of the thin-film solve (no network)" - summary: "One thin-film solve at 0.375 panels per gap." - paper: - tables: [tab:ladder-test] - test_infamily: {median_pct: 8.532, mae_ff: 0.7994, rmse_ff: 0.8871} - test_zeroshot: {median_pct: 7.578, mae_ff: 17.19, rmse_ff: 17.84} - time: "0.081 / 0.30 s in family, 0.11 / 0.73 s zero-shot (test)" - single-0.75: - title: "Single solve, 0.75 panels per gap (corrected prior)" - paper_name: "single solve, 0.75 ppg" - route: "(c) cheap physics" - kind: physics - stack: corrected - levels: [0.75] - self_note: "self terms of the thin-film solve (no network)" - summary: "One thin-film solve at 0.75 panels per gap." - paper: - tables: [tab:ladder-test] - test_infamily: {median_pct: 5.609, mae_ff: 0.5284, rmse_ff: 0.5918} - test_zeroshot: {median_pct: 4.777, mae_ff: 12.00, rmse_ff: 12.33} - time: "0.140 / 0.56 s in family, 0.21 / 1.93 s zero-shot (test)" - single-1.5: - title: "Single solve, 1.5 panels per gap (corrected prior)" - paper_name: "single solve, 1.5 ppg" - route: "(c) cheap physics" - kind: physics - stack: corrected - levels: [1.5] - self_note: "self terms of the thin-film solve (no network)" - summary: "One thin-film solve at 1.5 panels per gap." - paper: - tables: [tab:ladder-test] - test_infamily: {median_pct: 3.575, mae_ff: 0.3441, rmse_ff: 0.3928} - test_zeroshot: {median_pct: 2.871, mae_ff: 7.041, rmse_ff: 7.236} - time: "0.261 / 1.45 s in family, 0.42 / 4.81 s zero-shot (test)" - pair-0.375-0.75: - title: "Richardson pair R(0.375, 0.75) (corrected prior)" - paper_name: "R(0.375,0.75)" - route: "(c) cheap physics" - kind: physics - stack: corrected - levels: [0.375, 0.75] - self_note: "Richardson-extrapolated self terms of the thin-film solve (no network)" - summary: "2 log C(0.75) - log C(0.375): the cheapest Richardson pair." - paper: - tables: [tab:ladder-test, S-tab:multifid] - val: {median_pct: 2.773, mae_ff: 0.8157, rmse_ff: 0.8980, note: "validation on the uncorrected prior"} - test_infamily: {median_pct: 2.558, mae_ff: 0.2601, rmse_ff: 0.3125} - test_zeroshot: {median_pct: 3.740, mae_ff: 9.021, rmse_ff: 9.327} - time: "0.223 / 0.91 s in family, 0.32 / 2.79 s zero-shot (test)" - pair-0.75-1.5: - title: "Richardson pair R(0.75, 1.5) (corrected prior)" - paper_name: "R(0.75,1.5)" - route: "(c) cheap physics" - kind: physics - stack: corrected - levels: [0.75, 1.5] - self_note: "Richardson-extrapolated self terms of the thin-film solve (no network)" - summary: "2 log C(1.5) - log C(0.75): the coarser pair." - paper: - tables: [tab:ladder-test, S-tab:multifid] - val: {median_pct: 1.661, mae_ff: 0.4495, rmse_ff: 0.5077, note: "validation on the uncorrected prior"} - test_infamily: {median_pct: 1.508, mae_ff: 0.1663, rmse_ff: 0.2031} - test_zeroshot: {median_pct: 1.660, mae_ff: 2.450, rmse_ff: 2.575} - time: "0.403 / 2.05 s in family, 0.63 / 6.84 s zero-shot (test)" - cheap-2: - title: "Cheap-physics network, 2 levels (0.375, 0.75)" - paper_name: "cheap-physics network, 2 levels (0.375, 0.75)" - route: "(c) cheap physics" - kind: multifid - stack: corrected - levels: [0.375, 0.75] - checkpoints: - - {path: data_local/multifid/runs/L2_s0/model.pt, sha256: af43c30ac6fc2c34b12310b2dc1ccd91c6daf0342f1849f3601ff2659c6a8d1f} - - {path: data_local/multifid/runs/L2_s1/model.pt, sha256: 58d5815b8c8f3d170b04c89c26e86ca4586eae1b881c16fc8873c5bc8c01a45f} - - {path: data_local/multifid/runs/L2_s2/model.pt, sha256: a82145cb2ecc628db6c6c0328004a2c6a62d24c7aeb1d540ba20bdc23092e1fc} - summary: "Solves at 0.375 and 0.75 panels per gap and a residual network on their extrapolation (3 seeds; the variance head is not served)." - paper: - tables: [tab:ladder-test, tab:routes (c), S-tab:multifid] - val: {median_pct: 0.695, mae_ff: 0.1996, rmse_ff: 0.2397, note: "validation on the uncorrected prior"} - test_infamily: {median_pct: 0.480, mae_ff: 0.0510, rmse_ff: 0.0622} - test_zeroshot: {median_pct: 1.695, mae_ff: 2.591, rmse_ff: 2.779} - time: "0.308 / 1.13 s in family, 0.66 / 5.83 s zero-shot (test)" - cheap-3: - title: "Cheap-physics network, 3 levels (0.375, 0.75, 1.5)" - paper_name: "cheap-physics network, 3 levels (0.375, 0.75, 1.5)" - route: "(c) cheap physics" - kind: multifid - stack: corrected - levels: [0.375, 0.75, 1.5] - checkpoints: - - {path: data_local/multifid/runs/L3_s0/model.pt, sha256: 5aeb0c03f180ea3365ceadf9d30ea0eee559087e684cfc07d237cc2842084877} - - {path: data_local/multifid/runs/L3_s1/model.pt, sha256: e1bb3f6c09477bf434d1319d420ad0aa323f6239494bd29d740e650a3fb4fad0} - - {path: data_local/multifid/runs/L3_s2/model.pt, sha256: 100d0363aab3567324d0f42e6040161b132700148a56473e5d0de0446c83b9da} - summary: "Solves at 0.375, 0.75 and 1.5 panels per gap and a residual network (3 seeds; the variance head is not served)." - paper: - tables: [tab:ladder-test, tab:routes (c), S-tab:multifid] - val: {median_pct: 0.451, mae_ff: 0.1157, rmse_ff: 0.1445, note: "validation on the uncorrected prior"} - test_infamily: {median_pct: 0.275, mae_ff: 0.0307, rmse_ff: 0.0375} - test_zeroshot: {median_pct: 0.914, mae_ff: 1.711, rmse_ff: 1.795} - time: "0.575 / 2.63 s in family, 1.16 / 10.7 s zero-shot (test)" - cheap-2-exponent: - title: "Cheap-physics network, 2 levels, learned exponent" - paper_name: "2 levels, learned exponent" - route: "(c) cheap physics" - kind: multifid - stack: corrected - levels: [0.375, 0.75] - checkpoints: - - {path: data_local/multifid/runs/L2x_s0/model.pt, sha256: 48d83cdf96614f4bc3b2c9ae6d2765c1c985222ab7689e9d848737bc6200fe88} - - {path: data_local/multifid/runs/L2x_s1/model.pt, sha256: 718d4387fc42e79ef1c318c482496fa112b3985adf5be7546976dbf09cec6f5a} - - {path: data_local/multifid/runs/L2x_s2/model.pt, sha256: df0fe917bb6493ebdf41652006023375e75452a7bb18dff56409ca9b5bbc2319} - summary: "The 2-level network predicting a per-entry convergence exponent of the extrapolation instead of the fixed Richardson step." - paper: - tables: [S-tab:multifid] - val: {median_pct: 0.698, mae_ff: 0.2312, rmse_ff: 0.2683, note: "validation on the uncorrected prior; not test-scored"} - cheap-3-exponent: - title: "Cheap-physics network, 3 levels, learned exponent" - paper_name: "3 levels, learned exponent" - route: "(c) cheap physics" - kind: multifid - stack: corrected - levels: [0.375, 0.75, 1.5] - checkpoints: - - {path: data_local/multifid/runs/L3x_s0/model.pt, sha256: 9fa1d9814e7823eff1953337db9ee9a2752caf722fdfee817e28308056c705c9} - - {path: data_local/multifid/runs/L3x_s1/model.pt, sha256: 6a2485022c29af6494c69f344f7e49acf8cc422bd63d1e5d19de611a90aba6a1} - - {path: data_local/multifid/runs/L3x_s2/model.pt, sha256: d88cfaf5e988d85ed5e4408321c676eaf8bd39c8a50c4bcfa6240c3aebf34c4d} - summary: "The 3-level network predicting a per-entry convergence exponent." - paper: - tables: [S-tab:multifid] - val: {median_pct: 0.456, mae_ff: 0.1286, rmse_ff: 0.1573, note: "validation on the uncorrected prior; not test-scored"} - coarser-pair: - title: "The model's recipe on the coarser pair R(0.75, 1.5), retrained" - paper_name: "coarser pair + the model's recipe" - route: "(c) cheap physics" - kind: gnn - arm: full_gnn - stack: corrected - ppg: [0.75, 1.5] - checkpoints: - - {path: data_local/fastprior_p2/runs/p2_s0/model.pt, sha256: d9c01b20823a1c0b473949ad2b3f0977fc8c9f288b1d7737fb9e42f0ef2ee4ab} - - {path: data_local/fastprior_p2/runs/p2_s1/model.pt, sha256: 6dec390290f9d94af700bfd5e4e7e907a56c413d303d777b13eb9d2ce73e650c} - - {path: data_local/fastprior_p2/runs/p2_s2/model.pt, sha256: 0d43b0b5388e06fd49bf5c1b350e0aaa2a8a627d7b5d95972c0062affb1a24b0} - summary: "The model's networks retrained from scratch on R(0.75, 1.5) of the corrected prior: half the prior time; a trade-off point, never test-scored." - paper: - tables: [tab:routes (c), S-fig:ladder-val] - val: {median_pct: 0.343, mae_ff: 0.123, rmse_ff: 0.138, note: "against 0.229 % (0.067 / 0.079 fF) for the model; not test-scored (the physics pair alone: 1.508 % in family, 1.660 % zero-shot)"} - time: "prior 0.430 / 2.29 s against 0.809 / 6.61 s for the model's pair (x86, 2 CPUs, validation)" - # ---------------- (b) learned physics, (a) no physics - fast-model: - title: "The fast model: learned prior surrogate + the model's networks (families of its training data only)" - paper_name: "the fast model (learned prior surrogate + networks)" - route: "(b) learned physics" - kind: gnn - arm: full_gnn - stack: null - checkpoints: *ck_full_gnn - learned_prior: - name: surrogate_t100_norm - checkpoint: {path: data_local/learnedprior/runs/t100_norm/model.pt, sha256: 622fc374cc989bcc5569373787996169b8cde1254efdd118baa7252da0d788ce} - floor_ff: 1.7161304599611071e-09 # smallest positive prior mutual entry of the surrogate's training data (learnedprior/p2d_prepared TRAIN, both levels): the predicted priors are floored here before the networks' log (agents/embedspeed; grid_full underflowed to 0) - summary: "A learned surrogate (1.02M parameters, 385,593 generated layouts labelled by the prior alone + every family's training geometry) predicts the two priors; the model's networks correct them. No field solve." - warning: "Use the fast model only for the 13 component families of its training data (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated, synthetic campaign layouts). On a family held out of it, it is behind the physics it distils: 3.113 % (MAE 0.533 / RMSE 0.633 fF) against 1.554 % (0.166 / 0.205 fF). Use the model for a new component type." - paper: - tables: [tab:ladder-test, tab:routes (b), S-tab:sf-fast] - val: {median_pct: 0.846, mae_ff: 0.491, rmse_ff: 0.549} - test_infamily: {median_pct: 0.630, mae_ff: 0.1130, rmse_ff: 0.1414} - test_zeroshot: {median_pct: 3.576, mae_ff: 4.608, rmse_ff: 5.058, note: "families of its surrogate's training data"} - heldout_family: {median_pct: 3.113, mae_ff: 0.533, rmse_ff: 0.633} - time: "0.092 / 0.26 s in family, 0.30 / 2.47 s zero-shot (test); 0.122 / 0.471 s (GH200)" - solver-free: - title: "Solver-free network: the model's network with no prior, geometry only" - paper_name: "solver-free network" - route: "(a) no physics" - kind: gnn - arm: direct_gnn - stack: null - checkpoints: - - {path: data_local/geomfast/runs/p2d_direct_gnn_s0/model.pt, sha256: c3c0b8850d74984ebd6d1d42b63d9f8124bf9029627dda60e7aa0a1bdd9065c9} - - {path: data_local/geomfast/runs/p2d_direct_gnn_s1/model.pt, sha256: 3cc2e71de05e29a18212ad467c664d3219ff853c7522d45c1582b7af4185db25} - - {path: data_local/geomfast/runs/p2d_direct_gnn_s2/model.pt, sha256: 57bc28024fc6c5f0c5db424e313474cd64177b13fb9e3bc3d2044b1a01b8f691} - summary: "The model's network reading the geometric embedding only: base = training-median log mutual per pair kind, unbounded head." - warning: "No field solve: it interpolates in family and loses an order of magnitude outside it (zero-shot macro 17.29 %, MAE 8.934 / RMSE 9.972 fF). Use the model for any number you rely on." - paper: - tables: [tab:ladder-test, tab:routes (a), S-tab:multifid] - val: {median_pct: 1.486, mae_ff: 0.630, rmse_ff: 0.728} - test_infamily: {median_pct: 1.219, mae_ff: 0.1872, rmse_ff: 0.2290} - test_zeroshot: {median_pct: 17.29, mae_ff: 8.934, rmse_ff: 9.972} - time: "0.089 / 0.27 s in family, 0.30 / 2.48 s zero-shot (test); 0.124 s (GH200)" - -# ---------------------------------------------------------------- flagship Space (v4; user decisions 2026-10-19/20; deploy/GNN_SPACE.md "Flagship Space") -# Built by `python deploy/sync.py --flagship` (dry run) / `--flagship --push`; gated by deploy/tests/test_flagship_space.py. Three tiers, one -# selector, each the best recipe per speed level RETRAINED ON ALL ON-STACK DATA (45,771 Q3D layouts: TRAIN + VAL + every read test layout -# passing label QC; agents/flagship_v4/{PROTOCOL,RESULTS}.md). These models therefore have NO held-out score of their own: `reference` = the -# paper's held-out numbers for the same recipe (paper_v4; trained on 35,354 TRAIN layouts), `b5` = the one fresh check (campaign450 B5, 39 -# layouts of one generated family, N 3-4, never seen by any component; RESULTS.md section 5). Numbers: layout-mean median relative error % -# (MAE / RMSE fF) over mutual entries, 0.1 fF floor. Code path = the paper Space's (geomgnn.paper) through geomgnn.flagship.view. -flagship_hub: - public_link: SQuADDS/planar-capacitance # static Space, printed in the paper; opens the demo top-level (deploy/spaces/SQuADDS-planar-capacitance); never rename - deploy_20261114: # public-demo limits + short card (no paper model); Docker SYSTEM=spaces so HF OAuth works - commit: 142609ed7021861aea2be8ee5f51594b70e5918b # + text in the author's voice, Fast in the selector, Model not Tier, footer (was 4d44ef6) - live: deploy/tests/results/flagship_space_live_limits20261114.json # examples x tiers vs Mac <= 1.1e-3 rel; anon non-example refused; oauth_token call ran - deploy_20261115: # speed (phases A/B), outputs unchanged: concurrency groups, 2 threads, thickness floor 1 um, pinned deps (torch 2.14.1), background preload, slim bundle checkpoints, baked example results, prior-level cache - commit: f76c3bf6cfcd7c499049d7cc3d3ef0258d65a3e1 - rollback: {commit: 142609ed7021861aea2be8ee5f51594b70e5918b, local_copy: data_local/hf_archive/PlanarCapacitanceModel_142609ed} # 102 files - prior_level_cache_mb: 256 # TLSQ_PRIOR_LEVEL_CACHE_MB, set in the Space app.py - bake: "18 entries (6 examples x 3 tiers), warm.py bake step 62.9 s, peak RSS 2328 MB; loaded at start (interdigital recomputes bit for bit)" - gate: deploy/tests/results/flagship_space_gate_speed_20261115.json # + demo limits 11/11, examples 9/9, crop 8/8, substrate 3/3, flagship 6/6 - live: deploy/tests/results/flagship_space_live_speed_20261115.json # signed in (oauth_token): 12/12, examples bitwise = 2026-11-14 live, vs Mac <= 1.1e-3 rel (8.9e-3 fF) - offstack: deploy/tests/results/flagship_space_live_offstack_speed_20261115.json # bitwise = 2026-11-06 live - coldstart: {before: deploy/tests/results/flagship_space_coldstart_before_speed_20261115.json, after: deploy/tests/results/flagship_space_coldstart_speed_20261115.json} - deploy_20261116: # QCap rename (handoff/squadds_integration/RENAME_QCAP.md): QCap / QCap-Lite / QCap-Fast in the selector, results, /models ids, bake keys and API (model as text, any case); Space card with the new paper title; models and outputs unchanged - commit: 95e723d1f443ef0c758fbfab213248cbb799d0f0 - rollback: {commit: f76c3bf6cfcd7c499049d7cc3d3ef0258d65a3e1, local_copy: data_local/hf_archive/PlanarCapacitanceModel_f76c3bf6} - gate: deploy/tests/results/flagship_space_gate_qcap_20261116.json # demo limits 11/11, examples 9/9, crop 8/8, substrate 3/3, ground detection 10/10, flagship 6/6 - live: deploy/tests/results/flagship_space_live_qcap_20261116.json # signed in: 12/12, every matrix bitwise = 2026-11-15 live; bake loaded 18; aliases (qcap_fast) work, old names refused - offstack: deploy/tests/results/flagship_space_live_offstack_qcap_20261116.json # 6/6 matrices, routes bitwise = 2026-11-15; warnings equal apart from the names - deploy_20261116_launch: # public launch (author "go", 2026-11-16): About drops the private-preview sentence and the private-Space token comment; card title as confirmed by the author ("QCap: ... device layout"); models and outputs unchanged - commit: 6a50b4ce6b4ffb3bccbc446ea97d9992923d30de # Docker, cpu-basic, RUNNING 181 s after the upload - rollback: {commit: 95e723d1f443ef0c758fbfab213248cbb799d0f0, local_copy: data_local/hf_archive/PlanarCapacitanceModel_95e723d1} # 103 files - gate: deploy/tests/results/flagship_space_gate_launch_20261116.json # demo limits 11/11, examples 9/9, crop 8/8, substrate 3/3, ground detection 10/10, flagship 6/6 (B5 stored x86 worst 6.7e-7 / 5.6e-7 / 4.7e-6) - live: deploy/tests/results/flagship_space_live_launch_20261116.json # signed in (oauth_token): 12/12, every matrix bitwise = flagship_space_live_qcap_20261116.json; bake loaded 18; vs Mac <= 1.1e-3 rel (8.9e-3 fF) - anon: deploy/tests/results/flagship_space_live_launch_anon_20261116.json # no token: 4 examples answer, bitwise = the signed-in record; own upload refused with the sign-in message - deploy_20261116_logo: # QCap logo (handoff/squadds_integration/logo_qcap): compact QCap lockup beside the SQuADDS logo in the app header (title on its own line), QCap badge as the page icon (adaptive SVG link + 32 px PNG favicon_path); models and outputs unchanged - commit: ee162870236871d64b8e441158769ab7caae223f # Docker, cpu-basic, RUNNING 181 s after the upload - rollback: {commit: 6a50b4ce6b4ffb3bccbc446ea97d9992923d30de, local_copy: data_local/hf_archive/PlanarCapacitanceModel_6a50b4ce} # 103 files - gate: deploy/tests/results/flagship_space_gate_logo_20261116.json # demo limits 11/11, examples 9/9, crop 8/8, substrate 3/3, ground detection 10/10, flagship 6/6 (B5 stored x86 worst 6.7e-7 / 5.6e-7 / 4.7e-6) - live: deploy/tests/results/flagship_space_live_logo_20261116.json # signed in (oauth_token): 12/12, every matrix bitwise = flagship_space_live_launch_20261116.json; bake loaded 18; vs Mac <= 1.1e-3 rel (8.9e-3 fF) - anon: deploy/tests/results/flagship_space_live_logo_anon_20261116.json # no token: 4 examples answer, bitwise = the launch record; own upload refused with the sign-in message - deploy_20261116_logocard: # Space card only (handoff/hf_cards/body/PlanarCapacitanceModel.md): QCap horizontal lockup at the top (light / dark pair, HF dark:hidden classes), front matter thumbnail = assets/qcap_og.png (og:image checked); bundle adds assets/ (3 PNGs, sync.FLAGSHIP_ASSETS); app code and outputs unchanged - commit: 1f1a680dc2b0091d7effffa2a94fa8aa4b49de96 # Docker, cpu-basic, RUNNING 181 s after the upload - rollback: {commit: ee162870236871d64b8e441158769ab7caae223f, local_copy: data_local/hf_archive/PlanarCapacitanceModel_ee162870} - gate: deploy/tests/results/flagship_space_gate_logocard_20261116.json # demo limits 11/11, examples 9/9, crop 8/8, substrate 3/3, ground detection 10/10, flagship 6/6 (B5 stored x86 worst 6.7e-7 / 5.6e-7 / 4.7e-6) - live: deploy/tests/results/flagship_space_live_logocard_20261116.json # signed in: 12/12, every matrix bitwise = flagship_space_live_launch_20261116.json; bake loaded 18; vs Mac <= 1.1e-3 rel (8.9e-3 fF) - anon: deploy/tests/results/flagship_space_live_logocard_anon_20261116.json # no token: 4 examples bitwise = the launch record; own upload refused with the sign-in message - visibility_20261116: # flipped public with update_repo_settings(private=False), UTC; revision at the flip - SQuADDS/QCap: {utc: "2026-11-16T20:56:15Z", sha: e4087468129c641cde12f3ea8b2723998da305eb} - SQuADDS/SQuADDS_PlanarCapacitance: {utc: "2026-11-16T20:56:16Z", sha: 7ea40e91b1bc773ce74c2df6595809bd6f501a4d} # then 95a170d7 (MANIFEST.json without the internal repository name) - SQuADDS/SQuADDS_PlanarCapacitance-Synthetic: {utc: "2026-11-16T20:56:16Z", sha: 7319bc5d3f6bd9a5b597b1bc9f43c73022c50cb6} - shanto268/PlanarCapacitanceModel: {utc: "2026-11-16T20:56:17Z", sha: 6a50b4ce6b4ffb3bccbc446ea97d9992923d30de} - SQuADDS/planar-capacitance: {utc: "2026-11-16T20:56:18Z", sha: f905bdf1cc1558b0f13e24646214070bd17ec4ef} # static, opens https://shanto268-planarcapacitancemodel.hf.space top-level - still_private: [SQuADDS/PlanarCapacitance-paper, "SQuADDS/2026PaperModels-* (21 repos)", SQuADDS/SQuADDS_PlanarCapacitance-heldout, shanto268/SQuADDS-PlanarCapacitance-core] # checked after the flip (anonymous 401) - rollback: "update_repo_settings(repo_id, repo_type=..., private=True) per repo" - hf_cards_20261116_launch: # README-only (handoff/hf_cards/): QCap card drops "They go live there when the paper is published ..."; dataset card says the test labels are held out without naming the heldout repo; CHANGELOG / MANIFEST without internal repository names - SQuADDS/QCap: e4087468129c641cde12f3ea8b2723998da305eb # parent 3f5dbecd - SQuADDS/SQuADDS_PlanarCapacitance: 95a170d7d54ca48cd57dc4c187ab97799a75315c # 7ea40e91 (README + CHANGELOG, parent fb40d01a), then 95a170d7 (MANIFEST.json) - hf_cards_20261116_logo: # QCap logo on the Hugging Face pages (light / dark pair with HF's dark:hidden / hidden dark:block classes; verified rendered in both themes) - SQuADDS/QCap: {commit: b2217a5d431c2c89ce3e5c2a80c03d0aa76b1f35, rollback: e4087468129c641cde12f3ea8b2723998da305eb} # README (handoff/hf_cards/QCap.md): QCap horizontal lockup in place of the SQuADDS header image, "Part of SQuADDS" link; + assets/qcap_horizontal_{light,dark}.png - space: shanto268/PlanarCapacitanceModel # the URL is kept; its earlier v3 tiers are archived (archive below) - title: Planar Capacitance Model - private: false # public since 2026-11-16 20:56 UTC (author's launch "go"; visibility_20261116) - space_hardware: cpu-basic # free tier: 2 vCPU, 16 GB RAM - default_arm: accurate - max_conductors: 68 # signal conductors per layout: fewer than 70 with the ground (author 2026-11-14, geomgnn.access.MAX_NETS); the nine-qubit lattice has 66 + ground - paper_models: SQuADDS/PlanarCapacitance-paper # the paper's model (model repo); the paper Space is retired (paper_hub.retired) - checkpoints: data_local/flagship_v4/checkpoints.json # sha256 of every flagship checkpoint; sync.py refuses any other file - results: agents/flagship_v4/RESULTS.md - hf_cards_20261114: # README-only rewrite (re-pushed same day: /ml-paper/ link, then no links to the private paper model) (handoff/hf_cards/), private; package pins unchanged (manifest bb9d0ce / 5d4e094, dataset 13d46953) - SQuADDS/SQuADDS_PlanarCapacitance: c79953313874e9c116ca2f39a414d92025d18484 # physics_prior rename (24de414) + data/legacy_v1 removed - SQuADDS/SQuADDS_PlanarCapacitance-Synthetic: 3179ea7aed6f0ba92b549cc29aa645feea937513 - SQuADDS/SQuADDS_PlanarCapacitance-heldout: c538385b3e8d48f4183b68d00e376a06762b0705 - SQuADDS/PlanarCapacitance-flagship: a89f30850b638da1f693042b7d7cf14f20b19098 # + balanced/bal_v2m_sf_s{0,1,2}.pt (same sha256 as the Space) and SHA256SUMS - not_pushed: [SQuADDS/PlanarCapacitance-paper, shanto268/PlanarCapacitanceModel] # drafts in handoff/hf_cards/; author 2026-11-14: these stay private - model_repo: # rename 2026-11-16 (handoff/squadds_integration/RENAME_QCAP.md): flagship -> QCap; tier keys below stay internal - id: SQuADDS/QCap # was SQuADDS/PlanarCapacitance-flagship (old URL redirects) - folders_revision: 6dd46d33cd58788222dbf5478ca3550f2888f179 # accurate/ -> qcap/, balanced/ -> qcap-lite/, fast/ -> qcap-fast/; weights and sha256 unchanged - folders: {accurate: qcap/, balanced: qcap-lite/, fast: qcap-fast/} - names: {accurate: QCap, balanced: QCap-Lite, fast: QCap-Fast} # = flagship_tiers.*.paper_name; API ids qcap / qcap-fast (squadds_ml_api) - hf_cards_20261116: # README-only, QCap names (handoff/hf_cards/QCap.md, _links.md, _tiers.md); private repos stay private - SQuADDS/QCap: 25bdbb19ea3a17b2e86b08baea7b320e2d06d3a0 - SQuADDS/SQuADDS_PlanarCapacitance: e85ca683991bd3368f8c40d128ae2e7861760dbd - SQuADDS/SQuADDS_PlanarCapacitance-Synthetic: d0058e32c863eee28a2060e87203c58527882320 - SQuADDS/README: 007e7d48481eb78894d4f1a0beb2e54764325c4e # org card Space (public) - hf_cards_20261116_title_final: # README-only: title confirmed by the author (QCap: ... device layout); a revert in between (5b6ea8d7 / 84fa356b / 0ecc249c / dc03551a) is superseded - SQuADDS/QCap: 3f5dbecd53e54dcf4c6ee99c95e1b56ccda0d503 - SQuADDS/SQuADDS_PlanarCapacitance: fb40d01a135f8d58e97e103e080a2852eab1ff60 - SQuADDS/SQuADDS_PlanarCapacitance-Synthetic: 7319bc5d3f6bd9a5b597b1bc9f43c73022c50cb6 - SQuADDS/README: 4d2ce9a80422c49a5de2c2d63c0147b2dd9b0247 - hf_cards_20261116_title: # README-only: new paper title "QCap: a physics-corrected ... device layout" (package still pins QCap@25bdbb19; weights identical) - SQuADDS/QCap: bd51ff009a0680e2c715d330a6eb7c94c51260b7 - SQuADDS/SQuADDS_PlanarCapacitance: 854744a16ae34aa8f66e77768ece39f6c81a0edf - SQuADDS/SQuADDS_PlanarCapacitance-Synthetic: 77df19d3c3e5edfd10c9c7df563ccef755341b7a - SQuADDS/README: 63ce1252d671cbc7b0ab12289d9a7299bab0299f - training_layouts: 45771 - archive: - space: shanto268/PlanarCapacitanceModel - commit: 906bc45ae05ce9a1dac796a22c9aef481f079d40 # last commit of the earlier draft's v3 tiers (fast / coarse / fine, 2026-10-10); restore = push this revision - local_copy: data_local/hf_archive/PlanarCapacitanceModel_906bc45a # snapshot_download of that revision (79 files, 27 MB) - note: "the earlier draft's model repos (SQuADDS/2026PaperModels-*) are untouched; the old builder (sync.py without flags) skips this Space" - deployed: {commit: 8db73f7d1bcd7a5aeaf777dfd9f878afa054068a, date: 2026-10-20, gate: deploy/tests/results/flagship_space_gate_20261020.json, - live: deploy/tests/results/flagship_space_live_20261020.json} # 3 tiers, 80.7 MB bundle, RUNNING on cpu-basic, private (first push 79acb1d9, then the Space timings) - docker: {commit: e3e5a832e04ede8088bd91d7c0567cd68330ff51, first_push: c512e691e3117aea79062f89cc2aa1235a9706f0, date: 2026-10-20, sdk: docker, bundle: deploy/build_flagship_docker/PlanarCapacitanceModel, - live: deploy/tests/results/flagship_space_live_after_20261020.json, rollback: {commit: 8db73f7d1bcd7a5aeaf777dfd9f878afa054068a, sdk: gradio, - local_copy: data_local/hf_archive/PlanarCapacitanceModel_8db73f7d}} # agents/embedspeed: F64 embedding default (TLSQ_EMBEDDING_EXACT=1 = exact recipe) + baked numba cache - farfield: {commit: 6f16a03ab7d2f7a41e66261de3c98d5051960290, date: 2026-10-20, rollback: e3e5a832e04ede8088bd91d7c0567cd68330ff51, - gate: deploy/tests/results/flagship_space_gate_farfield_20261020.json, live: deploy/tests/results/flagship_space_live_farfield_20261020.json} # corrected prior with substrate far field + Accurate / Balanced retrained (agents/farfield/ADOPTION.md) - substrate: {commit: 4f5e6036f37b21cf9a24f6b5ad4762cbe1341809, date: 2026-11-03, rollback: 6f16a03ab7d2f7a41e66261de3c98d5051960290, - gate: deploy/tests/results/flagship_space_gate_substrate_20261103.json, live: deploy/tests/results/flagship_space_live_substrate_20261103.json, - offstack: deploy/tests/results/flagship_space_live_offstack_20261103.json} # calibrated substrate route (tl_squadds e60c67a; handoff/squadds_integration/reports/calibrated_substrate.md): Accurate solves the prior at the user's stack, Fast rescales + warns; rollback = the live farfield commit - ui: {commit: 334e8b524f6fb74d4cf56dd5f9718b594d525628, date: 2026-11-13, rollback: b749096deb5ae2d5a8af1dbb1927a8d182221844, source: tl_squadds 3dedf46, - live: deploy/tests/results/flagship_space_live_modelnames_20261113.json, offstack: deploy/tests/results/flagship_space_live_offstack_modelnames_20261113.json} # Fast warning quotes the measured off-stack errors and names the flagship model; physical-check text names models; models and numbers unchanged; rollback = the 2026-11-09 MetBrewer palette (live: flagship_space_live_palette_20261109.json) - prior_stacks: - corrected: *stack_corrected # the corrected prior with substrate far field + compiled exact solver (the same stack as the paper Space's model) - -flagship_tiers: - accurate: - title: "QCap (~1 s): the physics prior from two coarse solves, extrapolated and corrected by the networks" - paper_name: "QCap" # display name = the API name (case-insensitive; handoff/squadds_integration/RENAME_QCAP.md) - route: "QCap" - kind: gnn - arm: full_gnn - embedding: {far_k: 64, d_far_um: 100.0} # agents/embedspeed Part A (PROTOCOL.md amendment 2): far-sample decimation F64 of the pair vectors, the fastest arm tying the exact embedding on validation 4,608 and the 1q / 5q / 9q lattices; the paper Space keeps the exact embedding - stack: corrected - ppg: [1.5, 3.0] - checkpoints: - - {name: acc_v2m_sf_s0, path: data_local/flagship_v4/hpc/runs/acc_v2m_sf_s0/model.pt, sha256: cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5} # was acc_v2m_s0 56109a61 (half-space far field) - - {name: acc_v2m_sf_s1, path: data_local/flagship_v4/hpc/runs/acc_v2m_sf_s1/model.pt, sha256: 2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57} # was acc_v2m_s1 ae9c4be5 (half-space far field) - - {name: acc_v2m_sf_s2, path: data_local/flagship_v4/hpc/runs/acc_v2m_sf_s2/model.pt, sha256: d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed} # was acc_v2m_s2 0841acc6 (half-space far field) - summary: "Two thin-film method-of-moments solves at two mesh sizes, extrapolated, then corrected entry by entry by a graph neural network (three seeds, 89,858 parameters each, with a bounded correction) and a learned closure for the self terms. The output is the complete Maxwell matrix. Trained on all 45,771 of our Q3D designs." - own: # this release's own numbers; its networks saw every row scored here except B5 (data_local/farfield_adopt/insample.json, acc_v2m_sf ensemble) - insample: {set: "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", median_pct: 0.207, mae_ff: 0.0679, rmse_ff: 0.0770} - reference: - recipe: "the paper's version of this model (same architecture and prior stack at inference; its networks were trained on the 35,354 TRAIN layouts only, on the uncorrected prior; retrained on the corrected prior, as here, they score validation 0.218 % (0.0774 / 0.0888 fF)). These held-out numbers belong to the paper's version, not to this release, whose networks were retrained on every labelled design, the paper's test split included" - val: {median_pct: 0.229, mae_ff: 0.0674, rmse_ff: 0.0792} - test_infamily: {median_pct: 0.177, mae_ff: 0.0203, rmse_ff: 0.0250} - test_zeroshot: {median_pct: 0.587, mae_ff: 1.092, rmse_ff: 1.152} - heldout_family: {median_pct: 0.408, mae_ff: 0.049, rmse_ff: 0.059} - b5: {median_pct: 1.050, mae_ff: 0.132, rmse_ff: 0.188} # retrained 2026-10-20 (substrate far field); before 1.034 % (0.131 / 0.189 fF); B5 priors unchanged (N 3-4), seed-level network change - b5_physics: {name: "physics alone C^R = R(1.5, 3)", median_pct: 1.765, mae_ff: 0.275, rmse_ff: 0.376} - time_space: "interdigital 0.47 s, xmon 0.91 s, 1-qubit lattice (N 15) 19.0 s, 16-conductor layout 9.9 s, 9-qubit lattice (N 67) 154 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s)" - time_x86: "0.845 / 5.96 s in family, 1.75 / 18.1 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.99 s median (1.14 s on the 2026-10-20 re-run, Xeon E5-2640 v4)" - balanced: - title: "QCap-Lite (~0.5 s): the same recipe on two coarser solves" - paper_name: "QCap-Lite" - route: "QCap-Lite" - kind: gnn - arm: full_gnn - embedding: {far_k: 64, d_far_um: 100.0} # agents/embedspeed Part A (PROTOCOL.md amendment 2): far-sample decimation F64 of the pair vectors, the fastest arm tying the exact embedding on validation 4,608 and the 1q / 5q / 9q lattices; the paper Space keeps the exact embedding - stack: corrected - ppg: [0.75, 1.5] - checkpoints: - - {name: bal_v2m_sf_s0, path: data_local/flagship_v4/hpc/runs/bal_v2m_sf_s0/model.pt, sha256: aa742ab93b1e3ffcd86a753bda5cc4a68812acbe8140a6b0e311c11d1f36b4b2} # was bal_v2m_s0 50166723 (half-space far field) - - {name: bal_v2m_sf_s1, path: data_local/flagship_v4/hpc/runs/bal_v2m_sf_s1/model.pt, sha256: 486466473eba61c090f4e3fa7988bf880fc183570c5d02bd78f4c1356691f926} # was bal_v2m_s1 5d1f0ffb (half-space far field) - - {name: bal_v2m_sf_s2, path: data_local/flagship_v4/hpc/runs/bal_v2m_sf_s2/model.pt, sha256: 1b55ded04fd624585eeeccf2ab6e4a8e9354a9b96694131e1737dde43ad3ff58} # was bal_v2m_s2 dcd14c61 (half-space far field) - summary: "The QCap recipe on two coarser meshes, about half the solve time, with networks retrained for that pair on all 45,771 of our Q3D designs. About 2x faster than QCap at 1.5-1.7x its error." - own: # data_local/farfield_adopt/insample.json, bal_v2m_sf ensemble - insample: {set: "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", median_pct: 0.300, mae_ff: 0.0872, rmse_ff: 0.0999} - reference: - recipe: "the paper's version: the coarser pair + the model's recipe, trained on the 35,354 TRAIN layouts only (validation only, never test-scored). These numbers belong to the paper's version, not to this release" - val: {median_pct: 0.343, mae_ff: 0.123, rmse_ff: 0.138} - b5: {median_pct: 2.044, mae_ff: 0.258, rmse_ff: 0.348} # retrained 2026-10-20 (substrate far field); before 1.753 % (0.236 / 0.308 fF); B5 priors unchanged (N 3-4), within the earlier seed range 1.79-2.07 % - b5_physics: {name: "physics alone R(0.75, 1.5)", median_pct: 2.681, mae_ff: 0.396, rmse_ff: 0.583} - time_space: "interdigital 0.29 s, xmon 0.51 s, 1-qubit lattice (N 15) 7.7 s, 16-conductor layout 2.4 s, 9-qubit lattice (N 67) 54 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s)" - time_x86: "0.490 / 2.31 s in family, 1.00 / 10.0 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.56 s median" - fast: - title: "QCap-Fast (~0.1 s): a learned prior replaces the solves (trained component families only)" - paper_name: "QCap-Fast" - route: "QCap-Fast" - kind: gnn - arm: full_gnn - embedding: {far_k: 64, d_far_um: 100.0} # agents/embedspeed Part A (PROTOCOL.md amendment 2): far-sample decimation F64 of the pair vectors, the fastest arm tying the exact embedding on validation 4,608 and the 1q / 5q / 9q lattices; the paper Space keeps the exact embedding - stack: null - checkpoints: - - {name: acc_v1_s0, path: data_local/flagship_v4/hpc/runs/acc_v1_s0/model.pt, sha256: 9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba} - - {name: acc_v1_s1, path: data_local/flagship_v4/hpc/runs/acc_v1_s1/model.pt, sha256: f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe} - - {name: acc_v1_s2, path: data_local/flagship_v4/hpc/runs/acc_v1_s2/model.pt, sha256: 8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4} - learned_prior: - name: sall_all_s0 # surrogate seed 0 by declaration (PROTOCOL.md section 3, amendment A1) - checkpoint: {name: sall_all_s0, path: data_local/flagship_v4/hpc/sur/sall_all_s0/model.pt, sha256: 132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac} - summary: "A learned prior (1.02M parameters) predicts the two physics solves from the geometry, and the networks correct it. There is no field solve, so the time is the geometric embedding. The learned prior was trained on the physics prior of every Q3D design plus 432,697 generated layouts solved by the prior alone, and the networks on all 45,771 of our Q3D designs." - warning: "Use QCap-Fast only for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric and the generated layouts). On new designs of a trained family it was worse than the physics alone, 3.175 % (MAE 0.583 / RMSE 0.824 fF) against 1.765 % (0.275 / 0.376 fF). In the paper it was also worse than the physics alone on a component family held out of its training, 3.11 % (0.533 / 0.633 fF) against 1.55 % (0.166 / 0.205 fF). Use QCap for anything that matters." - own: # data_local/flagship_v4/scores/tables.json pooled.fast_sall_all_s0_ens (agents/flagship_v4/RESULTS.md section 2) - insample: {set: "in-sample, all 45,771 training layouts (TRAIN + VAL + the paper's test split; it was trained on them)", median_pct: 0.671, mae_ff: 0.353, rmse_ff: 0.395} - reference: - recipe: "the paper's version of the fast model (surrogate t100_norm trained on 385,593 generated layouts + the TRAIN geometry; networks trained on the 35,354 TRAIN layouts only). These held-out numbers belong to the paper's version, not to this release, which was trained on the paper's test split too" - val: {median_pct: 0.846, mae_ff: 0.491, rmse_ff: 0.549} - test_infamily: {median_pct: 0.630, mae_ff: 0.1130, rmse_ff: 0.1414} - test_zeroshot: {median_pct: 3.576, mae_ff: 4.608, rmse_ff: 5.058} - heldout_family: {median_pct: 3.113, mae_ff: 0.533, rmse_ff: 0.633} - heldout_family_physics: {median_pct: 1.554, mae_ff: 0.166, rmse_ff: 0.205} - val_same_surrogate: {median_pct: 0.722, mae_ff: 0.387, rmse_ff: 0.436, note: "this release's surrogate recipe trained without the validation layouts (P6 SUR-ALL) + the paper's TRAIN-only networks, held out (agents/surcov_p6/RESULTS_P6.md)"} - b5: {median_pct: 3.175, mae_ff: 0.583, rmse_ff: 0.824} - b5_physics: {name: "physics alone C^R = R(1.5, 3) (worse than the physics: QCap-Fast is behind it here)", median_pct: 1.765, mae_ff: 0.275, rmse_ff: 0.376} - time_space: "interdigital 0.036 s, xmon 0.11 s, 1-qubit lattice (N 15) 0.82 s, 16-conductor layout 0.49 s, 9-qubit lattice (N 67) 3.9 s (server time, one request, Docker build 2026-10-20; a repeated request is answered from the cache in ~0.01 s)" - time_x86: "0.091 / 0.274 s in family, 0.30 / 2.45 s zero-shot (median / p90; x86 cluster, 2 CPUs); B5 0.24 s median" - -squadds_ml_api: # unified SQuADDS ML inference API (handoff/squadds_ml_api/DESIGN.md, source deploy/squadds_ml_api/, build.py) - space: SQuADDS/squadds-ml-inference-api # free cpu-basic (created 2026-04-10, before HF's org paywall; a rebuild stays free, checked 2026-11-14) - deployed: 2026-11-16 - commit: 21f3f577d3385a721d2f5d02d706d17a86851bc3 # public launch (author "go" 2026-11-16): qcap / qcap-fast visibility public, card QCap section; squadds 25c5392 (squadds/ml = 0b3a12f); 59/59 local (tests adapted: hidden / gated checks on forced registries, public checks on the released one), --check resolves; live anonymous: /v1/health ok (squadds_commit 25c5392), legacy oracle 11/11, /v1/models lists qcap + qcap-fast, interdigital multipart predict qcap bitwise = examples/qcap.json, qcap-fast max 1.3e-5 fF (3.0e-6 rel, MAE 5.8e-6 / RMSE 8.6e-6 fF; example generated on arm64) (deploy/tests/results/squadds_ml_api_live_launch_20261116.json) - deploy_20261116: 8427cff1c825f4bd8e9350fb7934cb12511c0d68 # rollback of the launch deploy; squadds 7879eba (QCap rename): ids qcap / qcap-fast (hidden, 404 until launch), examples regenerated (matrices bitwise, revision 25bdbb19); 56/56 local, legacy oracle 11/11 live (deploy/tests/results/squadds_ml_api_live_qcap_20261116.json) - deploy_20261115: 8a0986e534f64165d2bbfe849412b05814f2f358 # rollback of the 2026-11-16 deploy; squadds ec4414d (lean/fast prior, bitwise), thread env 2 + torch threads, check_thickness; warm.py uses physics_prior (0dc991fe failed to build on the old name); 56/56 local, 11/11 legacy oracle live, capacitance models 404 - previous: a4f1ca1bfd6f0087baa0ab493d3ae04438671321 # 2026-11-14 deploy (a97aa742 + later commits), squadds 04ebd59 - rollback: legacy-olivia # tag on 01966faaa06432d425e06895f616db40e6cb858d (Olivia's single-model API); README-only test commit 7c985614 - models: {transmon_cross_hamiltonian_inverse: public, qcap: public, qcap-fast: public} # ids renamed 2026-11-16 (were planar_capacitance_flagship / _fast); qcap / qcap-fast public since the launch deploy 21f3f577 - collections: {models: SQuADDS/squadds-models-6af8b7da67a22df62af374c6, datasets: SQuADDS/squadds-datasets-6a65152b857f8efa5620880a} - gating: gated = HF token of a SQuADDS org member; needs Space secret HF_TOKEN (org read token) before the capacitance models go gated diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 4e49e57c590f0aaa0e83cc454d18efea14e36361..0000000000000000000000000000000000000000 --- a/requirements.txt +++ /dev/null @@ -1,15 +0,0 @@ ---extra-index-url https://download.pytorch.org/whl/cpu -torch==2.14.1 -numpy==2.5.3 -scipy==1.18.1 -shapely==2.1.2 -gdstk==1.0.1 -pandas==3.0.6 -pyyaml==6.0.3 -matplotlib==3.11.2 -huggingface_hub==2.2.0 -numba==0.68.0 -llvmlite==0.50.0 -threadpoolctl==3.7.0 -authlib==1.6.5 -itsdangerous==2.2.0 diff --git a/tlsq_infer/__init__.py b/tlsq_infer/__init__.py deleted file mode 100644 index 179a3e3e0e8c6f96934bab0f466e5e1599ae09a9..0000000000000000000000000000000000000000 --- a/tlsq_infer/__init__.py +++ /dev/null @@ -1,65 +0,0 @@ -"""tlsq_infer: zero-shot Maxwell capacitance matrices of planar superconducting layouts from a GDS file. - - from tlsq_infer import load_gds, prepare, predict - print(load_gds("chip.gds")) # layers / datatypes present - lay = prepare("chip.gds") # ground (1, 0), conductors (1, 10), full ground (training geometry) - res = predict(lay, model="pair-local", substrate="sapphire", thickness_um=430) - res["names"], res["matrix_fF"], res["expected_error"] - - from tlsq_infer.final import predict_final - res = predict_final(lay, "E3") # final recipes of the paper: "E3" (default), "E1", "C0", "E3-D" - -Threads: tlsq_infer.set_num_threads(n) (or the environment variable TLSQ_NUM_THREADS at import) sets torch, the BLAS -pools that threadpoolctl can reach (OpenBLAS / MKL; Apple Accelerate ignores it) and the mesh / assembly pool of the -MoM prior; the default is torch's thread count. -""" - -__version__ = "0.1.0" - -import os # noqa: E402 - -from .layout import LayoutError, PreparedLayout, load_gds, prepare # noqa: E402 -from .predict import PriorError, matrix_csv, predict # noqa: E402 -from .registry import load_registry # noqa: E402 - - -def available_cpus() -> int: - """CPUs this process may use: affinity mask and, in a container, the cgroup CPU quota.""" - n = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 1) - try: - q, p = open("/sys/fs/cgroup/cpu.max").read().split()[:2] - if q != "max": - n = min(n, max(1, int(q) // int(p))) - except (OSError, ValueError): - pass - return n - - -def set_num_threads(n: int | None = None) -> int: - """One knob for every thread pool of the pipeline (default: TLSQ_NUM_THREADS, else all available CPUs).""" - import torch - - from ._vendor import mom - - n = int(n or os.environ.get("TLSQ_NUM_THREADS") or available_cpus()) - torch.set_num_threads(n) - mom.NUM_THREADS = n - try: - from threadpoolctl import threadpool_limits - - threadpool_limits(n) - except ImportError: - pass - return n - - -if os.environ.get("TLSQ_NUM_THREADS"): - set_num_threads() - -if os.environ.get("TLSQ_REJTAIL_FV", "1") != "0": # value-preserving rejection-tail fix of the windowed prior (_vendor/rejtail_fv.py) - from ._vendor import rejtail_fv as _rejtail_fv - - _rejtail_fv.install() - -__all__ = ["LayoutError", "PreparedLayout", "PriorError", "available_cpus", "load_gds", "load_registry", "matrix_csv", "predict", "prepare", - "set_num_threads", "__version__"] diff --git a/tlsq_infer/_vendor/__init__.py b/tlsq_infer/_vendor/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/tlsq_infer/_vendor/blocks.py b/tlsq_infer/_vendor/blocks.py deleted file mode 100644 index cd82542abec9ebbee01c46bcd926c23355126ae7..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/blocks.py +++ /dev/null @@ -1,154 +0,0 @@ -"""Physics-agnostic geometry blocks: node (per conductor), edge (per conductor pair) and global features, all in -physical units (log µm, ratios) so that nothing is fitted to a dataset.""" - -from __future__ import annotations - -import numpy as np -import shapely -from scipy.special import ellipk -from scipy.spatial import cKDTree - -from .geometry import fourier_descriptors, sample_boundary, sample_boundary_fast, shape_metrics -from .mom import _nthreads -from .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, trees: dict | None = None) -> 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). trees: k-d - trees of bpts built once per conductor (sparse large-layout graphs; same numbers as building them per pair).""" - 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], trees[b] if trees is not None else 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, _ = (trees[b] if trees is not None else 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 - - -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, max_ground: int | None = None) -> tuple[dict, dict]: - """Boundary samples (STEP_UM) and widths per conductor; max_ground (sparse large-layout graphs): vectorised sampler - (`sample_boundary_fast`, the same points) and the ground samples subsampled evenly to at most this many points.""" - pts, widths = {}, {} - for i, c in enumerate(scene.conductors): - g = region(scene, i) - pts[i] = (sample_boundary_fast if max_ground else sample_boundary)(g, STEP_UM) - if max_ground and c.role == "ground" and len(pts[i]) > max_ground: - pts[i] = pts[i][:: int(np.ceil(len(pts[i]) / max_ground))] - widths[i] = np.inf if c.role == "ground" else 2 * g.area / g.length - return pts, widths diff --git a/tlsq_infer/_vendor/em.py b/tlsq_infer/_vendor/em.py deleted file mode 100644 index d980e90c960d07ae9d8ab1f7e714ce0dab28d81b..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/em.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Vendored logic of the final recipes (paper_v3: C0, E1, E3), copied from the training / scoring code without changes to -the arithmetic: scripts/e3_corr.py (KIND_ID, EDGE_KEYS, BOUND, N_PAD, _kind, _pack, make_model), scripts/em_matrix.py (item, -pack, apply_scale, predict), scripts/tm_final.py (logR) and scripts/metrics.py (entry_kind, KIND_XSET). The SceneGNN is the -vendored tlsq.uge.gnn class (same source). Parity: deploy/tests/test_final_parity.py.""" - -from __future__ import annotations - -import numpy as np - -KIND_ID = {"signal-signal": 1, "signal-ground": 2, "pad-ground": 3, "pad-other": 4} -EDGE_KEYS = (["is_ground_pair", "log_dmin_g"] + [f"sep_{k:02d}" for k in range(10)] + ["mom_0.5", "mom_1", "mom_2", "log_cps", - "share_mean", "share_absdiff"] + [f"lt_{k}{r}" for r in (50, 150, 400) for k in ("g", "o", "e")] + - ["lg_log_dmin_g"] + [f"lg_sep_{k:02d}" for k in range(10)] + ["lg_mom_0.5", "lg_mom_1", "lg_mom_2", "lg_log_cps", "mesh_step"]) -BOUND = 0.03 -N_PAD = 8 -KIND_XSET = {"signal-signal": "conductor-conductor", "pad-other": "conductor-conductor", "signal-ground": "conductor-ground", - "pad-ground": "conductor-ground"} - - -def entry_kind(a: str, b: str) -> str: - """Kind of the mutual entry between conductors named a and b ('P*' = pad, 'G' = ground) (metrics.entry_kind).""" - pad, gnd = a.startswith("P") or b.startswith("P"), "G" in (a, b) - return ("pad-ground" if gnd else "pad-other") if pad else ("signal-ground" if gnd else "signal-signal") - - -_kind = entry_kind # e3_corr._kind: the same rule - - -def logR(rlo, rhi): - """(log R, log MoM hi) of the mutual magnitudes: R = 2 log MoM(hi) - log MoM(lo) (tm_final.logR).""" - ml, mh = -np.asarray(rlo["proxy_matrix"], float), -np.asarray(rhi["proxy_matrix"], float) - with np.errstate(divide="ignore", invalid="ignore"): - return 2 * np.log(np.where(mh > 0, mh, np.nan)) - np.log(np.where(ml > 0, ml, np.nan)), np.log(np.where(mh > 0, mh, np.nan)) - - -def item(rlo, rhi, target=None): - """em_matrix.item (non-light): names, the two prior magnitudes, roles, pair tokens and the mesh gap of the finer row.""" - n = len(rhi["names"]) - tgt = np.ones((n, n)) if target is None else target - return {"names": list(rhi["names"]), "mlo": -np.asarray(rlo["proxy_matrix"], float), "mhi": -np.asarray(rhi["proxy_matrix"], float), - "target": -np.asarray(tgt, float), "roles": [nd["role_ground"] for nd in rhi["nodes"]], "edges": rhi["edges"], - "gap": rhi["global"]["proxy_min_gap_um"]} - - -def _pack(items, N): - """items: dicts with names, roles, edges {(i,j): token dict}, mlo, mhi (n x n magnitudes), target (n x n or None).""" - B, de = len(items), len(EDGE_KEYS) - X = np.zeros((B, N, 1), np.float32) - E = np.zeros((B, N, N, de), np.float32) - M = np.zeros((B, N), np.float32) - PR = np.zeros((B, N, N), np.float32) - Y = np.full((B, N, N), np.nan, np.float32) - K = np.zeros((B, N, N), np.int8) - A = np.zeros((B, N, N), np.float32) - for b, it in enumerate(items): - nm, n = it["names"], len(it["names"]) - M[b, :n] = 1 - X[b, :n, 0] = it["roles"] - g = np.log(max(it["gap"], 1e-6)) - for (i, j), f in it["edges"].items(): - v = [f["log_dmin"] - g if k == "log_dmin_g" else f["lg_log_dmin"] - g if k == "lg_log_dmin_g" else - np.log(it["mhi"][i, j]) - np.log(it["mlo"][i, j]) if k == "mesh_step" else f[k] for k in EDGE_KEYS] - E[b, i, j] = E[b, j, i] = np.nan_to_num(np.asarray(v, float)) - A[b, i, j] = A[b, j, i] = 1 - for i in range(n): - for j in range(n): - if i == j: - continue - PR[b, i, j] = 2 * np.log(it["mhi"][i, j]) - np.log(it["mlo"][i, j]) - K[b, i, j] = KIND_ID[_kind(nm[i], nm[j])] - if it["target"] is not None and it["target"][i, j] > 0: - Y[b, i, j] = np.log(it["target"][i, j]) - return X, E, M, PR, Y, K, A - - -def pack(items): - N = max(N_PAD, max(len(it["names"]) for it in items)) - X, E, M, PR, Y, K, A = _pack(items, N) - L = np.zeros((len(items), N, N), np.float32) - for b, it in enumerate(items): - n = len(it["names"]) - with np.errstate(divide="ignore", invalid="ignore"): - L[b, :n, :n] = np.log(np.where(it["mhi"] > 0, it["mhi"], np.nan)) - return dict(X=X, E=E, M=M, PR=PR, Y=Y, K=K, A=A, LMH=L) - - -def apply_scale(E, A, s): - return (np.clip((E - s["med"]) / s["iqr"], (s["lo"] - s["med"]) / s["iqr"], (s["hi"] - s["med"]) / s["iqr"]) * (A[..., None] > 0)).astype(np.float32) - - -def make_model(de): - """Bounded (+-BOUND) local correction on the base log B = log R + c_kind (e3_corr.make_model).""" - import torch.nn as nn - - from .gnn import SceneGNN - - class Bounded(nn.Module): - def __init__(self): - super().__init__() - self.net = SceneGNN(1, de, 1, 128, rounds=3) - - def forward(self, X, E, U, M, P, A=None): - import torch - raw = self.net(X, E, U, M, torch.zeros_like(P), A) # = edge head (off-diagonal) + node head (diagonal) - eye = torch.eye(M.shape[1], device=M.device)[None] - return P + BOUND * torch.tanh(raw) * (1 - eye) - - return Bounded() - - -def predict(model, d, idx, cvec, pre=""): - import torch - T = lambda x: torch.tensor(x, dtype=torch.float32) # noqa: E731 - P = d[pre + "PR"] + cvec[d[pre + "K"].astype(int)] * (d[pre + "K"] > 0) - out = [] - with torch.no_grad(): - for s0 in range(0, len(idx), 1024): - j = idx[s0:s0 + 1024] - out.append(model(T(d[pre + "X"][j]), T(d[pre + "E"][j]), torch.zeros((len(j), 1)), T(d[pre + "M"][j]), T(P[j]), T(d[pre + "A"][j])).numpy()) - return np.concatenate(out) diff --git a/tlsq_infer/_vendor/fastprior.py b/tlsq_infer/_vendor/fastprior.py deleted file mode 100644 index 9dadd84fcbaa92659d0b6c98b4f87309220313fd..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/fastprior.py +++ /dev/null @@ -1,695 +0,0 @@ -"""Vendored from tlsq.embed.fastprior (generated by scripts/vendor_fastprior.py; do not edit by hand): the -flagship-fast cheap priors of PRIOR_SCHEME.md Part III. `micro_mom`: the flagship mesh family at a fixed merged-panel -budget, one global window up to 8 conductors, core-graded windows beyond (pairs never co-windowed from the closed form); -`formula_prior`: closed-form edge-coupling prior (no mesh). Function sources identical to the training code.""" - -from __future__ import annotations - -import time -from concurrent.futures import ProcessPoolExecutor -from multiprocessing import get_context - -import numpy as np -import shapely -from scipy.spatial import cKDTree - -from . import mom as P -from .blocks import _kratio -from .geometry import sample_boundary - - -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 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) - - - -# formula constants: frozen 2026-10-09, not tuned on labels -FORMULA_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 form -FORMULA_SCREEN_UM = 1.0 # the screening factor is evaluated every FORMULA_SCREEN_UM of boundary and held in between -LITE_REFINE = 3 # rejected window solves: refine h by 2 up to this many times before majority-owned cells -LITE_LEVEL_GAPS = (10.0, 20.0, 40.0, 80.0) # windows of large layouts: finest panel within 10 gaps of the core, doubling beyond 10/20/40/80 -LITE_WINDOW_BUDGET = 2.0 # windows of large layouts: panel budget = this x the budget of the one-window (component) prior -LITE_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 - R = None - 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, R = False, None - 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 - if R is None: - raise RuntimeError(f"window solve failed: no positive-definite system after {refined} refinements (h={hh:.4g} um); " - "the window has no valid solution at this mesh") - 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, info diff --git a/tlsq_infer/_vendor/fastprior_loc.py b/tlsq_infer/_vendor/fastprior_loc.py deleted file mode 100644 index 72246beafb3078f9cb9f6d6f3d56a83372b3ea42..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/fastprior_loc.py +++ /dev/null @@ -1,199 +0,0 @@ -"""Vendored from tlsq.embed.fastprior_loc (copied verbatim except this header and `from . import mom as P`; checked by -deploy/tests/test_fastprior_loc.py). PRIOR_SCHEME.md section 19 Amendment MESH: local-gap graded lite prior.""" -from __future__ import annotations - -import time - -import numpy as np -import shapely - -from . import fastprior as F -from . import mom 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 - R = None - 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, R = False, None - 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 - if R is None: - raise RuntimeError(f"window solve failed: no positive-definite system after {refined} refinements (H={H:.4g} um)") - 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), info diff --git a/tlsq_infer/_vendor/geometry.py b/tlsq_infer/_vendor/geometry.py deleted file mode 100644 index 65444375772ceea17bfaf97cf8469add2627bf81..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/geometry.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Vendored from tlsq.geometry (shape metrics and boundary sampling used by the scene-graph features). Keep verbatim: -the trained networks depend on these exact features (deploy/tests/test_reproduction.py checks equality).""" - -from __future__ import annotations - -import numpy as np -import shapely -from shapely.geometry import Polygon - -BOUNDARY_STEP_UM = 0.25 -N_FOURIER = 16 -MIC_TOL = [0.01] # inscribed-circle tolerance (um); 0.1 for the approximate token variants (PRIOR_SCHEME.md 14.3.1) - - -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 sample_boundary_fast(geom, step: float = BOUNDARY_STEP_UM) -> np.ndarray: - """`sample_boundary` vectorised over all rings and points (numpy interpolation along the ring vertices instead of - one GEOS line_interpolate_point call per ring): the same points to float rounding (large layouts, sparse graphs).""" - rings = [] - for poly in getattr(geom, "geoms", [geom]): - rings += [poly.exterior, *poly.interiors] - xy = [np.asarray(r.coords) for r in rings] - seg = [np.sqrt(((c[1:] - c[:-1]) ** 2).sum(1)) for c in xy] - out = [] - for c, sl, r in zip(xy, seg, rings): - L = r.length - n = max(int(np.ceil(L / step)), 4) - s = np.linspace(0, L, n, endpoint=False) - cum = np.r_[0.0, np.cumsum(sl)] - k = np.clip(np.searchsorted(cum, s, side="right") - 1, 0, len(sl) - 1) - t = np.where(sl[k] > 0, (s - cum[k]) / np.where(sl[k] > 0, sl[k], 1.0), 0.0) - out.append(c[k] + t[:, None] * (c[k + 1] - c[k])) - return np.concatenate(out) - - -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] diff --git a/tlsq_infer/_vendor/gnn.py b/tlsq_infer/_vendor/gnn.py deleted file mode 100644 index 40341394b2e6457938af77c8fbde094e8f14dd68..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/gnn.py +++ /dev/null @@ -1,217 +0,0 @@ -"""Vendored from tlsq.uge.gnn (inference only): dense padded graph batches and the scene GNN.""" -from __future__ import annotations - -from dataclasses import dataclass -from itertools import combinations - -import numpy as np -import torch -import torch.nn as nn - -N_MAX = 8 -CLIP_MODES = ("iqr20", "iqr3", "envelope") -FEATURE_CLIP = {"mode": None} # evaluation override of the per-checkpoint clip (GRID_SCALING.md amendment 4); None = checkpoint's - - -def set_feature_clip(mode) -> None: - """None (each checkpoint's own: 'iqr20' for checkpoints without a 'features' spec), 'iqr20' (+-20 IQR, the released - models), 'iqr3' (+-3 IQR) or 'envelope' (the training range q0.1-q99.9 of each feature).""" - assert mode is None or mode in CLIP_MODES, mode - FEATURE_CLIP["mode"] = mode - - -N_LOCAL_UM = 200.0 -DERIVED_SCALE = {"prior_log_ppg": (float(np.log(3.0)), float(np.log(2.0))), "n_local": (1.0, 2.0)} # fixed (median, scale): one -# training resolution would give a near-zero IQR (single-ppg rows: IQR 3e-4, z down to -16,666) - - -def derive_features(row: dict) -> dict: - """Size- and window-invariant tokens (GRID_SCALING.md amendment 6): global prior_log_ppg = log(smallest gap / prior - finest panel), the prior's resolution; edge n_local = signal conductors (other than the pair) within N_LOCAL_UM of a - signal end of the pair (pair tokens' log_dmin). Returns a shallow copy of the row with the extra keys.""" - n = len(row["names"]) - dm = np.full((n, n), np.inf) - for (i, j), f in row["edges"].items(): - dm[i, j] = dm[j, i] = np.exp(f["log_dmin"]) - sig = np.array([nd["role_ground"] == 0 for nd in row["nodes"]]) - g = dict(row["global"]) - h = g.get("proxy_h_min_um") - gap = float(np.min(dm[np.isfinite(dm)])) if np.isfinite(dm).any() else 1.0 - if h and not g.get("proxy_min_gap_um"): # review W1: no sampled-dmin fallback (it was the B3 bug) - raise ValueError("row without proxy_min_gap_um: rebuild or backfill it (fix_hmin.py) before deriving the descriptor") - gap = g.get("proxy_min_gap_um") or gap - g["prior_log_ppg"] = float(np.log(max(gap, 1e-6) / h)) if h else 0.0 - near = (dm <= N_LOCAL_UM) & sig[None, :] - edges = {} - for (i, j), f in row["edges"].items(): - m = np.zeros(n, bool) - for e in (i, j): - if sig[e]: - m |= near[e] - m[[i, j]] = False - edges[(i, j)] = {**f, "n_local": float(m.sum())} - return {**row, "global": g, "edges": edges} - - -def scale_features(A, s, part: str, scaling: dict): - """(A - median) / IQR, clipped per FEATURE_CLIP or the checkpoint's scaling['features']['clip'].""" - z = np.nan_to_num((A - s[0]) / s[1]) - feats = scaling.get("features") or {} - mode = FEATURE_CLIP["mode"] or feats.get("clip", "iqr20") - if mode == "iqr3": - return np.clip(z, -3.0, 3.0) - if mode == "envelope": - lo, hi = (np.nan_to_num((np.asarray(b, float) - s[0]) / s[1]) for b in feats["envelope"][part]) - return np.clip(z, lo, hi) - return np.clip(z, -20.0, 20.0) - - -def _mlp(i, o, w): - return nn.Sequential(nn.Linear(i, w), nn.GELU(), nn.Linear(w, w), nn.GELU(), nn.Linear(w, o)) - - -@dataclass -class GraphSet: - X: np.ndarray # (B, N_MAX, dn) node features (scaled) - E: np.ndarray # (B, N_MAX, N_MAX, de) edge features (scaled, symmetric) - U: np.ndarray # (B, du) global features (scaled) - M: np.ndarray # (B, N_MAX) node mask - P: np.ndarray # (B, N_MAX, N_MAX) proxy log|C| (off-diagonal: log -C_ij, diagonal: log C_ii) - Y: np.ndarray # (B, N_MAX, N_MAX) target log|C| (NaN where absent) - ground: np.ndarray # (B, N_MAX) 1 for the ground node - A: np.ndarray | None = None # (B, N_MAX, N_MAX) 1 where the pair is a graph edge; None = every pair (dense graphs) - - def subset(self, idx): - return GraphSet(*(a[idx] for a in (self.X, self.E, self.U, self.M, self.P, self.Y, self.ground)), - None if self.A is None else self.A[idx]) - - def tensors(self, dev="cpu"): - return [torch.tensor(a, dtype=torch.float32, device=dev) for a in (self.X, self.E, self.U, self.M, self.P, self.Y, self.ground)] - - -def build_graphset(rows: list[dict], scaling: dict | None = None, proxy_key: str = "proxy_log_C", drop=(), - clip: str = "iqr20", derive: bool = False, local: bool = False) -> tuple[GraphSet, dict]: - """rows: scene-pass records. scaling (median/IQR per feature) is computed from rows when not given and returned, so it - can be frozen and shipped. proxy_key selects the edge proxy ('proxy_log_C' = MoM, 'conf_log_C' = conformal, None = none). - New scaling only: drop = feature names left out, clip = clip mode stored in scaling['features'] (with the training - envelope q0.1-q99.9 per feature). A given scaling fixes the features (its 'keys').""" - if derive or (scaling is not None and (scaling.get("features") or {}).get("derive")): - rows = [derive_features(r) for r in rows] - if scaling is not None: - nk, ek, gk = (list(k) for k in scaling["keys"]) - else: - nk = [k for k in rows[0]["nodes"][0] if not k.startswith("proxy_") and k not in drop] - ek = [k for k in next(iter(rows[0]["edges"].values())) if not (k.startswith("proxy_") or k.startswith("conf_")) and k not in drop - and (local or not k.startswith(("lt_", "lg_")))] # lt_*: local context tokens (localtok), only when asked for - gk = [k for k in rows[0]["global"] if not k.startswith("proxy_") and k not in drop] - B = len(rows) - N = max(N_MAX, max(len(r["names"]) for r in rows)) # pad to the largest layout; N_MAX is only a minimum - X = np.zeros((B, N, len(nk))) - E = np.zeros((B, N, N, len(ek))) - U = np.zeros((B, len(gk))) - M = np.zeros((B, N)) - G = np.zeros((B, N)) - P = np.zeros((B, N, N)) - Y = np.full((B, N, N), np.nan) - sparse = any(len(r["edges"]) < len(r["names"]) * (len(r["names"]) - 1) // 2 for r in rows) - A = np.zeros((B, N, N)) if sparse else None - for b, r in enumerate(rows): - n = len(r["names"]) - M[b, :n] = 1 - for i, nd in enumerate(r["nodes"]): - X[b, i] = [nd[k] for k in nk] - G[b, i] = nd["role_ground"] - P[b, i, i] = nd.get("proxy_log_Cself", 0.0) if proxy_key == "proxy_log_C" else 0.0 - for (i, j), f in r["edges"].items(): - E[b, i, j] = E[b, j, i] = [f[k] for k in ek] - if A is not None: - A[b, i, j] = A[b, j, i] = 1.0 - P[b, i, j] = P[b, j, i] = f.get(proxy_key, 0.0) if proxy_key else 0.0 - if proxy_key == "conf_log_C": # solver-free self term: sum of the conformal mutuals - for i in range(n): - P[b, i, i] = np.log(sum(np.exp(P[b, i, j]) for j in range(n) if j != i) + 1e-9) - U[b] = [r["global"][k] for k in gk] - T = r["target"] - for i in range(n): - Y[b, i, i] = np.log(max(T[i, i], 1e-9)) - for j in range(n): - if j != i: - Y[b, i, j] = np.log(max(-T[i, j], 1e-9)) - if scaling is None: - def stats(A, mask): - v = A[mask] - med = np.median(v, 0) - iqr = np.percentile(v, 75, 0) - np.percentile(v, 25, 0) - return med, np.where(iqr > 1e-9, iqr, 1.0) - def envelope(V, mask): - v = V[mask] - return np.percentile(v, 0.1, 0), np.percentile(v, 99.9, 0) - em = M[:, :, None] * M[:, None, :] * (1 - np.eye(N))[None] - if A is not None: - em = em * A - - def fixed(st, keys): - med, iqr = (np.array(x, float) for x in st) - for c, k in enumerate(keys): - if k in DERIVED_SCALE: - med[c], iqr[c] = DERIVED_SCALE[k] - return med, iqr - scaling = {"node": stats(X, M > 0), "edge": fixed(stats(E, em > 0), ek), "global": fixed(stats(U, np.ones(B, bool)), gk), "keys": (nk, ek, gk), - "features": {"drop": list(drop), "clip": clip, "derive": bool(derive), "local": bool(local), "envelope": {"node": envelope(X, M > 0), "edge": envelope(E, em > 0), - "global": envelope(U, np.ones(B, bool))}}} - sc = lambda V, p: scale_features(V, scaling[p], p, scaling) # noqa: E731 - return GraphSet(sc(X, "node") * M[..., None], sc(E, "edge"), sc(U, "global"), M, P, Y, G, A), scaling - - -class SceneGNN(nn.Module): - """gate=True: prediction = a * prior + head, with a learned per-entry trust a = sigmoid(.) in (0, 1) (starts near 1, - i.e. the plain residual model); lets the network discount a noisy prior instead of having to undo it.""" - - def __init__(self, dn, de, du, w=128, rounds=3, gate=False): - super().__init__() - self.enc_n, self.enc_e, self.enc_u = _mlp(dn, w, w), _mlp(de, w, w), _mlp(du, w, w) - self.msg = nn.ModuleList([_mlp(4 * w, w, w) for _ in range(rounds)]) - self.upd = nn.ModuleList([_mlp(3 * w, w, w) for _ in range(rounds)]) - self.head_e, self.head_n = _mlp(2 * w, 1, w), _mlp(2 * w, 1, w) - self.gate = gate - if gate: - self.gate_e, self.gate_n = _mlp(2 * w, 1, w), _mlp(2 * w, 1, w) - for g in (self.gate_e, self.gate_n): - nn.init.zeros_(g[-1].weight) - nn.init.constant_(g[-1].bias, 3.0) - - def forward(self, X, E, U, M, P, A=None): - mm = M[:, :, None] * M[:, None, :] * (1 - torch.eye(M.shape[1], device=M.device))[None] - if A is not None: # sparse graphs: pairs without an edge carry no message (their raw features are absent, not 0) - mm = mm * A - h, e, u = self.enc_n(X), self.enc_e(E), self.enc_u(U) - for msg, upd in zip(self.msg, self.upd): - hi, hj = h[:, :, None].expand_as(e), h[:, None, :].expand_as(e) - e = e + msg(torch.cat([e, hi + hj, (hi - hj).abs(), u[:, None, None].expand_as(e)], -1)) * mm[..., None] - agg = (e * mm[..., None]).sum(2) / mm.sum(2, keepdim=True).clamp(min=1) - h = h + upd(torch.cat([h, agg, u[:, None].expand_as(h)], -1)) * M[..., None] - out_e = self.head_e(torch.cat([e, u[:, None, None].expand_as(e)], -1))[..., 0] - out_e = 0.5 * (out_e + out_e.transpose(1, 2)) - out_n = self.head_n(torch.cat([h, u[:, None].expand_as(h)], -1))[..., 0] - eye = torch.eye(M.shape[1], device=M.device)[None] - if self.gate: - ze, zn = torch.cat([e, u[:, None, None].expand_as(e)], -1), torch.cat([h, u[:, None].expand_as(h)], -1) - ge = torch.sigmoid(self.gate_e(ze)[..., 0]) - ge = 0.5 * (ge + ge.transpose(1, 2)) - a = ge * (1 - eye) + torch.diag_embed(torch.sigmoid(self.gate_n(zn)[..., 0])) - self.last_gate = a - # P is log C; scale log C about a fixed reference (log 1 fF) so a < 1 shrinks the prior towards the head - P = a * P - return P + out_e * (1 - eye) + torch.diag_embed(out_n) - - -@torch.no_grad() -def predict(model, gs: GraphSet, idx, dev="cpu"): - sub = gs.subset(idx) - X, E, U, M, P, Y, G = sub.tensors(dev) - A = None if sub.A is None else torch.tensor(sub.A, dtype=torch.float32, device=dev) - out = [] - for s in range(0, len(X), 2048): - out.append(model(X[s:s + 2048], E[s:s + 2048], U[s:s + 2048], M[s:s + 2048], P[s:s + 2048], - None if A is None else A[s:s + 2048]).cpu().numpy()) - return np.concatenate(out) diff --git a/tlsq_infer/_vendor/graph.py b/tlsq_infer/_vendor/graph.py deleted file mode 100644 index df2706ea22a30439aa78712f4b47737409f6304d..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/graph.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Vendored from tlsq.uge.graph: scene graph (nodes = conductors, edges = all conductor pairs) with a precomputed -MoM prior injected (the deployment pipeline solves the MoM once and reuses its cell charges for the charge correction).""" - -from __future__ import annotations - -from itertools import combinations - -import numpy as np - -from .blocks import boundary_points, edge_features, global_features, node_features -from .scene import Scene - - -def prior_dict(C: np.ndarray, n_cells: int, h_min: float, edges, min_gap: float | None = None) -> dict: - """Same output as tlsq.uge.proxies.CapacitanceMoM.compute for a given Maxwell matrix C (min_gap: the prior mesh's - smallest conductor gap, recorded for the lite priors; the resolution descriptor = log(min_gap / h_min)).""" - n = C.shape[0] - out = {"node": {i: {"log_Cself": float(np.log(max(C[i, i], 1e-9)))} for i in range(n)}, "edge": {}, - "global": {"cells": float(n_cells), "h_min_um": float(h_min)}, "matrix": C} - if min_gap is not None: - out["global"]["min_gap_um"] = float(min_gap) - for (i, j) in edges: - out["edge"][(i, j)] = {"log_C": float(np.log(max(-C[i, j], 1e-9)))} - return out - - -MAX_GROUND_SAMPLES = 200_000 # sparse graphs: ground boundary samples kept (evenly subsampled) -_CTX: dict = {} # scene, samples and trees of the running sparse scene_graph, inherited by forked feature workers - - -def _workers(n: int) -> int: - from .mom import _prior_workers - return _prior_workers(n - 1) - - -def _feature_job(task): - from . import mom - mom.NUM_THREADS = 1 # one process per core: single-threaded k-d queries - c = _CTX - kind, items = task - if kind == "node": - return kind, [(i, node_features(c["scene"], i)) for i in items] - return kind, [((i, j), edge_features(c["scene"], i, j, c["bpts"], c["widths"], c["trees"])) for i, j in items] - - -def _parallel_features(scene, pairs, bpts, widths, trees, workers: int): - """node_features / edge_features of the sparse graph in `workers` forked processes; pairs are spread by cost - (boundary samples of both ends) so that the ground pairs do not land on one worker.""" - from concurrent.futures import ProcessPoolExecutor - from multiprocessing import get_context - - _CTX.clear() - _CTX.update(scene=scene, bpts=bpts, widths=widths, trees=trees) - cost = np.array([len(bpts[i]) + len(bpts[j]) for i, j in pairs], float) - order = np.argsort(-cost, kind="stable") - n_chunks = 8 * workers - chunks = [[pairs[k] for k in order[c::n_chunks]] for c in range(n_chunks)] - nchunks = [list(range(scene.n))[c::workers] for c in range(workers)] - tasks = [("node", c) for c in nchunks if c] + [("edge", c) for c in chunks if c] - nodes, edges = [None] * scene.n, {} - try: - with ProcessPoolExecutor(workers, mp_context=get_context("fork")) as ex: - for kind, res in ex.map(_feature_job, tasks): - for k, v in res: - if kind == "node": - nodes[k] = v - else: - edges[k] = v - finally: - _CTX.clear() - return nodes, {p: edges[p] for p in pairs} - - -def scene_graph(scene: Scene, prior_fn=None, edge_filter=None) -> dict: - """prior_fn(edges) -> CapacitanceMoM-style dict (see prior_dict), or None for the geometry-only network. - edge_filter(i, j) -> bool (large layouts, PRIOR_SCHEME.md Part III): only those pairs become edges (the O(N^2) pair - tokens are the cost on chips with hundreds of conductors); ground samples subsampled to MAX_GROUND_SAMPLES and one - k-d tree per conductor. None: every pair (the training graphs).""" - from scipy.spatial import cKDTree - - sparse = edge_filter is not None - bpts, widths = boundary_points(scene, MAX_GROUND_SAMPLES if sparse else None) - trees = {i: cKDTree(p) for i, p in bpts.items()} if sparse else None - pairs = [(i, j) for i, j in combinations(range(scene.n), 2) if not sparse or edge_filter(i, j)] - w = _workers(scene.n) if sparse else 1 - if w > 1: # large layouts: node and pair features on forked worker processes (same functions, same numbers) - nodes, edges = _parallel_features(scene, pairs, bpts, widths, trees, w) - else: - nodes = [node_features(scene, i) for i in range(scene.n)] - edges = {(i, j): edge_features(scene, i, j, bpts, widths, trees) for i, j in pairs} - # shielding: share of each endpoint's total geometric coupling carried by this edge - tot = np.zeros(scene.n) - for (i, j), f in edges.items(): - tot[i] += f["_cps"] - tot[j] += f["_cps"] - for (i, j), f in edges.items(): - 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 prior_fn is not None: - px = prior_fn(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(): - f.pop("_cps") - return g diff --git a/tlsq_infer/_vendor/mom.py b/tlsq_infer/_vendor/mom.py deleted file mode 100644 index 4a757df7553b6c080afe98b0fde237d74f3bfab5..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/mom.py +++ /dev/null @@ -1,1035 +0,0 @@ -"""Vendored from tlsq.embed.proxy: thin-film method-of-moments (MoM) capacitance on the exact polygons, adaptive -quadtree mesh, quasi-static half-space Green's function with eps_eff = (eps_r + 1) / 2. - -`mom_solve` is numerically the same solve as tlsq.embed.proxy.mom_capacitance_gds (standard: 8,000 cells, gap/3; -fine: 16,000 cells, gap/6) but keeps the cell charges of every excitation (reused by the charge correction) and builds -the dense interaction matrix in place to roughly halve peak memory.""" - -from __future__ import annotations - -import os -import queue -import threading -import time -from concurrent.futures import ThreadPoolExecutor -from functools import partial - -import numpy as np -import shapely -from scipy.linalg import cho_factor, cho_solve -from scipy.spatial import cKDTree - -EPS0_FF_PER_UM = 8.8541878128e-3 -MESH_INFO: dict = {} # last mesh: target h_min and smallest gap (reporting only; does not change any number) -SELF = 4 * np.log(1 + np.sqrt(2)) -STAGE_TIMES: dict = {} # seconds by stage (mesh, assemble, factor_solve) accumulated over the v3 solves since the last clear() -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 _tick(key: str, t0: float) -> None: - dt = time.perf_counter() - t0 - with _LOCK: - STAGE_TIMES[key] = STAGE_TIMES.get(key, 0.0) + dt - - -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 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 mesh(metals: list, max_cells: int = 8000, cells_per_gap: float = 3.0, grade: float = 2.0): - """Quadtree mesh exactly as mom_capacitance_gds: h_min = max(min gap / cells_per_gap, size / 4096), coarsened by - 1.5x until the mesh has at most max_cells cells. Returns centres, sides, owners, h_min.""" - 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))) - h_min = max(gap / cells_per_gap, size / 4096) - MESH_INFO.update(h_target=h_min, min_gap=gap) - while True: - 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 - - -def mom_solve(metals: list, eps_r: float = 11.45, max_cells: int = 8000, cells_per_gap: float = 3.0, grade: float = 2.0): - """Returns dict(C (n, n) Maxwell matrix in fF, cen, h, own, Q (cells, n) charges for every 1 V excitation, n_cells, h_min).""" - c, h, o, h_min = mesh(metals, max_cells, cells_per_gap, grade) - P = _assemble(c, np.stack([h, h], 1), SELF / h, eps_r, _near_quad) - B = (o[:, None] == np.arange(len(metals))[None, :]).astype(float) - Q = _chol_solve(P, B) - del P - C = np.stack([Q[o == a].sum(0) for a in range(len(metals))]) - info = _mesh_report(h_min, max_cells) - return {"C": 0.5 * (C + C.T), "cen": c, "h": h, "own": o, "Q": Q, "n_cells": len(c), "h_min": h_min, "mesh": info} - - -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: dict = {} -_IMG_GRID: dict = {} - - -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 not in _IMG_CACHE: - 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 = (w[None, :] / np.sqrt(u[:, None] ** 2 + D[None, :] ** 2)).sum(1) - _IMG_CACHE[key] = (du, T, w, D) - 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)) - 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 _mesh_report(h_min, max_cells, h_target=None, min_gap=None, **extra): - ht = MESH_INFO.get("h_target", h_min) if h_target is None else h_target - gap = MESH_INFO.get("min_gap", float("nan")) if min_gap is None else min_gap - return {"h_min_um": float(h_min), "h_min_target_um": float(ht), "min_gap_um": float(gap), "max_cells": int(max_cells), - "cells_per_min_gap": float(gap / h_min), "cap_hit": bool(h_min > ht * 1.0001), **extra} - - -# ---------------------------------------------------------------- v3 mesh (vendored from tlsq.embed.proxy, opt-in) -# Conductor-anchored lattice with exact edge panels (`anchored_cells`) and the panel solve; "v3-rich" adds Richardson -# extrapolation between gap/3 and gap/6. The v2 path above (`mesh`, `mom_solve`) is untouched. - -def anchored_cells(metals: list, h_f: float, grade: float = 2.0, majority: bool = False, limit: int | None = None): - """Same as tlsq.embed.proxy.anchored_cells. Returns centres (n, 2), panel sizes (n, 2), 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 rect_self(a, b): - 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 _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 _gap_size(metals: list): - bbox = shapely.union_all(metals).bounds - gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) - return gap, max(bbox[2] - bbox[0], bbox[3] - bbox[1]) - - -def _mesh_v3(metals: list, max_cells: int, cells_per_gap: float, grade: float = 2.0, gs=None): - gap, size = gs or _gap_size(metals) - h_min = max(gap / cells_per_gap, size / 4096) - MESH_INFO.update(h_target=h_min, min_gap=gap) - while True: - r = anchored_cells(metals, h_min, grade, limit=max_cells) - if r is not None: - return (*r, h_min) - h_min *= 2.0 - - -NONPD_FALLBACKS: list = [] # (n_cells, smallest pivot info) of solves that needed the exact near-field retry - - -def _solve_panels(c, wh, o, n_metals: int, eps_r: float): - """tlsq.embed.proxy.mom_solve (CPU path) for (width, height) panels; if the 3x3-quadrature system is not positive - definite, the solve is repeated with exact near-field entries (`_solve_panels_exact`). Solves that succeed are unchanged.""" - try: - return _solve_panels_quad(c, wh, o, n_metals, eps_r) - except np.linalg.LinAlgError as e: - NONPD_FALLBACKS.append((len(c), str(e))) - return _solve_panels_exact(c, wh, o, n_metals, eps_r) - - -def _solve_panels_exact(c, wh, o, n_metals: int, eps_r: float): - """Panel solve with the exact potential of a uniformly charged rectangle (`rect_potential`) for every near pair - (d < 1.5 max side) instead of the 3x3 point average; far pairs 1 / d and self terms as in the quadrature solve.""" - 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 _solve_panels_torch(c, wh, o, n_metals: int, eps_r: float, dev: str): - """Same assembly and Cholesky solve as `_solve_panels_quad`, in float64 torch on `dev` (tlsq.embed.proxy._mom_solve_torch).""" - import torch - - t0 = time.perf_counter() - t = lambda x: torch.as_tensor(np.ascontiguousarray(x), dtype=torch.float64, device=dev) # noqa: E731 - 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) - del sx, sy, r - P = 0.5 * (P + P.T) - P.diagonal().copy_(t(rect_self(wh[:, 0], wh[:, 1]))) - P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2 - B = t((o[:, None] == np.arange(n_metals)[None, :]).astype(float)) - if P.is_cuda: - torch.cuda.synchronize() - _tick("assemble", t0) - t0 = time.perf_counter() - 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") - Q = torch.cholesky_solve(B, L).cpu().numpy() - _tick("factor_solve", t0) - return Q - - -def _solve_panels_gpu(c, wh, o, n_metals: int, eps_r: float): - """Opt-in device solve (TLSQ_MOM_DEVICE=cuda): one of TLSQ_MOM_GPU_SLOTS slots (file locks shared by worker processes - on the node, default 3) must be free; None (solve on the CPU) when no slot is free or the device runs out of memory.""" - import fcntl - import tempfile - - import torch - - dev = os.environ["TLSQ_MOM_DEVICE"] - tag = os.environ.get("SLURM_JOB_ID", "local") - for k in range(int(os.environ.get("TLSQ_MOM_GPU_SLOTS", "3"))): - f = open(os.path.join(tempfile.gettempdir(), f"tlsq_infer_gpu_{tag}_{k}.lock"), "w") - try: - fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError: - f.close() - continue - try: - return _solve_panels_torch(c, wh, o, n_metals, eps_r, dev) - except RuntimeError as e: # includes torch.OutOfMemoryError - if "out of memory" not in str(e).lower(): - raise - return None - finally: - if dev.startswith("cuda"): - torch.cuda.empty_cache() - fcntl.flock(f, fcntl.LOCK_UN) - f.close() - return None - - -def _solve_panels_quad(c, wh, o, n_metals: int, eps_r: float): - """tlsq.embed.proxy.mom_solve (CPU path) for (width, height) panels: 3x3 point average for near pairs. With - TLSQ_MOM_DEVICE set (e.g. cuda) the same float64 assembly and Cholesky run in torch on that device (opt-in).""" - if os.environ.get("TLSQ_MOM_DEVICE") and SUBSTRATE["model"] == "halfspace": # the torch path has no image correction - Q = _solve_panels_gpu(c, wh, o, n_metals, eps_r) - if Q is not None: - return Q - t0 = time.perf_counter() - P = _assemble(c, wh, rect_self(wh[:, 0], wh[:, 1]), eps_r, _near_quad) - B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float) - _tick("assemble", t0) - t0 = time.perf_counter() - Q = _chol_solve(P, B) - _tick("factor_solve", t0) - return Q - - -LAST_V3: dict = {} # cells of the last single v3 solve (centres, panel sizes, owners, charges) for the v3 charge correction - - -def _cap_v3(metals, eps_r, max_cells, cells_per_gap, grade=2.0, gs=None): - t0 = time.perf_counter() - c, wh, o, h_min = _mesh_v3(metals, max_cells, cells_per_gap, grade, gs) - _tick("mesh", t0) - try: - Q = _solve_panels(c, wh, o, len(metals), eps_r) # 3x3 quadrature; exact near field if that is not positive definite - except np.linalg.LinAlgError as e: # coarse cut panels of different conductors overlap: whole finest cells by majority - NONPD_FALLBACKS.append((len(c), "majority cells: " + str(e))) - c, wh, o = anchored_cells(metals, h_min, grade, majority=True) - Q = _solve_panels_exact(c, wh, o, len(metals), eps_r) - C = np.stack([Q[o == a].sum(0) for a in range(len(metals))]) - cells = dict(cen=c, wh=wh, own=o, Q=Q) - LAST_V3.update(cells) - return 0.5 * (C + C.T), len(c), h_min, cells - - -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_solve_v3(metals: list, eps_r: float = 11.45, max_cells: int = 8000, cells_per_gap: float = 3.0, grade: float = 2.0, - rich: bool = False): - """v3 prior (tlsq.uge.proxies.CapacitanceMoM(mesh="v3" | "v3-rich")): dict(C, n_cells, h_min). No cell charges (the - charge correction always uses the v2 standard solve). rich: Richardson between gap/(2 cells_per_gap) with 2 max_cells - and gap/cells_per_gap with max_cells, as tlsq.embed.proxy.mom_capacitance_gds_rich.""" - gs = _gap_size(metals) - - def rep(h, cells, cpg, **extra): - return _mesh_report(h, cells, h_target=max(gs[0] / cpg, gs[1] / 4096), min_gap=gs[0], **extra) - - if not rich: - try: - C, n, h, cells = _cap_v3(metals, eps_r, max_cells, cells_per_gap, grade, gs) - return {"C": C, "n_cells": n, "h_min": h, "mesh": rep(h, max_cells, cells_per_gap), **cells} - except np.linalg.LinAlgError: # sliver edge panels can make the gap/3 system indefinite: gap/6 (as in training) - C, n, h, cells = _cap_v3(metals, eps_r, 2 * max_cells, 2 * cells_per_gap, grade, gs) - return {"C": C, "n_cells": n, "h_min": h, "mesh": {**rep(h, 2 * max_cells, 2 * cells_per_gap), - "note": "gap/3 system indefinite: solved at gap/6"}, **cells} - rf, rc = _both(partial(_cap_v3, metals, eps_r, 2 * max_cells, 2 * cells_per_gap, grade, gs), - partial(_cap_v3, metals, eps_r, max_cells, cells_per_gap, grade, gs)) - if isinstance(rf, np.linalg.LinAlgError): - if isinstance(rc, np.linalg.LinAlgError): - raise rc - Cc, nc, hc, _ = rc - return {"C": Cc, "n_cells": nc, "h_min": hc, "mesh": {**rep(hc, max_cells, cells_per_gap), "extrapolated": False, - "note": "fine mesh not positive definite: coarse solve only"}} - Cf, nf, hf, _ = rf - fine = rep(hf, 2 * max_cells, 2 * cells_per_gap) - if isinstance(rc, np.linalg.LinAlgError): - return {"C": Cf, "n_cells": nf, "h_min": hf, "mesh": {**fine, "extrapolated": False, - "note": "coarse mesh not positive definite: fine solve only"}} - Cc, nc, hc, _ = rc - r = hc / hf - C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1) - note = "" if r >= 1.01 else "cell cap forced both meshes to the same resolution: fine solve only, no extrapolation" - return {"C": C, "n_cells": nc + nf, "h_min": hf, "mesh": {**fine, "extrapolated": bool(r >= 1.01), "note": note}, - "C_coarse": Cc} # gap/3 solve: prior-convergence feature of the error model (tlsq_infer.errmodel) - - -_mom_solve_exact_near = _solve_panels_exact # name used by the flagship block below (verbatim copy of tlsq.embed.proxy) -# ---------------------------------------------------------------- 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, info - - -def mom_solve_flagship(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 250000, grade: float = 2.0, - rich: bool = True): - """Flagship prior (tlsq.embed.proxy.mom_capacitance_gds_flagship): dict(C, n_cells, h_min, mesh).""" - t0 = time.perf_counter() - C, n, h, info = mom_capacitance_gds_flagship(metals, eps_r, cells_per_gap, max_cells, grade, rich) - _tick("flagship", t0) - rep = _mesh_report(h, max_cells, h_target=info["h_target_um"], min_gap=info["min_gap_um"], raw_cells=info["raw_cells"], - extrapolated=info["extrapolated"], merged=True, solver="dense" if n <= DENSE_MAX else "H-matrix PCG") - rep["cap_hit"] = bool(info["cap_hit"]) - if rich: - rep["coarse_cells"] = int(info["coarse_cells"]) - return {"C": C, "n_cells": n, "h_min": h, "mesh": rep} - - -def _prior_workers(n_conductors: int) -> int: - """Worker processes for the windows / rows of the cheap priors on large layouts: TLSQ_PRIOR_WORKERS, else the - configured thread count; components (one window) never start a pool.""" - if n_conductors <= 8: - return 1 - return max(1, int(os.environ.get("TLSQ_PRIOR_WORKERS", 0)) or _nthreads()) - - -def mom_solve_lite(metals: list, eps_r: float = 11.45, max_cells: int = 1500, cells_per_gap: float = 3.0, workers: int | None = None): - """flagship-fast micro-MoM prior (tlsq.embed.fastprior.micro_mom; PRIOR_SCHEME.md Part III): dict(C, n_cells, h_min, - mesh, far_mask). The mesh report carries panels per gap but no `cells_per_min_gap`: the lite networks are trained on - priors at this resolution, so the 0.75-panels-per-gap regime flag of the v3 tiers does not apply.""" - from .fastprior import micro_mom - - t0 = time.perf_counter() - w = _prior_workers(len(metals) - 1) if workers is None else workers - C, far, info = micro_mom(metals[0], list(metals[1:]), eps_r, budget=max_cells, cells_per_gap=cells_per_gap, workers=w) - _tick("lite", t0) - for k in ("mesh_s", "assemble_s", "solve_s", "build_s", "formula_s"): - with _LOCK: - STAGE_TIMES[f"lite_{k}"] = STAGE_TIMES.get(f"lite_{k}", 0.0) + float(info[k]) - rep = {"prior": "lite", "h_min_um": float(min(info["h_um"])), "min_gap_um": float(info["min_gap_um"]), "max_cells": int(max_cells), - "panels_per_gap_min": float(min(info["panels_per_gap"])), "panels_per_gap_median": float(np.median(info["panels_per_gap"])), - "n_windows": int(info["n_windows"]), "panels": [int(x) for x in info["panels"]], "n_far_pairs": int(info["n_far_pairs"]), - "workers": int(w), "cap_hit": False, "merged": True, "solver": "dense (lite)"} - return {"C": C, "n_cells": int(sum(info["panels"])), "h_min": float(min(info["h_um"])), "mesh": rep, "far_mask": far} - - -def mom_solve_formula(metals: list, eps_r: float = 11.45, workers: int | None = None): - """flagship-fast closed-form prior (tlsq.embed.fastprior.formula_prior): dict(C, n_cells=0, h_min=smallest gap, mesh).""" - from .fastprior import formula_prior - - t0 = time.perf_counter() - w = _prior_workers(len(metals) - 1) if workers is None else workers - C, info = formula_prior(metals[0], list(metals[1:]), eps_r, workers=w) - _tick("formula", t0) - rep = {"prior": "formula", "min_gap_um": float(info["min_gap_um"]), "step_um": float(info["step_um"]), "samples": int(info["samples"]), - "n_bbox_pairs": int(info["n_bbox_pairs"]), "workers": int(w), "cap_hit": False, "solver": "closed form"} - return {"C": C, "n_cells": 0, "h_min": float(info["min_gap_um"]), "mesh": rep, "far_mask": np.zeros(C.shape, bool)} - - -def solve_prior(metals: list, mesh: str = "v2", substrate: str = "slab_open", **kw): - """Dispatch: mesh "v2" -> mom_solve (published priors, unchanged), "v3" / "v3-rich" -> mom_solve_v3, "flagship" -> - mom_solve_flagship (strip-merged Richardson, resolution-controlled), "lite" / "formula" -> the flagship-fast cheap - priors (mom_solve_lite / mom_solve_formula). substrate: the MoM Green's function (`SUBSTRATE`; the registry gives - "halfspace" for the priors the released models were trained on).""" - with globals()["substrate"](substrate): - return _solve_prior(metals, mesh, **kw) - - -def _solve_prior(metals: list, mesh: str = "v2", **kw): - if mesh == "v2": - return mom_solve(metals, **kw) - if mesh == "flagship": - return mom_solve_flagship(metals, **kw) - if mesh == "lite": - return mom_solve_lite(metals, **kw) - if mesh == "formula": - return mom_solve_formula(metals, **kw) - return mom_solve_v3(metals, rich=(mesh == "v3-rich"), **kw) diff --git a/tlsq_infer/_vendor/mom_loc.py b/tlsq_infer/_vendor/mom_loc.py deleted file mode 100644 index 856b42a26d049830cfbebc454689ebe45753b020..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/mom_loc.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Local-gap lite prior for inference (PRIOR_SCHEME.md section 19, Amendment MESH; training variants liteppg

_slab_loc). -Off the training path: nothing imports this module until the final-matrix code freeze hooks it into `mom.solve_prior` -(mesh "lite_loc") and `registry.PRIORS` (PRIORS_LOC below). Parity: deploy/tests/test_fastprior_loc.py.""" - -from __future__ import annotations - -import time - -import numpy as np - -from . import mom as M - -PRIORS_LOC = {f"liteppg{x:g}-slab-loc": dict(mesh="lite_loc", max_cells=10**9, cells_per_gap=x, substrate="slab_open") - for x in (0.375, 0.75, 1.5, 3.0)} - - -def mom_solve_lite_loc(metals: list, eps_r: float = 11.45, max_cells: int = 10**9, cells_per_gap: float = 3.0, workers: int | None = None): - """Layouts with a sliver pair (< 0.25 um) and <= 8 conductors: each cell meshed at clamp(local gap / ppg, size / 4096, - G_ref / ppg) (`fastprior_loc.micro_mom_loc`); every other layout: `mom.mom_solve_lite` unchanged. Same return dict - as mom_solve_lite; h_min = G_ref / ppg and mesh min_gap_um = G_ref (descriptor log ppg).""" - from .fastprior_loc import micro_mom_loc, ref_gap - - if len(metals) - 1 > 8 or ref_gap(metals)[3] == 0: - out = M.mom_solve_lite(metals, eps_r, max_cells, cells_per_gap, workers) - out["mesh"]["local"] = False - return out - t0 = time.perf_counter() - C, far, info = micro_mom_loc(metals[0], list(metals[1:]), eps_r, ppg=cells_per_gap) - M._tick("lite", t0) - for k in ("mesh_s", "solve_s"): - with M._LOCK: - M.STAGE_TIMES[f"lite_{k}"] = M.STAGE_TIMES.get(f"lite_{k}", 0.0) + float(info[k]) - rep = {"prior": "lite_loc", "local": True, "h_min_um": float(info["H_um"]), "min_gap_um": float(info["G_ref_um"]), - "gmin_um": float(info["gmin_um"]), "h_floor_um": float(info["h_floor_um"]), "max_cells": int(max_cells), - "panels_per_gap_min": float(min(info["panels_per_gap"])), "panels_per_gap_median": float(np.median(info["panels_per_gap"])), - "n_windows": 1, "panels": [int(x) for x in info["panels"]], "n_far_pairs": 0, "workers": 1, "cap_hit": False, - "merged": True, "solver": "dense (lite, local mesh)"} - return {"C": C, "n_cells": int(sum(info["panels"])), "h_min": float(info["H_um"]), "mesh": rep, "far_mask": far} - - -def solve_prior_loc(metals: list, mesh: str = "lite_loc", substrate: str = "slab_open", **kw): - """`mom.solve_prior` for mesh "lite_loc" (until the hook-up); any other mesh is passed to mom.solve_prior.""" - if mesh != "lite_loc": - return M.solve_prior(metals, mesh, substrate, **kw) - with M.substrate(substrate): - return mom_solve_lite_loc(metals, **kw) diff --git a/tlsq_infer/_vendor/rejtail_fv.py b/tlsq_infer/_vendor/rejtail_fv.py deleted file mode 100644 index a3f90bc45a8f46600fb8c3675505909c7d5b7b32..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/rejtail_fv.py +++ /dev/null @@ -1,115 +0,0 @@ -"""rejtail fix fv (agents/rejtail/RESULTS.md, scripts/rejtail/rt.py; user approval 2026-10-17): value-preserving removal of -the rejection tail of the windowed micro-MoM prior (`fastprior._window_solve`, all_rhs=False, layouts with > 8 conductors). - -A window attempt whose mesh leaves a metal without a panel is always rejected, whatever its solve returns. The frozen code -still solves it, and above DENSE_MAX panels the H-matrix PCG cannot converge: the panel-less metal has a zero right-hand -side, so the residual is 0/0 = NaN, and it runs 1,000 iterations before raising. fv meshes such attempts but does not -solve them. If the loop ends without an accepted attempt, the result the unpatched code returns is rebuilt by solving -the deferred dense attempts lazily: - keep_last_solved=True (frozen geomfast stage): the latest attempt whose solve succeeded, newest first; - keep_last_solved=False (tlsq_infer vendor): the last attempt's own solve, else the same RuntimeError. -Every accepted solve is the same call on the same mesh, so the result is bit-identical (621 layouts in RESULTS.md; -deploy/tests/test_gnn_space.py re-checks it). all_rhs=True calls (single window, N <= 8) run the original function. -The same file is shipped as geomgnn/rejtail_fv.py and tlsq_infer/_vendor/rejtail_fv.py; only the import line differs. -""" -from __future__ import annotations - -import time - -import numpy as np - -from . import fastprior as F -from . import mom as P - -KEEP_LAST_SOLVED = False -_ORIG = {} - - -def _solve(c, wh, o, metals, cols, eps_r): - """One attempt solved exactly as the original loop does (windowed: LDL^T dense, H-matrix PCG above DENSE_MAX). - Returns (R, assemble seconds).""" - 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 window_solve(metals: list, n_core: int, h: float, budget: float, eps_r: float, all_rhs: bool, levels: tuple = ()) -> tuple: - 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 = [] # per attempt, oldest first: ("R", R) | ("err",) | ("mesh", c, wh, o) deferred dense | ("doomed",) deferred H-matrix - 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) > P.DENSE_MAX else ("mesh", c, wh, o)) - ok = False - else: - t = time.perf_counter() - try: - R, ta = _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 KEEP_LAST_SOLVED else hist[-1:]): - 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)[0] - break - except np.linalg.LinAlgError: - continue - t_sol += time.perf_counter() - t - if R is None: - raise RuntimeError(f"window solve failed: no positive-definite system after {refined} refinements (h={hh:.4g} um); " - "the window has no valid solution at this mesh") - 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 install() -> None: - """Replace fastprior._window_solve (a module global, looked up at call time, also in the forked window workers).""" - if not _ORIG: - _ORIG["window_solve"] = F._window_solve - F._window_solve = window_solve - - -def uninstall() -> None: - if _ORIG: - F._window_solve = _ORIG.pop("window_solve") - - -def installed() -> bool: - return bool(_ORIG) diff --git a/tlsq_infer/_vendor/scene.py b/tlsq_infer/_vendor/scene.py deleted file mode 100644 index 57acc670f53bb742cc0232d8974bb2d1593974de..0000000000000000000000000000000000000000 --- a/tlsq_infer/_vendor/scene.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Vendored from tlsq.uge.scene: the scene container (ground net at index 0 + signal bodies) and the training stack.""" - -from __future__ import annotations - -from dataclasses import dataclass, field - -import shapely -from shapely.geometry import Polygon - -DEFAULT_STACK = {"n_metal_layers": 1, "metal_thickness_um": 0.25, "substrate_thickness_um": 350.0, "substrate_eps_r": 11.45} - - -@dataclass -class Conductor: - name: str - role: str # "ground" | "signal" - geom: object # shapely (Multi)Polygon, µm - - -@dataclass -class Scene: - conductors: list[Conductor] # index 0 is the ground net - chip: Polygon - pocket: object # chip minus ground metal - stack: dict = field(default_factory=lambda: dict(DEFAULT_STACK)) - - @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 make_scene(ground, signals: list, names: list[str]) -> Scene: - """Same construction as tlsq.uge.scene.scene_from_gds, from already-extracted geometry.""" - chip = shapely.box(*ground.bounds) - conds = [Conductor("G", "ground", ground)] + [Conductor(n, "signal", g) for n, g in zip(names, signals)] - return Scene(conds, chip, chip.difference(ground), dict(DEFAULT_STACK)) diff --git a/tlsq_infer/app_ui.py b/tlsq_infer/app_ui.py deleted file mode 100644 index b7e657b05b4f5bed398413131115099debce2661..0000000000000000000000000000000000000000 --- a/tlsq_infer/app_ui.py +++ /dev/null @@ -1,445 +0,0 @@ -"""Gradio front end shared by the two Spaces (flagship single-model app and the paper-models app). Needs `gradio`. - -API endpoints (gradio_client, api_name): - /inspect (gds file) -> layer table (JSON rows) - /prepare (gds, layers table, margin, ...) -> preview, warnings, summary, simplified GDS - /predict (gds, layers table, margin, ..., substrate) -> matrix table, CSV, JSON, report - /predict_gds (gds, ground "1/0", conductor "1/10", margin_gaps (0 auto, <0 no crop), substrate, eps, thickness_um, model, - self_from_rows); model = "fast" (default, flagship-fast) / "coarse" / "fine" (alias "accurate") or an explicit registry name - -> result dict (one call, for scripts; see examples/client.py) -""" - -from __future__ import annotations - -import json -import os -import tempfile -import threading -import time -from pathlib import Path - -import numpy as np - -from . import __version__ -from . import layout as L -from .layout import LayoutError, load_gds, prepare, read_polygons -from .predict import intervals_csv, matrix_csv, predict -from .registry import load_registry - -LIMITS = {"max_file_mb": float(os.environ.get("TLSQ_MAX_FILE_MB", 25)), "max_polygons": int(os.environ.get("TLSQ_MAX_POLYGONS", 200_000)), - "max_conductors": int(os.environ.get("TLSQ_MAX_CONDUCTORS", 1000)), - "max_conductors_heavy": int(os.environ.get("TLSQ_MAX_CONDUCTORS_HEAVY", 30))} # coarse / fine tiers (MoM cost); fast tier up to max_conductors -CUSTOM = "custom eps_r" -# flagship-prior solves (fine tier, and coarse-tier layouts routed to it) can take tens of seconds and several GB on large -# layouts: at most TLSQ_HEAVY_CONCURRENCY of them at once; other requests are not blocked -HEAVY = threading.BoundedSemaphore(int(os.environ.get("TLSQ_HEAVY_CONCURRENCY", 1))) - - -def _predict(lay, model, **kw): - from .predict import large_layout_model, resolve_model, would_hit_cap - - reg = load_registry() - name = resolve_model(reg, model or None) - prior = str(reg.model(name).get("prior", "")) - if prior not in ("lite500", "lite1500", "formula") and lay.n_conductors > LIMITS["max_conductors_heavy"]: - raise LayoutError(f"{lay.n_conductors} conductors: the coarse and fine tiers are capped at {LIMITS['max_conductors_heavy']} on " - "this server (their physics prior grows with the chip); use the fast tier (default), which handles " - "multi-qubit chips") - heavy = prior.startswith("flagship") - if not heavy and large_layout_model(reg, name): - heavy = would_hit_cap([lay.ground] + list(lay.conductors), prior)[0] - if not heavy: - return predict(lay, model=model or None, **kw) - with HEAVY: - return predict(lay, model=model or None, **kw) -LAYER_COLS = ["layer", "datatype", "role", "n_polygons", "area_um2", "bbox_um"] - - -def _path(f): - if f is None: - raise LayoutError("upload a GDS file first") - p = f if isinstance(f, str) else getattr(f, "name", None) or f.get("path") - if os.path.getsize(p) > LIMITS["max_file_mb"] * 1e6: - raise LayoutError(f"file larger than {LIMITS['max_file_mb']:g} MB: crop the layout to the region of interest") - return p - - -def _roles(table) -> tuple[list, list, list]: - """(ground, conductor, ignore) layer lists from the editable layer table (list of rows or a DataFrame).""" - if table is None: - return [(1, 0)], [(1, 10)], [] - rows = table.to_dict("records") if hasattr(table, "to_dict") else [dict(zip(LAYER_COLS, r)) if isinstance(r, (list, tuple)) else r for r in table] - g, c, i = [], [], [] - for r in rows: - try: - key = (int(float(r["layer"])), int(float(r["datatype"]))) - except (TypeError, ValueError, KeyError): - continue - role = str(r.get("role", "ignore")).strip().lower() - if "+" in role or role.startswith("b"): # ground+conductor / both: one layer holds both, the ground is detected - g.append(key) - c.append(key) - continue - (g if role.startswith("g") else c if role.startswith("c") else i).append(key) - return g or [(1, 0)], c or [(1, 10)], i - - -def _parse_layers(s: str) -> list: - out = [] - for tok in str(s).replace(";", ",").split(","): - tok = tok.strip() - if tok: - l, d = tok.split("/") - out.append((int(l), int(d))) - return out - - -def _parse_select(s): - s = (s or "").strip() - if not s: - return None - return [int(x) - 1 for x in s.replace(" ", "").split(",") if x] # UI uses 1-based C1, C2, ... - - -def inspect_fn(f): - p = _path(f) - polys, _, _ = read_polygons(p) - n = sum(len(v) for v in polys.values()) - if n > LIMITS["max_polygons"]: - raise LayoutError(f"{n} polygons (> {LIMITS['max_polygons']}): crop the layout before uploading") - rows = load_gds(p) - table = [[r["layer"], r["datatype"], r["role"], r["n_polygons"], round(r["area_um2"], 1), - "(" + ", ".join(f"{x:.1f}" for x in r["bbox_um"]) + ")"] for r in rows] - return table, layer_preview(polys) - - -def layer_preview(polys: dict): - import matplotlib - - matplotlib.use("Agg") - import matplotlib.pyplot as plt - from matplotlib.patches import Polygon as MPoly - - fig, ax = plt.subplots(figsize=(6, 6)) - others = [c for c in L.CONDUCTOR_COLORS[3:] + L.CONDUCTOR_COLORS[1:3] if c != L.LIGHT_GOLD] # markers are thin: no light gold - handles = [] - k = 0 - for key, ps in sorted(polys.items(), key=lambda kv: (kv[0] != (1, 0), kv[0])): # ground first, underneath - if key == (1, 0): - col = L.GROUND_COLOR - elif key == (1, 10): - col = L.CONDUCTOR_COLORS[0] - else: - col, k = others[k % len(others)], k + 1 - for p in ps[:5000]: - ax.add_patch(MPoly(np.asarray(p.exterior.coords), closed=True, fc=col, ec="k", lw=0.2, alpha=0.85 if key != (1, 0) else 1.0)) - handles.append(MPoly([[0, 0]], fc=col, ec="k", label=f"{key[0]}/{key[1]} ({len(ps)})")) - ax.autoscale_view() - ax.set_aspect("equal") - ax.legend(handles=handles, loc="upper right", fontsize=8, title="layer/datatype (polygons)") - ax.set_xlabel("x (µm)") - ax.set_ylabel("y (µm)") - fig.tight_layout() - return fig - - -def _prepare(f, table, margin_gaps, margin_um, select): - g, c, i = _roles(table) - mu = float(margin_um) if margin_um not in (None, "", 0, 0.0) else None - return prepare(_path(f), ground_layers=g, conductor_layers=c, ignore_layers=i, margin_gaps=_margin(margin_gaps), margin_um=mu, - select=_parse_select(select), max_conductors=LIMITS["max_conductors"]) - - -def prepare_fn(f, table, margin_gaps, margin_um, select): - lay = _prepare(f, table, margin_gaps, margin_um, select) - import matplotlib - - matplotlib.use("Agg") - fig = lay.render() - fig.tight_layout() - out = Path(tempfile.mkdtemp()) / "prepared_1-0_ground_1-10_conductors.gds" - lay.to_gds(out) - summ = {"conductors": lay.names, "min_gap_um": round(lay.min_gap_um, 4), "window_um": [round(x, 2) for x in lay.window] if lay.window else None, - "lateral_extent_um": round(lay.extent_um(), 1), **{k: v for k, v in lay.info.items() if k != "cell"}} - warn = "\n".join(f"- {w}" for w in lay.warnings) or "- none" - return fig, f"**Warnings**\n\n{warn}", summ, str(out) - - -def _margin(v): - """0 (or 'auto') = automatic training-like window; < 0 = no crop; > 0 = that many conductor-ground gaps.""" - if v in (None, "", "auto"): - return "auto" - v = float(v) - return "auto" if v == 0 else (None if v < 0 else v) - - -def _eps(substrate, custom_eps): - return float(custom_eps) if substrate == CUSTOM else substrate - - -def report_md(res: dict, reg) -> str: - e = res["expected_error"] - v = e.get("validation", {}) - lines = [f"**Model** `{res['model']}` ({res['model_title']}), package {res['package_version']}, registry v{res['registry_version']}", - f"**Substrate** {res['substrate']} (eps_r {res['eps_r']:g}), {res['thickness_um']:g} µm (training stack; these models " - "are served for it only)", - "**Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in res["timing_s"].items()), - "", - f"**Expected error.** On {v.get('set', 'the 926 never-seen validation designs')} this model has median {v.get('median_pct')} % " - f"(MAE {v.get('mae_ff')} fF, RMSE {v.get('rmse_ff')} fF) over all mutual capacitances."] - if res.get("per_entry"): - pe = e.get("per_entry_model", {}) - val = pe.get("validation") or "" - lines.append(f"**Per-entry error estimates** (table above; ± = 80 % interval). For this layout: predicted median error " - f"{e['expected_median_pct']:.2f} %, MAE ≈ {e['expected_mae_ff']:.3g} fF, RMSE ≈ {e['expected_rmse_ff']:.3g} fF; " - f"{e['n_entries_p_large_gt_0p5']} of {len(res['per_entry'])} mutual entries have P(|error| > 5 %) > 0.5. " - "The intervals are split-conformal, calibrated on residuals of networks that never saw the design group, " - f"{val or ''} {pe.get('caveat', '')}") - if "expected_median_pct" in e and not res.get("per_entry"): - lines.append(f"Expected for this layout: median {e['expected_median_pct']:.2f} %, MAE ≈ {e['expected_mae_ff']:.2f} fF, " - f"RMSE ≈ {e['expected_rmse_ff']:.2f} fF (global estimate: this model has no per-entry error model).") - if res["warnings"]: - lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]] - lines += ["", "Ground self-capacitance is not predicted (depends on the chip boundary).", - "Trained and validated on planar single-layer layouts; training stack Si (eps 11.45), 350 µm, zero-thickness metal."] - return "\n".join(lines) - - -PM_CHOICES = ["values", "values ± 80 % interval"] -ENTRY_COLS = ["i", "j", "kind", "C (fF)", "80 % interval (fF)", "95 % interval (fF)", "predicted median error (%)", "P(|error| > 5 %)"] - - -def matrix_table(res, show=PM_CHOICES[0]): - """Matrix rows for the UI; with show = PM_CHOICES[1] the mutual entries carry ± half the 80 % interval.""" - if not res: - return None - names = res["names"] - hw = {} - for e in res.get("per_entry") or []: - lo, hi = e["interval_80_fF"] - hw[(e["i"], e["j"])] = hw[(e["j"], e["i"])] = 0.5 * (hi - lo) - out = [] - for a, row in zip(names, res["matrix_fF"]): - cells = [] - for b, x in zip(names, row): - if x is None: - cells.append("") - elif show == PM_CHOICES[1] and (a, b) in hw: - cells.append(f"{x:.4g} ± {hw[(a, b)]:.2g}") - else: - cells.append(round(x, 4) if show != PM_CHOICES[1] else f"{x:.4g}") - out.append([a] + cells) - return out - - -def entries_table(res): - ent = res.get("per_entry") or [] - return [[e["i"], e["j"], e["kind"], round(e["C_fF"], 4), "[{:.4g}, {:.4g}]".format(*e["interval_80_fF"]), - "[{:.4g}, {:.4g}]".format(*e["interval_95_fF"]), round(e["predicted_median_err_pct"], 2), round(e["p_large_error"], 3)] - for e in ent] - - -def predict_fn(f, table, margin_gaps, margin_um, select, substrate, custom_eps, thickness, model, self_rows): - reg = load_registry() - lay = _prepare(f, table, margin_gaps, margin_um, select) - res = _predict(lay, model, substrate=_eps(substrate, custom_eps), thickness_um=float(thickness), self_from_rows=bool(self_rows)) - d = Path(tempfile.mkdtemp()) - (d / "capacitance_fF.csv").write_text(matrix_csv(res)) - (d / "capacitance.json").write_text(json.dumps(res, indent=1)) - iv = None - if res.get("per_entry"): - iv = d / "capacitance_intervals_fF.csv" - iv.write_text(intervals_csv(res)) - return (matrix_table(res), str(d / "capacitance_fF.csv"), str(d / "capacitance.json"), report_md(res, reg), res, - entries_table(res), None if iv is None else str(iv)) - - -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="", self_from_rows=False): - t = time.perf_counter() - lay = prepare(_path(f), ground_layers=_parse_layers(ground_layers), conductor_layers=_parse_layers(conductor_layers), - margin_gaps=_margin(margin_gaps), max_conductors=LIMITS["max_conductors"]) - res = _predict(lay, model, substrate=_eps(substrate, custom_eps), thickness_um=float(thickness_um), - self_from_rows=bool(self_from_rows)) - res["timing_s"]["prepare_and_total_s"] = time.perf_counter() - t - return res - - -def _safe(fn, n_out): - import gradio as gr - - def wrapped(*a): - try: - return fn(*a) - except (LayoutError, ValueError, KeyError, FileNotFoundError) as e: - raise gr.Error(str(e)) from e - except MemoryError as e: - raise gr.Error("out of memory: crop the layout or use the coarse prior") from e - except Exception as e: # noqa: BLE001 - raise gr.Error(f"internal error ({type(e).__name__}): {e}") from e - wrapped.__name__ = fn.__name__ - return wrapped - - -INTRO = """ -### What this does -Upload the GDS of a **planar** superconducting layout (metal film on a dielectric substrate) and get its full -**Maxwell capacitance matrix** in fF, zero-shot: no simulation of your design. A thin-film method-of-moments solve -provides a physics prior and a graph network trained on 40,153 Q3D simulations corrects it. - -### Layer convention -* **1/0 = ground**: the ground plane (one net, everything on this layer is connected). -* **1/10 = conductors**: the floating metal islands; every connected body is one net (C1, C2, ...). -* Anything else (port markers, junctions, labels) is ignored unless you assign it a role. - -Your file may use other layers: assign the roles in step 1. 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). -""" - - -def _model_md(reg, k): - m = reg.models[k] - p = m.get("paper", {}) - - def f(x): - return f"{x.get('median_pct')} % / MAE {x.get('mae_ff')} fF / RMSE {x.get('rmse_ff')} fF" if x else "n/a" - repo = m.get("repo_id") - return (f"**{m['title']}** — {m.get('summary', '')} \n" - f"Never-seen components: {f(p.get('never_seen'))} · OOD-60 shapes: {f(p.get('ood60'))}" - + (f" \nWeights: [{repo}](https://huggingface.co/{repo})" if repo else "")) - - -def tier_choices(reg) -> list[tuple[str, str]]: - """Flagship model choice: [("Fast: flagship-fast (default, ~X s) ...", "fast"), ("Coarse prior (~Y s) ...", "coarse"), - ("Fine prior (most accurate, ~Z s) ...", "fine")] with the measured latency and held-out accuracy from registry - defaults.tiers; a tier only when its model is configured.""" - from .predict import TIER_KEYS - - d = reg["defaults"] - info = d.get("tiers", {}) - labels = {"fast": "Fast: flagship-fast (default", "coarse": "Coarse prior (", "fine": "Fine prior (most accurate"} - out = [] - for tier in ("fast", "coarse", "fine"): - if not d.get(TIER_KEYS[tier]): - continue - t = info.get(tier, {}) - lat = f"~{t['latency_s']:.0f} s" if t.get("latency_s") is not None else "" - lab = labels[tier] + ((", " if not labels[tier].endswith("(") else "") + lat if lat else "") + ")" - acc = (f" — held-out median {t['median_pct']:.2f} %, MAE {t['mae_ff']:.2f} fF, RMSE {t['rmse_ff']:.2f} fF" - if t.get("median_pct") is not None else "") - out.append((lab.replace("()", "") + acc, tier)) - return out - - -def _tier_md(reg, tier): - from .predict import resolve_model - - name = resolve_model(reg, tier) - t = reg["defaults"].get("tiers", {}).get(tier, {}) - note = t.get("note", "") - return f"Model: **{reg.models[name]['title']}** (`{name}`). {note}" - - -def build_app(title: str, model_choices: list[str], default_model: str, header_md: str = "", examples_dir=None, - extra_tab=None, tiers: bool = False): - import gradio as gr - - reg = load_registry() - subs = list(reg.substrates()) + [CUSTOM] - ex = sorted(Path(examples_dir).glob("*.gds")) if examples_dir and Path(examples_dir).exists() else [] - space = os.environ.get("SPACE_ID") - with gr.Blocks(title=title) as demo: - gr.Markdown(f"# {title}\n{header_md}" + (f"\n\nSpace: `{space}`" if space else "")) - if extra_tab is not None: - extra_tab(gr, reg) - with gr.Accordion("Planar circuits and the layer convention", open=True): - with gr.Row(): - gr.Markdown(INTRO) - with gr.Column(): - ex_pick = gr.Dropdown([p.name for p in ex], value=ex[0].name if ex else None, label="example layout") - ex_plot = gr.Plot(label="annotated example: grey = ground (1/0), colours = conductors (1/10)") - top_pick = extra_tab is not None # paper-models app: model choice is the point, so it comes first - if top_pick: - gr.Markdown("## Choose a model of the paper") - model = gr.Radio([(f"{reg.models[k]['title']}", k) for k in model_choices], value=default_model, label="model") - model_info = gr.Markdown(_model_md(reg, default_model)) - 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: - gr.Examples([[str(p)] for p in ex], inputs=[gds], 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 nets and crop the ground") - with gr.Row(): - with gr.Column(scale=1): - margin = gr.Slider(0, 300, value=0, step=1, label="ground margin around the conductors, in conductor-ground gaps (0 = auto: training-like, recommended)") - margin_um = gr.Number(value=None, label="or absolute margin (µm); overrides the slider") - select = gr.Textbox(label="conductors to model (e.g. 1,2,3; empty = all)", value="") - 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 (dashed: crop window)") - gr.Markdown("## 3. Substrate" + ("" if top_pick else " and model")) - 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)") - if tiers: # flagship: fast (default) / coarse / fine tier choice instead of a model list - model = gr.Radio(tier_choices(reg), value="fast", label="model") - elif not top_pick: - model = gr.Dropdown(model_choices, value=default_model, label="model") - self_rows = gr.Checkbox(False, label="self-capacitance from row sums") - if tiers: - tier_info = gr.Markdown(_tier_md(reg, "fast")) - model.change(lambda k: _tier_md(reg, k), model, tier_info, api_visibility="private") - pred_btn = gr.Button("Predict", variant="primary") - gr.Markdown("## 4. Maxwell capacitance matrix (fF)") - with gr.Row(): - with gr.Column(scale=2): - pm = gr.Radio(PM_CHOICES, value=PM_CHOICES[1], label="matrix display") - 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 + per-entry error estimates)") - iv_f = gr.File(label="CSV of per-entry intervals") - entries = gr.Dataframe(headers=ENTRY_COLS, label="per-entry error estimates (mutual entries; intervals include the stack residual)", - interactive=False) - 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") - - def ex_fn(name): - if not name: - return None - from .layout import prepare as _p - - lay = _p(str(Path(examples_dir) / name), margin_gaps=None) - fig = lay.render(title=f"{name}: {lay.n_conductors} conductors + ground") - fig.tight_layout() - return fig - - if ex: - ex_pick.change(ex_fn, ex_pick, ex_plot, api_visibility="private") - demo.load(ex_fn, ex_pick, ex_plot, api_visibility="private") - gds.upload(_safe(inspect_fn, 2), gds, [layers, layer_plot], api_name="inspect") - prep_btn.click(_safe(prepare_fn, 4), [gds, layers, margin, margin_um, select], [prep_plot, warn_md, summary, prepared_gds], api_name="prepare") - pred_btn.click(_safe(predict_fn, 7), [gds, layers, margin, margin_um, select, substrate, custom_eps, thickness, model, self_rows], - [mat, csv_f, json_f, report, res_state, entries, iv_f], api_name="predict").then( - matrix_table, [res_state, pm], mat, api_visibility="private") - pm.change(matrix_table, [res_state, pm], mat, api_visibility="private") - a_btn.click(_safe(api_predict_gds, 1), [gds, a_g, a_c, a_m, substrate, custom_eps, thickness, model, self_rows], a_out, - api_name="predict_gds") - gr.Markdown(f"tlsq_infer {__version__}. Demo-server caps (not limits of the models): {LIMITS['max_file_mb']:g} MB per file, " - f"{LIMITS['max_polygons']:,} polygons, {LIMITS['max_conductors']} conductors + ground on the fast tier " - f"({LIMITS['max_conductors_heavy']} on the coarse / fine tiers).") - return demo diff --git a/tlsq_infer/app_v2.py b/tlsq_infer/app_v2.py deleted file mode 100644 index f3e69127d7c14cc46e5a9245b57eed2ad328cc21..0000000000000000000000000000000000000000 --- a/tlsq_infer/app_v2.py +++ /dev/null @@ -1,288 +0,0 @@ -"""Gradio front end of the paper-models Space (v2, PLAN_HF_SPACE_V2.md): one app, a model toggle over the final recipes of -the paper (tlsq_infer.final: E3 model, E1 fast, C0 physics only, plus the deployment model E3-D when its weights are -bundled), training geometry by default (no ground crop; the crop is an advanced option). Reuses app_ui (layer table, -previews, error handling). Needs `gradio`. - -API endpoints (gradio_client, api_name; the same over REST at /gradio_api/call/): - /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 (one call, for scripts). margin_gaps: 0 or < 0 = no crop (training geometry, default), - > 0 = crop the ground to that many conductor-ground gaps around the conductors, "auto" = the old auto window. - model: "E3" (default) / "E1" / "C0" / "E3-D" / "E1-D", or the words "model" / "fast" / "physics" / "deployment" / - "deployment fast". trust_rule (default True = final_defaults.trust_rule): the paper's seed-spread rule for the E3 - recipes (E3, E3-D); False returns the raw E3 matrix. The trust decision and the seed spread are in "trust". -""" - -from __future__ import annotations - -import json -import os -import shutil -import tempfile -import time -from pathlib import Path - -from . import __version__ -from . import final as F -from . import substrate as SUB -from .app_ui import CUSTOM, HEAVY, INTRO, LAYER_COLS, LIMITS, _eps, _parse_layers, _parse_select, _path, _roles, _safe, inspect_fn, matrix_table -from .layout import LayoutError, prepare -from .predict import matrix_csv -from .registry import load_registry - -ALIASES = {"model": "E3", "fast": "E1", "physics": "C0", "physics only": "C0", "deployment": "E3-D", "deployment fast": "E1-D"} -NETWORK_CAP = int(os.environ.get("TLSQ_MAX_CONDUCTORS_NETWORK", 30)) # E3 recipes: dense pair tensors; E1 / C0 up to LIMITS["max_conductors"] -PURGE_AGE_S = int(os.environ.get("TLSQ_PURGE_AGE_S", 600)) -_TMP = Path(tempfile.gettempdir()) / "tlsq_results" - - -def served(reg=None) -> list[str]: - """Final models with weights present (C0 always), in registry order.""" - reg = reg or load_registry() - return [k for k in F.model_names(reg) if F.available(k, reg)] - - -def resolve(reg, model) -> str: - m = str(model or reg["final_defaults"]["model"]).strip() - m = ALIASES.get(m.lower(), m) - if m not in served(reg): - raise ValueError(f"model {model!r} is not served here; choose one of {served(reg)} (or model / fast / physics / deployment / " - "deployment fast)") - return m - - -def _crop(crop, margin_gaps, margin_um): - """(margin_gaps, margin_um) for prepare: no crop unless asked (training geometry).""" - if not crop: - return None, None - mu = float(margin_um) if margin_um not in (None, "", 0, 0.0) else None - return (float(margin_gaps) if margin_gaps not in (None, "", 0, 0.0) else "auto"), mu - - -def _prepare(f, table, crop, margin_gaps, margin_um, select, ground_pieces=None): - g, c, i = _roles(table) - mg, mu = _crop(crop, margin_gaps, margin_um) - return prepare(_path(f), ground_layers=g, conductor_layers=c, ignore_layers=i, margin_gaps=mg, margin_um=mu, - select=_parse_select(select), max_conductors=LIMITS["max_conductors"], ground_pieces=ground_pieces) - - -def prepare_fn(f, table, crop, margin_gaps, margin_um, select, ground_pieces=None): - import matplotlib - matplotlib.use("Agg") - lay = _prepare(f, table, crop, margin_gaps, margin_um, select, ground_pieces) - fig = lay.render() - fig.tight_layout() - out = _outdir() / "prepared_1-0_ground_1-10_conductors.gds" - lay.to_gds(out) - summ = {"conductors": lay.names, "min_gap_um": round(lay.min_gap_um, 4), "geometry": "cropped" if lay.window else "training (no crop)", - "window_um": [round(x, 2) for x in lay.window] if lay.window else None, "lateral_extent_um": round(lay.extent_um(), 1), - **{k: v for k, v in lay.info.items() if k != "cell"}} - warn = "\n".join(f"- {w}" for w in lay.warnings) or "- none" - return fig, f"**Warnings**\n\n{warn}", summ, str(out) - - -def _outdir() -> Path: - """Per-request result folder; folders older than PURGE_AGE_S are deleted on every request (nothing is kept).""" - _TMP.mkdir(parents=True, exist_ok=True) - now = time.time() - for d in _TMP.iterdir(): - try: - if now - d.stat().st_mtime > PURGE_AGE_S: - shutil.rmtree(d, ignore_errors=True) - except OSError: - pass - return Path(tempfile.mkdtemp(dir=_TMP)) - - -def _predict(lay, model, **kw): - reg = load_registry() - name = resolve(reg, model) - if F.load_model(name, reg).recipe == "E3" and lay.n_conductors > NETWORK_CAP: - raise LayoutError(f"{lay.n_conductors} conductors: the network recipes (E3) are capped at {NETWORK_CAP} on this server; " - "use the fast (E1) or physics-only (C0) recipe, or run the package locally") - kw["trust_rule"] = bool(reg["final_defaults"].get("trust_rule", True)) if kw.get("trust_rule") is None else bool(kw["trust_rule"]) - if lay.n_conductors <= 8: - return F.predict_final(lay, name, **kw) - with HEAVY: - return F.predict_final(lay, name, **kw) - - -def trust_note(reg) -> str: - return reg["final_defaults"].get("trust_rule_note") or "" - - -def _acc_lines(m: dict) -> list[str]: - acc = m.get("accuracy") or {} - if not acc: - return ["No test number applies to this model (see its warning)."] + ([f"\n{m['scoring_note']}"] if m.get("scoring_note") else []) - 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.values()] - return rows - - -def report_md(res: dict, reg) -> str: - m = reg["final_models"][res["model"]] - t = res["timing_s"] - tr = res.get("trust") or {} - lines = [f"**Model** `{res['model']}`: {res['model_title']} ({res['role']}; ledger id `{res['ledger_id']}`), package " - f"{res['package_version']}, registry v{res['registry_version']}", - SUB.line(res), - "**Timing** " + ", ".join(f"{k.replace('_s', '')} {v:.2f} s" for k, v in t.items() if isinstance(v, float)), - ""] - if tr: - sp = f"seed spread of the three networks {tr['seed_spread']:.3g} vs threshold {tr['tau']:g}" - if tr.get("applied") and tr.get("fallback_to_C0"): - lines.append(f"**Trust rule applied (default): FALLBACK to physics-only C0** for this whole layout ({sp}: the networks disagree).") - elif tr.get("applied"): - lines.append(f"**Trust rule applied (default): E3 kept** on the {tr['n_E3_entries']} conductor pairs closer than " - f"{tr['near_um']:g} µm, physics-only C0 on the other pairs ({sp}: the networks agree).") - else: - lines.append(f"**Trust rule switched off**: raw E3 on every pair ({sp}" - + ("; the rule would have fallen back to C0)." if tr["exceeds_tau"] else "; the rule would have kept E3 on the close pairs).")) - if m.get("accuracy"): - lines += ["", "**Test results of this recipe in the paper** (reported model, scored once on each test set; median relative " - "error / MAE / RMSE over mutual entries):", ""] + _acc_lines(m) - else: - lines += ["", "**Test results**:", ""] + _acc_lines(m) - if res["warnings"]: - lines += ["", "**Warnings**", ""] + [f"- {w}" for w in res["warnings"]] - lines += ["", f"Self capacitance: {res['self_capacitance']}. Ground self-capacitance is not predicted.", - "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, substrate=_eps(substrate, custom_eps), thickness_um=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 _margin_api(v): - if isinstance(v, str) and v.strip().lower() == "auto": - return "auto" - v = float(v or 0) - return None if v <= 0 else v - - -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="E3", 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, substrate=_eps(substrate, custom_eps), thickness_um=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 models_fn(): - reg = load_registry() - return [{"id": k, "title": reg["final_models"][k]["title"], "recipe": reg["final_models"][k]["recipe"], "role": reg["final_models"][k].get("role"), - "ledger_id": reg["final_models"][k].get("ledger_id"), "accuracy": reg["final_models"][k].get("accuracy") or {}, - "warning": reg["final_models"][k].get("warning")} for k in served(reg)] + [{"package_version": __version__, "registry_version": reg["version"]}] - - -def _model_md(reg, k) -> str: - m = reg["final_models"][k] - return "\n".join([f"**{m['title']}** ({m.get('role')}). {m.get('summary', '')}"] + ([f"\n> {m['warning']}"] if m.get("warning") else []) - + ["", *_acc_lines(m)]) - - -HEADER = """Zero-shot **Maxwell capacitance matrix** of a planar superconducting layout from its GDS: a slab-kernel micro-MoM solve at -two panel densities, log-Richardson extrapolation, per-kind offsets and (model E3) a bounded learned correction. Choose the -recipe below; the default is the paper's reported model, with the paper's trust rule applied (note below). **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["final_defaults"]["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}") - if trust_note(reg): - gr.Markdown(f"> {trust_note(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([(reg["final_models"][k]["title"], k) for k in ms], value=default, label="recipe") - 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: - gr.Examples([[str(p)] for p in ex], inputs=[gds], 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\nOn substrates other than the training stack (Si, eps_r 11.45, 350 µm) the physics priors are solved " - "at your eps_r and thickness and the recipes' corrections are applied unchanged (calibrated route, tested on Si at 10-1000 µm " - "and eps_r 3.8-24 at 350 µm with the paper model; other combinations are flagged untested).") - 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="self-capacitance from row sums (not trained, not scored)") - trust_cb = gr.Checkbox(bool(reg["final_defaults"].get("trust_rule", True)), - label="apply the trust rule (E3 models; 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"tlsq_infer {__version__}. Demo-server caps (not limits of the models): {LIMITS['max_file_mb']:g} MB per file, " - f"{LIMITS['max_polygons']:,} polygons, {LIMITS['max_conductors']} conductors + ground (E1 / C0), {NETWORK_CAP} for the " - "network recipes (E3).") - return demo diff --git a/tlsq_infer/charge.py b/tlsq_infer/charge.py deleted file mode 100644 index 9b8a7f8a59dd9d001728436c384f26bff5c8bfaa..0000000000000000000000000000000000000000 --- a/tlsq_infer/charge.py +++ /dev/null @@ -1,119 +0,0 @@ -"""Charge-corrected MoM prior: a gradient-boosted model of log(|q_Q3D| / |q_MoM|) per quadtree cell from 9 local geometry -features (scripts/charge_locality.py, scripts/zs_study.py: cell_features), applied to the cell charges of every -excitation and integrated per conductor. Trained once on the surface charge of the training families (no capacitance -labels) and shipped as a joblib file. - - python -m tlsq_infer.charge fit --cells data_local/charge_p1/train_cells.parquet --out deploy/artifacts/charge_gbm.joblib -""" - -from __future__ import annotations - -import numpy as np -import shapely - -FEATS = ["owner_driven", "owner_ground", "other_is_driven", "other_is_ground", "log_h", "log_d_own", "log_d_other", - "log_h_over_d", "log_sig_mom"] -GBM_PARAMS = dict(max_iter=400, learning_rate=0.05, random_state=0) - - -def fit_gbm(cells_parquet): - """Exactly the cell model of the paper (all five training families, 9 features).""" - import pandas as pd - from sklearn.ensemble import HistGradientBoostingRegressor - - cells = pd.read_parquet(cells_parquet) - ok = (np.sign(cells.q_mom) == np.sign(cells.q_q3d)) & (cells.q_mom.abs() > 1e-9) & (cells.q_q3d.abs() > 1e-9) - cells = cells[ok] - r = np.log(np.abs(cells.q_q3d) / np.abs(cells.q_mom)) - return HistGradientBoostingRegressor(**GBM_PARAMS).fit(cells[FEATS], r, sample_weight=cells.q_mom.abs()), int(len(cells)) - - -def cell_feature_frames(metals: list, mom: dict) -> tuple[dict, np.ndarray]: - """Per-excitation feature tables (float32, as in the paper's cell cache) and float32 cell charges.""" - import pandas as pd - - cen, h, own, Q = mom["cen"], mom["h"], mom["own"], mom["Q"] - pts = shapely.points(cen) - d_own, d_other, other_id = np.zeros(len(cen)), np.full(len(cen), np.inf), np.full(len(cen), -1) - for k, g in enumerate(metals): - sel = own == k - d_own[sel] = shapely.distance(g.boundary, pts[sel]) - for k2, g2 in enumerate(metals): - if k2 != k: - dk = shapely.distance(g2, pts[sel]) - better = dk < d_other[sel] - ix = np.nonzero(sel)[0][better] - d_other[ix], other_id[ix] = dk[better], k2 - base = {"owner_ground": (own == 0).astype(float), "other_is_ground": (other_id == 0).astype(float), "log_h": np.log(h), - "log_d_own": np.log(d_own + 0.05), "log_d_other": np.log(d_other + 0.05), "log_h_over_d": np.log(h / (d_own + 0.05))} - X = {j: pd.DataFrame({**base, "owner_driven": (own == j).astype(float), "other_is_driven": (other_id == j).astype(float), - "log_sig_mom": np.log(np.abs(Q[:, j]) / h**2 + 1e-12)}).astype(np.float32) for j in range(len(metals))} - return X, Q.astype(np.float32) - - -def corrected_matrix(gbm, metals: list, mom: dict) -> np.ndarray: - """Charge-corrected Maxwell matrix (fF), training stack.""" - X, Q = cell_feature_frames(metals, mom) - n = len(metals) - own = mom["own"] - C = np.stack([np.bincount(own, weights=Q[:, j] * np.exp(gbm.predict(X[j][FEATS])), minlength=n) for j in range(n)], 1) - return 0.5 * (C + C.T) - - -def corrected_matrix_v3(gbm, metals: list, mom: dict) -> np.ndarray: - """Charge-corrected Maxwell matrix on the v3 gap/3 mesh (scripts/charge_v3.py: rectangular panels, log_h = - log sqrt(w h), density |q| / (w h), float64 charges). `mom` = a v3 solve with cell arrays (mom_solve_v3, rich=False).""" - import pandas as pd - - cen, wh, own, Q = mom["cen"], mom["wh"], mom["own"], mom["Q"] - n = len(metals) - pts = shapely.points(cen) - d_own, d_other, other_id = np.zeros(len(cen)), np.full(len(cen), np.inf), np.full(len(cen), -1) - for k, g in enumerate(metals): - sel = own == k - d_own[sel] = shapely.distance(g.boundary, pts[sel]) - for k2, g2 in enumerate(metals): - if k2 != k: - dk = shapely.distance(g2, pts[sel]) - better = dk < d_other[sel] - ix = np.nonzero(sel)[0][better] - d_other[ix], other_id[ix] = dk[better], k2 - area = wh[:, 0] * wh[:, 1] - lh = 0.5 * np.log(area) - base = {"owner_ground": (own == 0).astype(float), "other_is_ground": (other_id == 0).astype(float), "log_h": lh, - "log_d_own": np.log(d_own + 0.05), "log_d_other": np.log(d_other + 0.05), "log_h_over_d": lh - np.log(d_own + 0.05)} - - def frame(j): - return pd.DataFrame({**base, "owner_driven": (own == j).astype(float), "other_is_driven": (other_id == j).astype(float), - "log_sig_mom": np.log(np.abs(Q[:, j]) / area + 1e-12)})[FEATS].astype(np.float32) - C = np.stack([np.bincount(own, weights=Q[:, j] * np.exp(gbm.predict(frame(j))), minlength=n) for j in range(n)], 1) - return 0.5 * (C + C.T) - - -def load_gbm(path): - import joblib - - return joblib.load(path) - - -if __name__ == "__main__": - import argparse - import json - import time - - import joblib - import sklearn - - ap = argparse.ArgumentParser() - ap.add_argument("cmd", choices=["fit"]) - ap.add_argument("--cells", required=True) - ap.add_argument("--out", required=True) - a = ap.parse_args() - t = time.time() - m, n = fit_gbm(a.cells) - joblib.dump(m, a.out, compress=3) - meta = {"features": FEATS, "params": GBM_PARAMS, "n_cells": n, "sklearn": sklearn.__version__, "fit_s": round(time.time() - t, 1), - "target": "log(|q_Q3D| / |q_MoM|) per quadtree cell, weight |q_MoM|"} - with open(str(a.out).replace(".joblib", ".json"), "w") as f: - json.dump(meta, f, indent=1) - print(meta) diff --git a/tlsq_infer/errmodel.py b/tlsq_infer/errmodel.py deleted file mode 100644 index e16b5e438e3f2dc2aba4ea15af32caa2b018b40c..0000000000000000000000000000000000000000 --- a/tlsq_infer/errmodel.py +++ /dev/null @@ -1,125 +0,0 @@ -"""Per-entry error model (ERROR_MODEL.md): physics features of every mutual entry -> predicted median |log error|, -P(|err| > 5 %) and split-conformal 80 % / 95 % intervals. - -The same `features` function builds the training table (HPC, fold networks; scripts/error_model.py) and the inference -features (here), from one "ingredients" record per design: - - names ["G", ...] (index 0 = ground) - logC_seeds (S, k, k) per-seed network output (diag log C_ii, off-diag log |C_ij|), training stack - prior_C (k, k) Maxwell matrix of the MoM prior the network saw - prior_coarse_C (k, k) gap/3 solve when the prior is v3-rich (else None) - edges {(i, j): (log_dmin, log_cps, share_mean)} from the scene graph - h_min smallest MoM cell (µm) -""" - -from __future__ import annotations - -import json -from pathlib import Path - -import numpy as np - -FEATURES = ["is_cg", "log_c", "log_rel_max", "log_rel_min", "d_prior", "prior_conv", "cells_per_gap", "n_cond", - "log_min_gap", "log_dmin", "log_cps", "share_mean", "seed_sd"] -MONOTONE = {"log_c": -1, "log_rel_max": -1, "prior_conv": 1, "seed_sd": 1, "cells_per_gap": -1} -THRESHOLD = 0.05 # |C_pred / C_true - 1| > 5 % = "large error" - - -def ingredients_from_graph(names, logC_seeds, prior_C, graph, h_min, prior_coarse_C=None) -> dict: - edges = {tuple(e): (float(f["log_dmin"]), float(f["log_cps"]), float(f["share_mean"])) for e, f in graph["edges"].items()} - return {"names": list(names), "logC_seeds": np.asarray(logC_seeds, np.float64), "prior_C": np.asarray(prior_C, np.float64), - "prior_coarse_C": None if prior_coarse_C is None else np.asarray(prior_coarse_C, np.float64), "edges": edges, - "h_min": float(h_min)} - - -def _neglog(C, i, j): - return np.log(max(-C[i, j], 1e-9)) - - -def features(ing: dict, use_prior_conv: bool) -> tuple[list[tuple[int, int]], np.ndarray]: - """(pairs, X) with X[:, FEATURES]: one row per mutual entry i < j (prior_conv NaN when unused).""" - S = ing["logC_seeds"] - k = len(ing["names"]) - L = S.mean(0) - sd = S.std(0, ddof=1) if S.shape[0] > 1 else np.zeros_like(L) - P, Pc = ing["prior_C"], ing.get("prior_coarse_C") - gaps = [v[0] for v in ing["edges"].values()] - log_min_gap = float(min(gaps)) if gaps else np.nan - cpg = float(np.exp(log_min_gap) / max(ing["h_min"], 1e-9)) if gaps else np.nan - pairs, rows = [], [] - for i in range(k): - for j in range(i + 1, k): - lc = L[i, j] - ends = [x for x in (i, j) if x != 0] - rel = [lc - L[x, x] for x in ends] - conv = abs(_neglog(P, i, j) - _neglog(Pc, i, j)) if (use_prior_conv and Pc is not None) else np.nan - ld, lcps, sh = ing["edges"].get((i, j), ing["edges"].get((j, i), (np.nan, np.nan, np.nan))) - rows.append([float(i == 0), lc, max(rel), min(rel), abs(lc - _neglog(P, i, j)), conv, cpg, float(k - 1), - log_min_gap, ld, lcps, sh, sd[i, j]]) - pairs.append((i, j)) - return pairs, np.asarray(rows, np.float64) - - -def targets(ing: dict, Y: np.ndarray, pairs) -> tuple[np.ndarray, np.ndarray]: - """a = |log(C_pred / C_true)| and rel = |C_pred / C_true - 1| per entry (Y: Maxwell labels, fF).""" - L = ing["logC_seeds"].mean(0) - d = np.array([L[i, j] - np.log(-Y[i, j]) for i, j in pairs]) - return np.abs(d), np.abs(np.expm1(d)) - - -# ---------------------------------------------------------------- inference - -_CACHE: dict = {} - - -def find_artifact(model: str, reg=None) -> Path | None: - """deploy/artifacts/error_model_.joblib for the registry model (registry artifacts.error_model maps names).""" - tag = None - if reg is not None: - tag = (reg["artifacts"].get("error_model") or {}).get(model) - if not tag: - return None - here = Path(__file__).resolve() - for p in [here.parent / tag] + [q / "artifacts" / tag for q in here.parents] + [q / "deploy" / "artifacts" / tag for q in here.parents]: - if p.exists(): - return p - try: - from .registry import _hub_download - - return Path(_hub_download(reg.model(model)["repo_id"], tag)) - except Exception: # noqa: BLE001 - return None - - -def load(path) -> dict: - path = str(path) - if path not in _CACHE: - import joblib - - _CACHE[path] = joblib.load(path) - return _CACHE[path] - - -def predict_entries(art: dict, ing: dict, labels: list[str], scale: float = 1.0, stack_rel: float = 0.0) -> list[dict]: - """Per-entry estimates for the result dict. scale: the eps correction factor applied to the matrix; stack_rel: median - relative stack residual (material + thickness, deploy/stack_error.py), added in quadrature (Gaussian assumption).""" - pairs, X = features(ing, art["use_prior_conv"]) - Xu = X[:, [FEATURES.index(f) for f in art["features"]]] - sig = np.maximum(art["regressor"].predict(Xu), 1e-4) - p = art["classifier"].predict_proba(Xu)[:, 1] - L = ing["logC_seeds"].mean(0) - s_stack = stack_rel / 0.674 # Gaussian sigma of the stack residual in log space (small-error approximation) - out = [] - for (i, j), x, s, pl in zip(pairs, X, sig, p): - kind = "conductor-ground" if x[0] > 0.5 else "conductor-conductor" - q = art["conformal"][kind] - c = float(np.exp(L[i, j]) * scale) - rec = {"i": labels[i], "j": labels[j], "kind": kind, "C_fF": c, - "predicted_median_err_pct": float(100 * np.sqrt(np.expm1(s) ** 2 + (0.674 * s_stack) ** 2)), - "p_large_error": float(pl)} - for lev, z in (("80", 1.2816), ("95", 1.96)): - h = float(np.hypot(q[lev] * s, z * s_stack)) - rec[f"interval_{lev}_fF"] = [c * float(np.exp(-h)), c * float(np.exp(h))] - rec[f"halfwidth_{lev}_pct"] = float(100 * np.expm1(h)) - out.append(rec) - return out diff --git a/tlsq_infer/final.py b/tlsq_infer/final.py deleted file mode 100644 index 153836a894d7c58113b5f956517c96fcd9fda6e4..0000000000000000000000000000000000000000 --- a/tlsq_infer/final.py +++ /dev/null @@ -1,404 +0,0 @@ -"""Final recipes of the paper (paper_v3; TRAINING_PLAN Amendment E-matrix, scored by scripts/tm_final.py): - - C0 = R(1.5, 3) log-Richardson of the slab lite micro-MoM at 1.5 and 3 panels per gap (no fitted parameter) - E1 = R(0.75, 1.5) + c_kind per-entry-kind log offsets of the model (no network) - E3 = R(1.5, 3) + c_kind + correction bounded (+-3 %) local correction (SceneGNN on pair tokens), mean log C of 3 seeds - -The rows are built as the evaluation rows of scripts/tm_eval.py (build_one): training-convention scene (uncropped ground), -pair tokens (tlsq.uge.blocks) on every pair (pairs within 150 smallest gaps on layouts with > 8 conductors), local tokens -(localtok), and per resolution the slab lite prior (local-gap mesh on sliver layouts, PRIOR_SCHEME.md section 19; identical to -the plain lite prior elsewhere). Prediction on rows reproduces tm_final.score_em exactly (deploy/tests/test_final_parity.py). -Other substrates: the slab lite priors are solved at the requested (eps_r, thickness) and the recipe's offsets / corrections, fit on -the training stack (Si 11.45, 350 um), are applied unchanged; the features stay at the training stack (tlsq_infer.substrate). -""" - -from __future__ import annotations - -import copy -import hashlib -import json -import os -import time -from dataclasses import dataclass, field -from itertools import combinations -from pathlib import Path - -import numpy as np - -from . import __version__ -from ._vendor import em as EM -from ._vendor import mom as _mom -from ._vendor.graph import prior_dict -from ._vendor.scene import make_scene -from .layout import PreparedLayout -from .registry import PRIORS, load_registry -from . import substrate as SUB -from .substrate import EPS_TRAIN, T_TRAIN - -RECIPES = {"C0": (1.5, 3.0), "E1": (0.75, 1.5), "E3": (1.5, 3.0)} -TAU = 1.254e-3 # trust rule (tm_final.TAU): seed spread above this -> C0 on the near graph entries -NEAR_UM = 100.0 -SPARSE_MIN, SPARSE_R_GAPS = 8, 150.0 # tm_eval: > 8 signal conductors -> pair tokens only within 150 smallest gaps - - -class PriorError(ValueError): - """The physics prior produced no usable mutual entry.""" - - -def internal_names(n_signal: int) -> list[str]: - """Entry-kind names of the deployment convention (as predict.py and the qm116 / atlas / large-N rows): G, N, S, P1, ...""" - return ["G"] + (["N", "S"] + [f"P{k}" for k in range(1, n_signal - 1)])[:n_signal] - - -# ------------------------------------------------------------------ rows (tm_eval.build_one) -def far_mask(metals: list) -> np.ndarray: - import shapely - - from ._vendor.fastprior import gap_of - n = len(metals) - far = np.zeros((n, n), bool) - if n - 1 <= SPARSE_MIN: - return far - conds = list(metals[1:]) - a, b = shapely.STRtree(conds).query(conds, predicate="dwithin", distance=SPARSE_R_GAPS * gap_of(list(metals))) - far[:] = True - far[a + 1, b + 1] = False - far[0, :] = far[:, 0] = False - np.fill_diagonal(far, False) - return far - - -def graph(scene, far: np.ndarray) -> dict: - """tm_eval.graph: tlsq.uge.graph.scene_graph without the prior, pairs restricted to the non-far ones.""" - from ._vendor.blocks import boundary_points, edge_features, global_features, node_features - bpts, widths = boundary_points(scene) - nodes = [node_features(scene, i) for i in range(scene.n)] - edges = {(i, j): edge_features(scene, i, j, bpts, widths) for i, j in combinations(range(scene.n), 2) if not far[i, j]} - tot = np.zeros(scene.n) - for (i, j), f in edges.items(): - tot[i] += f["_cps"] - tot[j] += f["_cps"] - for (i, j), f in edges.items(): - 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) - f.pop("_cps") - return {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges} - - -def solve(metals: list, ppg: float, mesh: str = "loc", eps_r: float = EPS_TRAIN, t_um: float = T_TRAIN) -> dict: - """Slab lite micro-MoM at ppg panels per smallest gap on a substrate of eps_r and thickness t_um: mesh "loc" (training rows: - local-gap mesh on sliver layouts, otherwise the plain lite mesh) or "plain" (liteppg

_slab everywhere).""" - with _mom.substrate(None, float(t_um)): - if mesh == "loc": - from ._vendor.mom_loc import PRIORS_LOC, solve_prior_loc - return solve_prior_loc(metals, eps_r=float(eps_r), **PRIORS_LOC[f"liteppg{ppg:g}-slab-loc"]) - return _mom.solve_prior(metals, eps_r=float(eps_r), **PRIORS[f"liteppg{ppg:g}-slab"]) - - -def build_rows(metals: list, names: list[str], ppgs, features: bool = True, mesh: str = "loc", timing: dict | None = None, - stack: tuple | None = None) -> dict: - """{ppg: row} for one layout (metals[0] = ground; names[0] = 'G'). features=False: prior matrices only (C0 / E1). - stack: (eps_r, thickness_um) the priors are solved at (default the training stack); the features always use the training stack.""" - timing = {} if timing is None else timing - t = time.perf_counter() - far = far_mask(metals) - g = {"names": list(names), "nodes": [], "edges": {}, "global": {}} - if features: - from .localtok import add_tokens - sc = make_scene(metals[0], list(metals[1:]), list(names[1:])) - timing["scene_s"] = time.perf_counter() - t - t = time.perf_counter() - g = graph(sc, far) - timing["features_s"] = time.perf_counter() - t - t = time.perf_counter() - g = add_tokens(sc, g) - timing["tokens_s"] = time.perf_counter() - t - out = {} - for p in ppgs: - t = time.perf_counter() - px = solve(metals, p, mesh, *(stack or (EPS_TRAIN, T_TRAIN))) - timing[f"prior_ppg{p:g}_s"] = time.perf_counter() - t - r = copy.deepcopy(g) - d = prior_dict(px["C"], px["n_cells"], px["h_min"], list(g["edges"]), (px.get("mesh") or {}).get("min_gap_um")) - for i, v in d["node"].items(): - if features: - r["nodes"][i].update({f"proxy_{k}": x for k, x in v.items()}) - for e, v in d["edge"].items(): - r["edges"][e].update({f"proxy_{k}": x for k, x in v.items()}) - r["global"].update({f"proxy_{k}": x for k, x in d["global"].items()}) - r["proxy_matrix"] = px["C"] - r["_mesh"] = px.get("mesh") or {} - out[p] = r - out["far"] = far - return out - - -# ------------------------------------------------------------------ models -@dataclass -class FinalModel: - name: str - recipe: str - pair: tuple - c_kind: dict = field(default_factory=dict) - scaling: dict | None = None - nets: list = field(default_factory=list) - files_sha256: list = field(default_factory=list) - entry: dict = field(default_factory=dict) - - -def _sha(f) -> str: - return hashlib.sha256(Path(f).read_bytes()).hexdigest() - - -def _paths(reg, name: str, model_dir=None) -> tuple[str, Path | None]: - """("export", dir) for an exported model (//info.json: Space bundle) or ("source", path) for the - training artefacts named in the registry (repository checkout).""" - m = reg["final_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(): - return "export", Path(md) / name - if m.get("source"): - return "source", reg.root / m["source"] - return "none", None - - -_CACHE: dict = {} - - -def load_model(name: str, registry=None, model_dir=None) -> FinalModel: - reg = registry or load_registry() - key = (str(reg.path), name, str(os.environ.get("TLSQ_MODEL_DIR") if model_dir is None else model_dir)) - if key in _CACHE: - return _CACHE[key] - m = reg["final_models"][name] - recipe, pair = m["recipe"], tuple(float(x) for x in m["pair"]) - fm = FinalModel(name, recipe, pair, entry={"name": name, **m}) - kind, p = _paths(reg, name, model_dir) - if recipe == "E1": - f = p / "info.json" if kind == "export" else p - fm.c_kind = json.loads(Path(f).read_text())["c_kind"] - fm.files_sha256 = [_sha(f)] - elif recipe == "E3": - import torch - lo = pair[0] - if kind == "export": - info = json.loads((p / "info.json").read_text()) - files = [p / f for f in info["files"]] - states = [torch.load(f, map_location="cpu", weights_only=True) for f in files] - else: - info = json.loads((p / f"info_p{lo:g}.json").read_text()) - files = [p / f"s{s}_p{lo:g}.pt" for s in (0, 1, 2)] - states = [torch.load(f, map_location="cpu", weights_only=False)["state"] for f in files] - fm.c_kind = info["c_kind"] - fm.scaling = {k: np.asarray(v) for k, v in info["scaling"].items()} - assert list(info.get("edge_keys", EM.EDGE_KEYS)) == list(EM.EDGE_KEYS), f"{name}: edge keys differ from the package" - for st in states: - net = EM.make_model(len(EM.EDGE_KEYS)) - net.load_state_dict(st) - net.eval() - fm.nets.append(net) - fm.files_sha256 = [_sha(f) for f in files] - elif recipe != "C0": - raise ValueError(f"{name}: unknown recipe {recipe!r}") - _CACHE[key] = fm - return fm - - -def export_model(name: str, dst, registry=None) -> list[str]: - """Weights-only export of a final model into dst (Space bundle / model repo): info.json (+ seed.pt state dicts).""" - import torch - reg = registry or load_registry() - fm = load_model(name, reg, model_dir="") - dst = Path(dst) - dst.mkdir(parents=True, exist_ok=True) - m = reg["final_models"][name] - info = {"name": name, "recipe": fm.recipe, "pair": list(fm.pair), "c_kind": fm.c_kind, "ledger_id": m.get("ledger_id"), - "role": m.get("role"), "package_version": __version__, "source_sha256": fm.files_sha256, "files": []} - if fm.recipe == "E3": - info["scaling"] = {k: np.asarray(v).tolist() for k, v in fm.scaling.items()} - info["edge_keys"] = list(EM.EDGE_KEYS) - for k, net in enumerate(fm.nets): - torch.save({k_: v.clone() for k_, v in net.state_dict().items()}, dst / f"seed{k}.pt") - info["files"].append(f"seed{k}.pt") - (dst / "info.json").write_text(json.dumps(info, indent=1)) - return ["info.json"] + info["files"] - - -# ------------------------------------------------------------------ prediction on rows (tm_final.score_em) -def predict_rows(model: FinalModel, pairs: list, seeds: bool = False): - """pairs: [(row_lo, row_hi)] at model.pair. Returns a list of (n, n) log|C_ij| matrices (diagonal NaN), in the order of - the rows; seeds=True also returns the per-seed E3 matrices (S, n, n) per design (None for C0 / E1). One batch, as - tm_final (E3: one pack of all rows; the padding is max(8, max n)).""" - out, per_seed = [], [] - if model.recipe == "E3": - items = [EM.item(rl, rh) for rl, rh in pairs] - d = EM.pack(items) - d["E"] = EM.apply_scale(d["E"], d["A"], model.scaling) - cvec = np.array([0.0] + [model.c_kind[k] for k in EM.KIND_ID], np.float32) - P = np.asarray([EM.predict(net, d, np.arange(len(items)), cvec) for net in model.nets]) - Pm = np.mean(P, 0) - for b, (rl, rh) in enumerate(pairs): - nm = list(rh["names"]) - n = len(nm) - LR, _ = EM.logR(rl, rh) - L = np.full((n, n), np.nan) - for i in range(n): - for j in range(i + 1, n): - if model.recipe == "E3": - v = float(Pm[b, i, j]) - elif model.recipe == "E1": - v = float(LR[i, j] + model.c_kind[EM.entry_kind(nm[i], nm[j])]) - else: - v = float(LR[i, j]) - L[i, j] = L[j, i] = v - out.append(L) - per_seed.append(P[:, b, :n, :n] if model.recipe == "E3" else None) - return (out, per_seed) if seeds else out - - -def pair_distance_um(metals: list, pairs) -> dict: - """{(i, j): exact polygon distance (um)} for the given pairs: the paper's pair distance (scripts/grid_scaling.pair_distances, - the near / far slices of the test tables; ground pairs included).""" - import shapely - return {(i, j): float(shapely.distance(metals[i], metals[j])) for i, j in pairs} - - -def seed_spread(seeds: np.ndarray, row: dict, near_um: float | None = NEAR_UM, dist: dict | None = None) -> tuple[float, np.ndarray]: - """Trust statistic of tm_final (TRUST): median seed std over the near graph entries (pairs with an edge and a pair distance - below near_um: dist = pair_distance_um, else the edge feature's sampled minimum distance; near_um=None: every graph edge, - the convention of rows without a pair distance); returns (s, near mask).""" - n = len(row["names"]) - near = np.zeros((n, n), bool) - for (a, b), f in row["edges"].items(): - d = dist[(a, b)] if dist is not None else np.exp(f["log_dmin"]) - if near_um is None or d < near_um: - near[a, b] = near[b, a] = True - sd = seeds.std(0)[:n, :n] - return (float(np.median(sd[near])) if near.any() else float("inf")), near - - -def apply_trust(L: np.ndarray, seeds: np.ndarray, LR: np.ndarray, row: dict, near_um: float | None = NEAR_UM, - dist: dict | None = None) -> tuple[np.ndarray, dict]: - """Trust rule (TRAINING_PLAN Amendment Trust rule; tm_final TRUST, tau fixed before unblinding): s = seed spread over the near - graph entries. s <= TAU: E3 (L) on the near entries, C0 (LR) on every other entry; s > TAU: C0 on every entry. Returns the - log|C| matrix and the trust record.""" - s, near = seed_spread(seeds, row, near_um, dist) - use = s <= TAU - out = np.where(use & near, L, LR) - np.fill_diagonal(out, np.nan) - rec = {"seed_spread": s, "tau": TAU, "exceeds_tau": bool(s > TAU), "applied": True, "fallback_to_C0": not use, - "used": "E3 on near entries, C0 elsewhere" if use else "C0 (seed spread above tau)", - "near_um": near_um, "n_near_entries": int(np.triu(near, 1).sum()), - "n_E3_entries": int(np.triu(near, 1).sum()) if use else 0} - return out, rec - - -# ------------------------------------------------------------------ layout -> Maxwell matrix -def model_names(registry=None) -> list[str]: - reg = registry or load_registry() - return [k for k, v in (reg.data.get("final_models") or {}).items() if v.get("status", "available") == "available"] - - -def available(name: str, registry=None, model_dir=None) -> bool: - reg = registry or load_registry() - m = reg["final_models"][name] - if m["recipe"] == "C0": - return True - kind, p = _paths(reg, name, model_dir) - if kind == "export": - return True - if kind == "none": - return False - return p.exists() and (m["recipe"] == "E1" or all((p / f"s{s}_p{float(m['pair'][0]):g}.pt").exists() for s in (0, 1, 2))) - - -def predict_final(prepared: PreparedLayout, model: str | None = None, substrate="Si (cryogenic, training)", thickness_um: float = 350.0, - self_from_rows: bool = True, names: list[str] | None = None, registry=None, model_dir=None, mesh: str = "loc", - trust_rule: bool | None = None, trust_near_um: float | None = NEAR_UM, return_debug: bool = False) -> dict: - """Maxwell capacitance matrix (fF) of a prepared layout with a final recipe (registry final_models; default - final_defaults.model). names: entry-kind names (default G, N, S, P1, ...: the deployment convention). Self terms: row - sums / (1 - row_sum_eps) (not trained, not scored) when self_from_rows, else not returned (null). trust_rule (E3 recipes): - the paper's seed-spread rule (apply_trust); None = registry final_defaults.trust_rule (on), False = raw E3 (spread still - reported). trust_near_um: near = graph pairs whose polygon distance (the paper's pair distance) is below this; None = every - graph pair.""" - reg = registry or load_registry() - if trust_rule is None: - trust_rule = bool(reg["final_defaults"].get("trust_rule", True)) - model = model or reg["final_defaults"]["model"] - if model not in (reg.data.get("final_models") or {}): - raise ValueError(f"unknown final model {model!r}; available: {model_names(reg)}") - t_all = time.perf_counter() - timing: dict = {} - t = time.perf_counter() - fm = load_model(model, reg, model_dir) - timing["load_s"] = time.perf_counter() - t - eps, t_um = reg.eps_of(substrate), float(thickness_um) - sub, sub_w = SUB.route(eps, t_um, physics_only=(fm.recipe == "C0")) - metals = [prepared.ground] + list(prepared.conductors) - k = len(metals) - nm = list(names) if names is not None else internal_names(k - 1) - lo, hi = fm.pair - need = sorted({lo, hi} | ({1.5, 3.0} if trust_rule and fm.recipe == "E3" else set())) - rows = build_rows(metals, nm, need, features=(fm.recipe == "E3"), mesh=mesh, timing=timing, stack=(eps, t_um)) - for p in need: - mut = -np.asarray(rows[p]["proxy_matrix"])[np.triu_indices(k, 1)] - if not np.all(np.isfinite(mut)) or np.any(mut <= 0): - raise PriorError(f"the slab lite prior at {p:g} panels per gap returned {int((~np.isfinite(mut)).sum())} non-finite and " - f"{int((mut <= 0).sum())} non-positive mutual entries on this layout: no matrix is returned") - t = time.perf_counter() - L, S = predict_rows(fm, [(rows[lo], rows[hi])], seeds=True) - L, S = L[0], S[0] - timing["network_s" if fm.recipe == "E3" else "recipe_s"] = time.perf_counter() - t - debug = {"rows": rows, "logC": L.copy()} - trust = None - if fm.recipe == "E3": - dist = pair_distance_um(metals, rows[hi]["edges"]) if trust_near_um is not None else None - if trust_rule: - L, trust = apply_trust(L, S, EM.logR(rows[1.5], rows[3.0])[0], rows[hi], trust_near_um, dist) - else: - s, near = seed_spread(S, rows[hi], trust_near_um, dist) - trust = {"seed_spread": s, "tau": TAU, "exceeds_tau": bool(s > TAU), "applied": False, "fallback_to_C0": False, - "used": "E3 everywhere (trust rule switched off)", "near_um": trust_near_um, "n_near_entries": int(np.triu(near, 1).sum())} - Cabs = np.exp(L) - M = -Cabs - e_rs = float(reg["self_capacitance"]["row_sum_eps"]) - for i in range(k): - M[i, i] = np.nan - if self_from_rows: - for i in range(1, k): - M[i, i] = sum(Cabs[i, j] for j in range(k) if j != i) / (1 - e_rs) - timing["total_s"] = time.perf_counter() - t_all - timing["threads"] = int(_mom.NUM_THREADS or 0) or None - labels = ["G"] + list(prepared.names) - iu = np.triu_indices(k, 1) - mut = np.abs(M[iu]) - m = fm.entry - acc = m.get("accuracy") or {} - warnings = list(prepared.warnings) - far = rows["far"] - if far.any(): - warnings.append(f"{int(np.triu(far, 1).sum())} conductor pairs farther apart than {SPARSE_R_GAPS:g} smallest gaps have no pair " - "tokens (large layout); their entries carry the prior's long-range value (aF scale, weakest entries)") - if trust and trust["exceeds_tau"]: - warnings.append(f"trust rule: seed spread {trust['seed_spread']:.3g} > tau {TAU:g}: " - + ("fell back to the physics-only C0 recipe for this whole layout" if trust["applied"] else - "the rule (switched off here) would use the physics-only C0 recipe for this layout")) - warnings += sub_w - mesh_info = {p: rows[p]["_mesh"] for p in need} - out = {"names": labels, "matrix_fF": [[None if np.isnan(v) else float(v) for v in row] for row in M], "units": "fF", - "convention": "Maxwell matrix: diagonal = self, off-diagonal = -mutual; row/column 0 = ground (self not predicted)", - "self_capacitance": (f"row sums / (1 - {e_rs}); not trained, not scored" if self_from_rows else "not returned"), - "model": model, "model_title": m.get("title"), "recipe": fm.recipe, "pair": list(fm.pair), "role": m.get("role"), - "ledger_id": m.get("ledger_id"), "weights_sha256": fm.files_sha256, "package_version": __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}, "kind_names": nm, "timing_s": timing, - "prior_mesh": {f"{p:g}": {kk: v for kk, v in mi.items() if kk in ("prior", "local", "min_gap_um", "h_min_um", "panels", "n_windows")} - for p, mi in mesh_info.items()}, - "accuracy": acc, "expected_error": {}, "trust": trust, "far_mask": far.tolist() if far.any() else None, - "warnings": warnings, "stored": False} - if m.get("warning"): - out["warnings"].insert(0, m["warning"]) - if return_debug: - out["debug"] = debug - return out diff --git a/tlsq_infer/layout.py b/tlsq_infer/layout.py deleted file mode 100644 index 0075dd306e38ec92d4972d40c98284e95fa28fd9..0000000000000000000000000000000000000000 --- a/tlsq_infer/layout.py +++ /dev/null @@ -1,514 +0,0 @@ -"""GDS reading and layout preparation: layers -> ground net + conductor bodies (full ground by default; optional crop window).""" - -from __future__ import annotations - -import tempfile -from dataclasses import dataclass, field -from pathlib import Path - -import gdstk -import numpy as np -import shapely -from shapely.geometry import Polygon - -from ._vendor.scene import _valid - -GROUND = (1, 0) -CONDUCTOR = (1, 10) -N_VALIDATED_SIGNALS = 7 # largest conductor count (plus ground) seen in training and validation -N_MAX_SIGNALS = 30 # practical cap for the free Space (MoM cost); the networks themselves have no limit -AUTO_GAPS, AUTO_FRAC, AUTO_MIN_UM = 100.0, 0.5, 150.0 # margin="auto" (see deploy/LIMITS.md: crop study) # the networks are dense over at most 8 conductors including ground - -# Figure colours = the paper's (MetBrewer Archambault, Hokusai2, OKeeffe1; paper_v4/ml_paper_2026/figures/scripts/_style.py) -GROUND_COLOR = "#D9D9D9" -CONDUCTOR_COLORS = ("#AB3329", "#F9D14A", "#381A61", "#88A0DC", "#E78429", "#7C4B73", "#ED968C") -LIGHT_GOLD = "#F9D14A" # large conductors only: thin ones skip it -WINDOW_COLOR = "#381A61" -UNMODELLED_COLOR = "#6B200C" -INK = "#111827" - - -def conductor_colors(areas) -> list[str]: - """The paper's per-conductor cycle; a conductor smaller than the median area skips light gold.""" - med = float(np.median(areas)) if len(areas) else 0.0 - out, i = [], 0 - for a in areas: - if CONDUCTOR_COLORS[i % len(CONDUCTOR_COLORS)] == LIGHT_GOLD and a < med: - i += 1 - out.append(CONDUCTOR_COLORS[i % len(CONDUCTOR_COLORS)]) - i += 1 - return out - - -def _luminance(hex_color: str) -> float: - lin = [(c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4) for c in (int(hex_color[j:j + 2], 16) / 255 for j in (1, 3, 5))] - return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2] - - -def text_color(hex_color: str) -> str: - """White or ink, whichever has the higher WCAG contrast on the fill.""" - lum = _luminance(hex_color) - return "white" if 1.05 / (lum + 0.05) >= (lum + 0.05) / (_luminance(INK) + 0.05) else INK - - -class LayoutError(ValueError): - """The layout cannot be turned into a valid capacitance problem (message says why and what to change).""" - - -def _top_cell(lib, cell: str | None): - if cell is not None: - for c in lib.cells: - if c.name == cell: - return c - raise LayoutError(f"cell {cell!r} not in the file (cells: {[c.name for c in lib.cells][:20]})") - tops = lib.top_level() - if not tops: - raise LayoutError("the GDS file has no cells") - if len(tops) == 1: - return tops[0] - # several top cells: take the one with the most (flattened) polygons - return max(tops, key=lambda c: len(c.get_polygons())) - - -def read_polygons(path, cell: str | None = None) -> tuple[dict, float, str]: - """{(layer, datatype): [shapely Polygon in µm, ...]} in file order, with references and paths flattened.""" - try: - lib = gdstk.read_gds(str(path)) - except Exception as e: # noqa: BLE001 - raise LayoutError(f"not a readable GDS file: {e}") from e - top = _top_cell(lib, cell) - u = lib.unit / 1e-6 - # flat cells (the training files): direct polygons in file order, which fixes the conductor order of the paper; - # otherwise everything is flattened (references, repetitions, paths) - polys = list(top.polygons) if not (top.references or top.paths) else top.get_polygons(apply_repetitions=True, include_paths=True) - out: dict = {} - for p in polys: - if len(p.points) < 3: - continue - out.setdefault((p.layer, p.datatype), []).append(Polygon(p.points * u)) - return out, u, top.name - - -def load_gds(path, layer_map: dict | None = None, cell: str | None = None) -> list[dict]: - """Detected (layer, datatype) pairs with polygon count, area (µm²) and bounding box (µm), plus a suggested role - (ground / conductor / ground+conductor / ignore) from `layer_map` ({"ground": [(1, 0)], "conductor": [(1, 10)]} by default; - a single-layer file without them gets "ground+conductor").""" - layer_map = layer_map or {"ground": [GROUND], "conductor": [CONDUCTOR]} - lm = {tuple(k): role for role, ks in layer_map.items() for k in ks} - polys, _, top = read_polygons(path, cell) - if len(polys) == 1 and not set(lm) <= set(polys): - lm = {k: "ground+conductor" for k in polys} # one metal layer: ground detected among its pieces (prepare) - rows = [] - for (l, d), ps in sorted(polys.items()): - b = shapely.union_all(ps).bounds if ps else (np.nan,) * 4 - rows.append({"layer": l, "datatype": d, "n_polygons": len(ps), "area_um2": float(sum(p.area for p in ps)), - "bbox_um": tuple(float(x) for x in b), "role": lm.get((l, d), "ignore"), "cell": top}) - return rows - - -def _components(polys: list) -> list[list[int]]: - """Connected components (touching or overlapping polygons) as lists of polygon indices, ordered by first index.""" - n = len(polys) - parent = list(range(n)) - - def find(a): - while parent[a] != a: - parent[a] = parent[parent[a]] - a = parent[a] - return a - - if n > 1: - tree = shapely.STRtree(polys) - ii, jj = tree.query(polys, predicate="intersects") - for a, b in zip(ii, jj): - ra, rb = find(int(a)), find(int(b)) - if ra != rb: - parent[max(ra, rb)] = min(ra, rb) - groups: dict = {} - for i in range(n): - groups.setdefault(find(i), []).append(i) - return sorted(groups.values(), key=lambda g: g[0]) - - -def _core_bounds(G, bodies: list, warnings: list) -> tuple: - """Bounds of the conductors together with the etched pocket(s) that contain them, so that cropping never cuts into the - ground edge facing the conductors. Open regions (the etch reaches the outer boundary of the metal) and very large - pockets (e.g. a CPW gap running across the chip) fall back to the conductors' own bounds.""" - S = shapely.union_all(bodies) - sb = S.bounds - outer = shapely.box(*shapely.union_all([G, S]).bounds) - etched = outer.difference(G) - parts = [p for p in getattr(etched, "geoms", [etched]) if p.intersects(S)] - if not parts: - return sb - P = shapely.union_all(parts) - pb = P.bounds - ob = outer.bounds - open_ = any(abs(a - b) < 1e-6 for a, b in zip(pb, ob)) - big = (pb[2] - pb[0]) * (pb[3] - pb[1]) > 25 * max((sb[2] - sb[0]) * (sb[3] - sb[1]), 1e-9) - if open_ or big: - if big and not open_: - warnings.append("the etched region around the conductors is large (> 25x their bounding box); window built " - "around the conductors only: check the crop in the preview") - return sb - return (min(sb[0], pb[0]), min(sb[1], pb[1]), max(sb[2], pb[2]), max(sb[3], pb[3])) - - -RECT_FILL, AREA_RATIO_LOW = 0.95, 2.0 # ground detection: near-rectangular outline; top-2 piece areas within this ratio = low confidence - - -def _shell(g): - """The piece with its openings filled (outer boundary only).""" - return shapely.union_all([Polygon(p.exterior) for p in getattr(g, "geoms", [g]) if p.geom_type == "Polygon"]) - - -def detect_ground(geoms: list) -> tuple[list[int], str, str]: - """(ground piece indices, reason, confidence) for metal pieces that share one layer. Ground = the piece whose openings - contain every other piece; else the largest near-rectangular piece touching the layout bounding box; else the largest.""" - n = len(geoms) - areas = [float(g.area) for g in geoms] - shells = [_shell(g) for g in geoms] - enc = [i for i in range(n) if all(shells[i].contains(geoms[j]) for j in range(n) if j != i)] - if len(enc) == 1: - k, why = enc[0], "it encloses every other piece (they sit in its openings)" - else: - B = shapely.union_all(geoms).bounds - tol = 1e-6 * max(B[2] - B[0], B[3] - B[1]) - - def rect_edge(i): - with np.errstate(divide="ignore", invalid="ignore"): # GEOS warns on axis-aligned rectangles; the envelope is still right - fill = shells[i].area / max(shells[i].minimum_rotated_rectangle.area, 1e-30) - return fill >= RECT_FILL and any(abs(a - b) <= tol for a, b in zip(shells[i].bounds, B)) - - cand = [i for i in range(n) if rect_edge(i)] - if cand: - k = max(cand, key=lambda i: areas[i]) - why = "no piece encloses all the others; it is the largest near-rectangular piece on the layout boundary" - else: - k = max(range(n), key=lambda i: areas[i]) - why = "no piece encloses all the others and none is a near-rectangular piece on the layout boundary; it is the largest" - top = sorted(areas, reverse=True) - close = n > 1 and top[0] < AREA_RATIO_LOW * top[1] - conf = "high" if len(enc) == 1 and not close else "low" - if close: - why += f"; the two largest pieces are within {AREA_RATIO_LOW:g}x in area" - return [k], why, conf - - -@dataclass -class PreparedLayout: - ground: object # shapely geometry (µm), cropped - conductors: list # shapely geometries (µm), one per net, file order - names: list[str] - window: tuple | None # (x0, y0, x1, y1) µm, or None when not cropped - min_gap_um: float - source: str = "" - warnings: list[str] = field(default_factory=list) - extra_metal: dict = field(default_factory=dict) # label -> geometry of metal inside the window that is not modelled - info: dict = field(default_factory=dict) - pieces: list = field(default_factory=list) # metal pieces (shapely, µm) when ground and conductors share a layer; piece #k = pieces[k - 1] (conductor Ck) - - @property - def n_conductors(self) -> int: - return len(self.conductors) - - def extent_um(self) -> float: - """Lateral size L of the conductors: diagonal of their joint bounding box (µm).""" - x0, y0, x1, y1 = shapely.union_all(self.conductors).bounds - return float(np.hypot(x1 - x0, y1 - y0)) - - def to_gds(self, path=None) -> bytes: - """Simplified GDS in the training convention: ground on (1, 0), one or more polygons per conductor on (1, 10). - Returns the bytes (and writes them when `path` is given).""" - lib = gdstk.Library(unit=1e-6, precision=1e-9) - cell = lib.new_cell("PREPARED") - - def add(g, layer, dt): - for poly in getattr(g, "geoms", [g]): - if poly.is_empty: - continue - if len(poly.interiors) == 0: - cell.add(gdstk.Polygon(np.asarray(poly.exterior.coords)[:-1], layer=layer, datatype=dt)) - else: # polygons with holes: boolean in gdstk keeps them as keyhole polygons - outer = gdstk.Polygon(np.asarray(poly.exterior.coords)[:-1]) - holes = [gdstk.Polygon(np.asarray(r.coords)[:-1]) for r in poly.interiors] - for p in gdstk.boolean(outer, holes, "not", layer=layer, datatype=dt): - cell.add(p) - - add(self.ground, *GROUND) - for g in self.conductors: - add(g, *CONDUCTOR) - if path is None: - with tempfile.TemporaryDirectory() as d: - lib.write_gds(Path(d) / "prepared.gds") - return (Path(d) / "prepared.gds").read_bytes() - lib.write_gds(str(path)) - return Path(path).read_bytes() - - def plot(self, ax=None, **kwargs): - """Draw the layout: ground grey, conductors coloured and named as the predictions name them. ``prepare_layout(gds).plot()``; - keyword arguments as ``render`` (labels, show_window, title, figsize, compact). Returns the matplotlib Axes.""" - fig = self.render(ax=ax, **kwargs) - return ax if ax is not None else fig.axes[0] - - def render(self, ax=None, show_window: bool = True, title: str | None = None, figsize=(6.4, 6.4), compact: bool = False, - labels=None): - """Matplotlib figure: ground (grey), conductors (coloured, labelled), unmodelled metal (hatched), window. When ground and - conductors share a layer, conductor piece #k is labelled Ck and ground pieces "G #k" (the numbers ground_pieces takes); - compact = smaller labels; labels = {name: text} renames conductors on the figure (e.g. {"C1": "star"}), False hides them.""" - import matplotlib.pyplot as plt - from matplotlib.patches import PathPatch, Rectangle - from matplotlib.path import Path as MPath - - def patch(g, **kw): - for poly in getattr(g, "geoms", [g]): - if poly.is_empty or poly.geom_type != "Polygon": - continue - verts, codes = [], [] - for ring in [poly.exterior, *poly.interiors]: - xy = np.asarray(ring.coords) - verts += list(xy) - codes += [MPath.MOVETO] + [MPath.LINETO] * (len(xy) - 2) + [MPath.CLOSEPOLY] - ax.add_patch(PathPatch(MPath(verts, codes), **kw)) - - if ax is None: - fig, ax = plt.subplots(figsize=figsize) - else: - fig = ax.figure - patch(self.ground, facecolor=GROUND_COLOR, edgecolor="#8c8c8c", lw=0.4) - gd = self.info.get("ground_detection") - fs = 8 if compact else 11 - for g, nm, col in zip(self.conductors, self.names, conductor_colors([g.area for g in self.conductors])): - patch(g, facecolor=col, edgecolor="black", lw=0.4) - p = g.representative_point() if g.area > 0 else g.centroid - if labels is not False: - ax.annotate((labels or {}).get(nm, nm), (p.x, p.y), ha="center", va="center", fontsize=fs, weight="bold", - color=text_color(col), bbox=dict(boxstyle="round,pad=0.2", fc=col, ec="black", lw=0.6)) - for r in (gd or {}).get("pieces", []): - if r["role"] != "conductor": - x, y = r["label_xy"] - ax.annotate(f"{'G' if r['role'] == 'ground' else 'not modelled'} #{r['id']}", (x, y), ha="center", va="center", - fontsize=fs, weight="bold", color=INK, bbox=dict(boxstyle="round,pad=0.2", fc="#e5e7eb", ec="#374151", lw=0.6)) - for lab, g in self.extra_metal.items(): - patch(g, facecolor="none", edgecolor=UNMODELLED_COLOR, hatch="///", lw=0.6) - if show_window and self.window is not None: - x0, y0, x1, y1 = self.window - ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False, ls="--", ec=WINDOW_COLOR, lw=1.0)) - b = shapely.union_all([self.ground, *self.conductors]).bounds - pad = 0.03 * max(b[2] - b[0], b[3] - b[1]) - ax.set_xlim(b[0] - pad, b[2] + pad) - ax.set_ylim(b[1] - pad, b[3] + pad) - ax.set_aspect("equal") - ax.set_xlabel("x (µm)") - ax.set_ylabel("y (µm)") - if title is None and gd: - title = (f"ground = piece {', '.join(f'#{i}' for i in gd['ground_pieces'])} ({gd['method']}, confidence {gd['confidence']}); " - f"{len(self.conductors)} conductors") - ax.set_title(title or f"{len(self.conductors)} conductors + ground; min gap {self.min_gap_um:.2f} µm", fontsize=10) - return fig - - -def prepare(path, ground_layers=(GROUND,), conductor_layers=(CONDUCTOR,), margin_gaps: float | str | None = None, - margin_um: float | None = None, ignore_layers=(), cell: str | None = None, select=None, select_box=None, - max_conductors: int = N_MAX_SIGNALS, ground_pieces=None) -> PreparedLayout: - """Extract the capacitance problem from a GDS file. - - - conductors: connected bodies of the conductor-layer polygons (touching/overlapping polygons are one net), in file - order; bodies that touch the ground metal are shorted to it and merged into the ground net (warning). - - ground: union of the ground-layer polygons. Default (margin_gaps=None, margin_um=None): no crop, the training - geometry (tlsq.uge.scene.scene_from_gds; TRAINING_PLAN Addendum R5; default since 2026-10-14). Optional crop to the - window = bbox(conductors + the etched pocket that contains them) expanded by `margin_um` if given, else `margin_gaps` - x (smallest conductor-to-ground gap), or ("auto") by max(100 gaps, half the conductor extent, 150 µm) (deploy/LIMITS.md). - - select: optional list of conductor-body indices (0-based, file order), or select_box = (x0, y0, x1, y1) µm (bodies - fully inside); the other bodies are not modelled and are flagged as extra metal when they fall inside the window. - - metal on layers that are neither ground, conductor nor in `ignore_layers` is flagged when inside the window. - - ground and conductors on one layer (ground_layers == conductor_layers, or a file with a single metal layer while the default - layers 1/0 and 1/10 are not both present): the layer's metal is split into connected pieces and the ground is detected - (detect_ground; result and confidence in info["ground_detection"], plus a warning). Pieces are numbered with the - automatically detected ground last and the others in file order, and conductor piece #k is named Ck, so the automatic - split names its conductors as the two-layer file does and names stay put when roles change. ground_pieces = piece - numbers (as in render()) overrides the pick; several pieces make one ground net. - """ - gl = {tuple(x) for x in ground_layers} - cl = {tuple(x) for x in conductor_layers} - il = {tuple(x) for x in ignore_layers} - if gl & cl and gl != cl: - raise LayoutError(f"layers {sorted(gl & cl)} are assigned both ground and conductor (assign the same layers to both to detect " - "the ground automatically)") - polys, _, top = read_polygons(path, cell) - warnings: list[str] = [] - metal = [k for k in polys if k not in il] - shared = None - if gl == cl: - shared = gl - elif gl == {GROUND} and cl == {CONDUCTOR} and len(metal) == 1 and not (GROUND in polys and CONDUCTOR in polys): - shared = set(metal) - if shared is None and ground_pieces is not None: - raise LayoutError("ground_pieces applies only when ground and conductors share one layer (the same ground and conductor " - "layers, or a single-layer file)") - pieces, gdet = [], None - if shared is not None: - gl = cl = shared - allp = [p for k in polys if k in shared for p in polys[k]] - if not allp: - raise LayoutError(f"no polygons on {sorted(shared)}; detected layers: {sorted(polys)}") - val = [_valid(p) for p in allp] - ok = [i for i, g in enumerate(val) if not g.is_empty and g.area > 0] - comps = [[ok[j] for j in c] for c in _components([val[i] for i in ok])] - pieces = [val[c[0]] if len(c) == 1 else _valid(shapely.union_all([val[i] for i in c])) for c in comps] - if len(pieces) < 2: - raise LayoutError(f"the metal on {sorted(shared)} is one connected piece: no floating conductor to compute") - auto, why, conf = detect_ground(pieces) - order = [i for i in range(len(pieces)) if i not in auto] + auto - pieces, comps = [pieces[i] for i in order], [comps[i] for i in order] - if ground_pieces is None: - gids, method = list(range(len(pieces) - len(auto), len(pieces))), "automatic" - else: - try: - gp = [x for x in ground_pieces.split(",") if x.strip()] if isinstance(ground_pieces, str) else list(ground_pieces) - gids = sorted({int(i) - 1 for i in gp}) - except (TypeError, ValueError) as e: - raise LayoutError(f"ground_pieces must be piece numbers such as [1] or '1,4' (got {ground_pieces!r})") from e - bad = [i + 1 for i in gids if not 0 <= i < len(pieces)] - if bad or not gids: - raise LayoutError(f"ground_pieces {bad or list(ground_pieces)} not valid: this layout has pieces 1..{len(pieces)} " - "(numbers as in the labelled figure)") - if len(gids) == len(pieces): - raise LayoutError("ground_pieces lists every piece: at least one piece must be a conductor") - why, conf, method = f"set by ground_pieces={[i + 1 for i in gids]}", "user", "user" - gset = {i for g in gids for i in comps[g]} - gpolys = [allp[i] for i in sorted(gset)] - cpolys = [allp[i] for i in range(len(allp)) if i not in gset] - lay_s = ", ".join(f"{k[0]}/{k[1]}" for k in sorted(shared)) - ids = ", ".join(f"#{g + 1}" for g in gids) - if method == "automatic": - warnings.append(f"ground and conductors share layer {lay_s}: the ground was detected automatically as piece {ids} ({why}; " - f"confidence {conf}). Check the numbered figure of the pieces and, if it is wrong, resubmit with " - "ground_pieces=[piece numbers].") - else: - warnings.append(f"ground and conductors share layer {lay_s}: ground = piece {ids} (set by ground_pieces)") - gdet = {"layers": [list(k) for k in sorted(shared)], "method": method, "ground_pieces": [g + 1 for g in gids], "reason": why, - "confidence": conf, "n_pieces": len(pieces)} - else: - gpolys = [p for k in polys if k in gl for p in polys[k]] - cpolys = [p for k in polys if k in cl for p in polys[k]] - if not gpolys: - raise LayoutError(f"no ground polygons on {sorted(gl)}; detected layers: {sorted(polys)}") - if not cpolys: - raise LayoutError(f"no conductor polygons on {sorted(cl)}; detected layers: {sorted(polys)}") - cvalid = [_valid(p) for p in cpolys] - keep = [i for i, g in enumerate(cvalid) if not g.is_empty and g.area > 0] - if len(keep) < len(cvalid): - warnings.append(f"{len(cvalid) - len(keep)} degenerate conductor polygon(s) (zero area) dropped") - cvalid = [cvalid[i] for i in keep] - G = _valid(shapely.union_all([_valid(g) for g in gpolys])) - bodies = [] - for comp in _components(cvalid): - bodies.append(cvalid[comp[0]] if len(comp) == 1 else _valid(shapely.union_all([cvalid[i] for i in comp]))) - n_merged = len(cvalid) - len(bodies) - if n_merged: - warnings.append(f"{len(cvalid)} conductor polygons form {len(bodies)} connected bodies (touching polygons merged into one net)") - # bodies in contact with ground metal are at ground potential - shorted = [i for i, b in enumerate(bodies) if shapely.intersects(b, G)] - if shorted: - warnings.append(f"{len(shorted)} conductor body(ies) touch the ground metal and were merged into the ground net") - G = _valid(shapely.union_all([G] + [bodies[i] for i in shorted])) - bodies = [b for i, b in enumerate(bodies) if i not in set(shorted)] - if not bodies: - raise LayoutError("every conductor body touches the ground: nothing floating to compute") - all_bodies = bodies - others = [] - if select is not None or select_box is not None: - if select_box is not None: - box = shapely.box(*select_box) - idx = [i for i, b in enumerate(bodies) if box.contains(b)] - else: - idx = [int(i) for i in select] - bad = [i for i in idx if i < 0 or i >= len(bodies)] - if bad: - raise LayoutError(f"select indices {bad} out of range (0..{len(bodies) - 1})") - if not idx: - raise LayoutError("the selection matched no conductor body") - bodies = [all_bodies[i] for i in idx] - others = [all_bodies[i] for i in range(len(all_bodies)) if i not in set(idx)] - if len(bodies) > max_conductors: - raise LayoutError(f"{len(bodies)} conductors found; this server is configured for at most {max_conductors} signal conductors " - "plus ground (a cost cap of the demo, not a limit of the models: pass prepare(max_conductors=...) " - "locally). Use `select` (indices or a box) to pick the conductors of interest.") - if len(bodies) > N_VALIDATED_SIGNALS: - warnings.append(f"{len(bodies)} conductors: beyond the validated range ({N_VALIDATED_SIGNALS} conductors plus ground). " - "The model applies the same pair function to every pair, but accuracy at this size has not been verified.") - metals = [G] + bodies - gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) - if not np.isfinite(gap) or gap <= 0: - raise LayoutError("zero gap between two nets (overlapping metal on different nets)") - window = None - if margin_um is not None or margin_gaps is not None: - gap_cg = min(shapely.distance(G, b) for b in bodies) # conductor-to-ground gap sets the scale of the ground's field - x0, y0, x1, y1 = _core_bounds(G, bodies, warnings) - if margin_um is not None: - m = float(margin_um) - elif margin_gaps == "auto": - # a training-like neighbourhood: the training chips extend ~150-330 µm (30-170 gaps) beyond the conductors - m = max(AUTO_GAPS * gap_cg, AUTO_FRAC * max(x1 - x0, y1 - y0), AUTO_MIN_UM) - else: - m = float(margin_gaps) * gap_cg - window = (x0 - m, y0 - m, x1 + m, y1 + m) - box = shapely.box(*window) - Gc = _valid(shapely.intersection(G, box)) - if Gc.is_empty: - raise LayoutError("no ground metal inside the window; increase the margin") - G = Gc - metals = [G] + bodies - gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals))) - if G.geom_type == "MultiPolygon" and len(G.geoms) > 1: - warnings.append(f"cropped ground consists of {len(G.geoms)} separate pieces (all treated as one net)") - box = shapely.box(*window) if window is not None else shapely.box(*shapely.union_all(metals).bounds) - extra = {} - for k, ps in polys.items(): - if k in gl or k in cl or k in il: - continue - inside = [p for p in ps if shapely.intersects(p, box)] - if inside: - extra[f"layer {k[0]}/{k[1]}"] = shapely.union_all([_valid(p) for p in inside]) - for i, b in enumerate(others): - if shapely.intersects(b, box): - extra.setdefault("unselected conductors", []) - extra["unselected conductors"].append(b) - if "unselected conductors" in extra: - n_un = len(extra["unselected conductors"]) - extra["unselected conductors"] = shapely.union_all(extra["unselected conductors"]) - warnings.append(f"{n_un} unselected conductor body(ies) lie inside the window and are NOT modelled (they would screen the selected ones)") - for lab in extra: - if lab.startswith("layer"): - warnings.append(f"metal on {lab} inside the window is not assigned (ground / conductor) and is ignored") - holes = sum(len(p.interiors) for b in bodies for p in getattr(b, "geoms", [b])) - if holes: - warnings.append(f"conductors contain {holes} hole(s): supported, but outside the training families") - size = max(np.subtract(shapely.union_all(metals).bounds[2:], shapely.union_all(metals).bounds[:2])) - if gap < 3 * size / 4096: - warnings.append(f"smallest gap {gap:.3g} µm is below the MoM resolution floor for a {size:.0f} µm layout " - f"(~{3 * size / 4096:.3g} µm): crop tighter or expect larger errors") - names = [f"C{i + 1}" for i in range(len(bodies))] - if gdet is not None: - gset = set(gdet["ground_pieces"]) - cond = sorted((k for k in range(1, len(pieces) + 1) if k not in gset), key=lambda k: comps[k - 1][0]) # file order = body order - piece_of = dict(zip(map(id, all_bodies), cond)) if len(cond) == len(all_bodies) else {} - names = [f"C{piece_of[id(b)]}" if piece_of else nm for b, nm in zip(bodies, names)] - info = {"cell": top, "margin_um": m if window else None, "n_conductor_polygons": len(cvalid), "n_bodies_total": len(all_bodies), "layout_size_um": float(size), - "extent_um": float(np.hypot(*np.subtract(shapely.union_all(bodies).bounds[2:], shapely.union_all(bodies).bounds[:2])))} - if gdet is not None: - info["ground_detection"] = _detection_info(gdet, pieces, comps, {piece_of[id(b)]: nm for b, nm in zip(bodies, names)} if piece_of else {}) - return PreparedLayout(G, bodies, names, window, float(gap), str(path), warnings, extra, info, pieces) - - -def _detection_info(gdet: dict, pieces: list, comps: list, name_of: dict) -> dict: - """JSON-ready record of the pieces and their roles (name_of: piece number -> conductor name of the modelled conductors).""" - gset = set(gdet["ground_pieces"]) - rows = [] - for i, g in enumerate(pieces, 1): - p = g.representative_point() - role = "ground" if i in gset else "conductor" if i in name_of else "not modelled" - rows.append({"id": i, "role": role, "name": "G" if i in gset else name_of.get(i), "area_um2": round(float(g.area), 3), - "bbox_um": [round(float(x), 3) for x in g.bounds], "n_polygons": len(comps[i - 1]), "label_xy": [float(p.x), float(p.y)]}) - return {**gdet, "pieces": rows} diff --git a/tlsq_infer/localtok.py b/tlsq_infer/localtok.py deleted file mode 100644 index 63eda9be8af482cc8c6eed25ab34b5076963a057..0000000000000000000000000000000000000000 --- a/tlsq_infer/localtok.py +++ /dev/null @@ -1,99 +0,0 @@ -"""Local, window-invariant context tokens (PRIOR_SCHEME.md 14.5 E4; replace the chip / pocket areas): for every signal -conductor and radius R, the fractions of its surrounding annulus (conductor buffered by R, minus the conductor) that are -ground metal, other-conductor metal and etched chip; the rest of the annulus lies outside the chip (no metal). Pair -tokens = mean over the pair's signal ends (a ground pair: its signal end). Identical copy: tlsq.uge.localtok (training).""" - -from __future__ import annotations - -import numpy as np -import shapely -from scipy.spatial import cKDTree - -from ._vendor.blocks import MOMENTS, SEP_EDGES_UM, STEP_UM, _kratio -from ._vendor.geometry import sample_boundary - -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) - for k in sig: - 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] - out[k] = vals - return out - - -LG_R_UM = 100.0 -TOK = ["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) - for k, c in enumerate(conds): - if c.role == "ground": - continue - g = c.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[cKDTree(pj).query(pg)[0] < LG_R_UM] # drops the clip-box edges (>= LG_R_UM away) and the far ground - if not len(pg): - continue - 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 = cKDTree(b_).query(a_)[0] - 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))) - out[k] = [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))] - 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) - 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} diff --git a/tlsq_infer/ood.py b/tlsq_infer/ood.py deleted file mode 100644 index 9252e42fad6153956a478060fc4a7aaea6db0cae..0000000000000000000000000000000000000000 --- a/tlsq_infer/ood.py +++ /dev/null @@ -1,81 +0,0 @@ -"""Out-of-distribution trust gate (GRID_SCALING.md amendment 4, PRIOR_SCHEME.md section 16-OOD). - -Per entry, z = the largest excess of a used feature beyond the training envelope (q0.1-q99.9), in IQR units (global -features; the pair's edge features for a mutual entry, the conductor's node features for a self entry), or the excess of -the seed spread of the network term beyond its training reference. trust a = exp(-(z / 3)^2) is 1 inside the training -envelope; the gated prediction is log P + a * f (f = network log-correction, P = physics prior). -""" - -from __future__ import annotations - -import json -from pathlib import Path - -import numpy as np - -TRUST_Z = 3.0 -WARN_TRUST = 0.5 - - -def find_stats(name: str, reg=None) -> Path | None: - """artifacts/ood/.json (training envelope + seed-spread reference) next to the package or in deploy/, or None.""" - here = Path(__file__).resolve() - for q in [here.parent] + list(here.parents): - for p in (q / "artifacts" / "ood" / f"{name}.json", q / "deploy" / "artifacts" / "ood" / f"{name}.json"): - if p.exists(): - return p - return None - - -def load_stats(name: str, reg=None) -> dict | None: - p = find_stats(name, reg) - return json.loads(p.read_text()) if p else None - - -def _excess(V: np.ndarray, iqr, lo, hi) -> np.ndarray: - """max over features of max(0, x - hi, lo - x) / IQR (NaN features ignored).""" - V, lo, hi, iqr = (np.asarray(a, float) for a in (V, lo, hi, iqr)) - ex = np.maximum(np.maximum(V - hi, lo - V), 0.0) / iqr - return np.nanmax(np.nan_to_num(ex, nan=0.0), axis=-1) - - -def trust(graph: dict, scaling: dict, stats: dict | None, f_seeds: np.ndarray | None) -> dict: - """graph: scene-graph row (nodes / edges / global); scaling: a member's scaling (keys, median / IQR); stats: the model's - OOD artifact (envelope when the checkpoint has none, seed_std_ref); f_seeds: (S, n, n) network term per seed. - Returns {"trust": (n, n), "z": (n, n), "z_global": float}; pairs without an edge get trust 1 (the prior is used).""" - nk, ek, gk = scaling["keys"] - env = (scaling.get("features") or {}).get("envelope") or (stats or {}).get("envelope") - n = len(graph["names"]) - z = np.zeros((n, n)) - if env is not None: - zu = float(_excess(np.array([graph["global"][k] for k in gk]), scaling["global"][1], *env["global"])) - Xn = np.array([[nd[k] for k in nk] for nd in graph["nodes"]], float) - zn = _excess(Xn, scaling["node"][1], *env["node"]) - z[np.arange(n), np.arange(n)] = zn - if graph["edges"]: - pairs = list(graph["edges"]) - En = np.array([[graph["edges"][e][k] for k in ek] for e in pairs], float) - ze = _excess(En, scaling["edge"][1], *env["edge"]) - ii, jj = np.array(pairs).T - z[ii, jj] = z[jj, ii] = ze - z = np.maximum(z, zu) - else: - zu = float("nan") - ref = (stats or {}).get("seed_std_ref") - if ref and f_seeds is not None and len(f_seeds) > 1: - sd = np.std(np.asarray(f_seeds)[:, :n, :n], 0) - r = np.full((n, n), float(ref["edge"])) - np.fill_diagonal(r, float(ref["node"])) - z = np.maximum(z, TRUST_Z * np.maximum(sd - r, 0.0) / r) - if graph["edges"]: - mask = np.zeros((n, n), bool) - ii, jj = np.array(list(graph["edges"])).T - mask[ii, jj] = mask[jj, ii] = True - np.fill_diagonal(mask, True) - z = np.where(mask, z, 0.0) - return {"trust": np.exp(-(z / TRUST_Z) ** 2), "z": z, "z_global": zu} - - -def gate(logP: np.ndarray, log_net: np.ndarray, a: np.ndarray) -> np.ndarray: - """log P + a * (log_net - log P).""" - return logP + a * (log_net - logP) diff --git a/tlsq_infer/predict.py b/tlsq_infer/predict.py deleted file mode 100644 index ebcfb24c1d454dd0b304d1211db6ae76a8315fb4..0000000000000000000000000000000000000000 --- a/tlsq_infer/predict.py +++ /dev/null @@ -1,475 +0,0 @@ -"""Prediction: prepared layout -> MoM prior -> scene graph -> network ensemble (-> charge correction -> blend) -> Maxwell -matrix (fF) for the requested substrate.""" - -from __future__ import annotations - -import time -from pathlib import Path - -import numpy as np - -from . import __version__ -from ._vendor.graph import prior_dict, scene_graph -from ._vendor import mom as _mom -from ._vendor.mom import solve_prior -from ._vendor.scene import make_scene -from .charge import corrected_matrix, corrected_matrix_v3 -from .layout import PreparedLayout -from .registry import PRIORS, get_component, load_registry -from .stack_error import EPS_TRAIN, expected_error, lateral_extent, load_params -from .substrate import on_training_stack -from . import errmodel -from .ood import WARN_TRUST - - -def _internal_names(n_signal: int) -> list[str]: - """Training-convention names fixing the blend entry kinds: first two signal bodies N, S; later bodies are pads.""" - return (["N", "S"] + [f"P{k}" for k in range(1, n_signal - 1)])[:n_signal] - - -def _kind(a: str, b: str) -> str: - if a.startswith("P") or b.startswith("P"): - return "pad" - return "signal-ground" if "G" in (a, b) else "signal-signal" - - -def _kind_invariant(a: str, b: str) -> str: - """Order-invariant entry kind (deploy/MODEL_SELECTION.md amendment 3): independent of the conductor file order.""" - return "conductor-ground" if "G" in (a, b) else "conductor-conductor" - - -def blend_weights(reg, blend_kinds: str | None = None) -> tuple[dict, object]: - """(weights, kind function). blend_kinds: "invariant" (default when the registry provides invariant weights) or - "published" (file-order kinds of the paper; reproduction only).""" - b = reg["blend"] - mode = blend_kinds or b.get("kinds", "published") - if mode == "invariant": - return b["weights_gnn_side_invariant"], _kind_invariant - return b["weights_gnn_side"], _kind - - -def _logC(C: np.ndarray) -> np.ndarray: - n = C.shape[0] - out = np.zeros_like(C) - for i in range(n): - for j in range(n): - out[i, j] = np.log(max(C[i, i], 1e-9)) if i == j else np.log(max(-C[i, j], 1e-9)) - return out - - -TIERS = ("fast", "coarse", "fine") # released tiers (2026-10-10): fast = flagship-fast (cheap micro-MoM prior, default), coarse = one -# gap/3 conductor-anchored solve, fine = flagship prior (Richardson gap/6 + gap/3) -TIER_ALIASES = {"fast": "fast", "coarse": "coarse", "fine": "fine", "accurate": "fine", "flagship-fast": "fast", "default": "fast"} -TIER_KEYS = {"fast": "flagship_model", "coarse": "coarse_model", "fine": "flagship_accurate_model"} -CHEAP_PRIORS = ("lite500", "lite1500", "formula", "liteppg0.375", "liteppg0.75", "liteppg1.5", "liteppg3") # flagship-fast priors: windowed, cost bounded per conductor, never re-routed -REGIME_MIN_CELLS_PER_GAP = 0.75 # training-family priors sit at 0.75-3 panels across the smallest gap (GRID_SCALING.md section 2) -LARGE_LAYOUT_MODEL_KEY = "large_layout_model" # registry defaults: model (flagship prior) that large layouts are routed to - - -class PriorError(ValueError): - """The physics prior produced no usable matrix (zero or non-finite mutual entries).""" - - -def large_layout_model(reg, model: str) -> str | None: - """Model that `model` is re-routed to when its capped prior would fall below the training regime on this layout: - registry defaults.large_layout_model (a flagship-prior model), or None when not configured or already such a model.""" - fb = reg["defaults"].get(LARGE_LAYOUT_MODEL_KEY) - if not fb or fb == model or fb not in reg.models: - return None - if str(reg.model(model).get("prior", "")) in CHEAP_PRIORS: # flagship-fast handles large layouts itself - return None - if str(reg.model(model).get("prior", "")).startswith("flagship"): - return None - return fb - - -def would_hit_cap(metals: list, prior: str) -> tuple[bool, float]: - """Whether the capped v3 / v3-rich mesh of `prior` falls below the training regime on this layout, decided without a - solve: the lattice is coarsened by factors of two until the mesh fits the cap, so it is below the regime exactly when - the mesh at the coarsest lattice level that still has >= REGIME_MIN_CELLS_PER_GAP panels per gap exceeds the cap (one - cheap mesh attempt at that level, stopped at the cap). Returns (below, upper bound on the panels per gap reached).""" - if prior not in ("v3", "v3-rich"): - return False, float("nan") - kw = PRIORS[prior] - cap = kw["max_cells"] * (2 if prior == "v3-rich" else 1) - cpg = kw["cells_per_gap"] * (2 if prior == "v3-rich" else 1) - gap, size = _mom._gap_size(metals) - h = max(gap / cpg, size / 4096) - if gap / h < REGIME_MIN_CELLS_PER_GAP: # the resolution floor alone is below the regime - return True, gap / h - while gap / (2 * h) >= REGIME_MIN_CELLS_PER_GAP: # coarsest lattice level still in the regime - h *= 2.0 - if _mom.anchored_cells(metals, h, 2.0, limit=cap) is None: # does not fit: the capped mesh coarsens below the regime - return True, gap / (2 * h) - return False, float("nan") - - -def tier_of(model: str | None) -> str | None: - """Tier name ("fast" / "coarse" / "fine") of a model argument (None or "" -> "fast", the default), or None for an - explicit registry name.""" - if not model: - return "fast" - return TIER_ALIASES.get(str(model).lower()) - - -def resolve_model(reg, model: str | None) -> str: - """Model name from an explicit registry name or a tier: "fast" (default: flagship-fast), "coarse", "fine" (alias - "accurate").""" - tier = tier_of(model) - if tier is None: - return model - name = reg["defaults"].get(TIER_KEYS[tier]) - if not name: - raise ValueError(f"no {tier}-tier model is configured (defaults.{TIER_KEYS[tier]}); use 'fast'") - return name - - -SPARSE_MIN_CONDUCTORS = 8 # more signal conductors than this: pair tokens only for pairs within SPARSE_R_GAPS (and ground) -SPARSE_R_GAPS = 150.0 - - -def far_pairs(metals: list) -> np.ndarray: - """(N, N) mask of the conductor pairs farther apart than SPARSE_R_GAPS smallest gaps (never the ground): not given - pair tokens on large layouts; their entries are the prior's (PRIOR_SCHEME.md Part III section 16).""" - import shapely - - from ._vendor.fastprior import gap_of - - conds = list(metals[1:]) - a, b = shapely.STRtree(conds).query(conds, predicate="dwithin", distance=SPARSE_R_GAPS * gap_of(list(metals))) - far = np.ones((len(metals), len(metals)), bool) - far[a + 1, b + 1] = False - far[0, :] = far[:, 0] = False - np.fill_diagonal(far, False) - return far - - -def run_pipeline(metals: list, names: list[str], model: str, reg=None, model_dir=None, timing=None, - blend_kinds: str | None = None, ood_gate: bool = False) -> tuple[np.ndarray, dict]: - """Core: log|C| matrix (diag: log C_ii, off-diag: log -C_ij) on the training stack, in `metals` order (0 = ground).""" - reg = reg or load_registry() - m = reg.model(model) - timing = {} if timing is None else timing - kind = m["kind"] - if kind == "blend": - gnn_name, ch_name = m["components"] - prior = reg.model(gnn_name).get("prior", "standard") - else: - prior = m.get("prior", "standard") - debug = {"model": model, "kind": kind} - mom = None - if prior != "none": - t = time.perf_counter() - _mom.STAGE_TIMES.clear() - mom = solve_prior(metals, **PRIORS[prior]) - timing["prior_s"] = time.perf_counter() - t - debug["prior_stage_s"] = dict(_mom.STAGE_TIMES) # v3 priors: mesh / assemble / factor_solve (reporting only) - debug.update(mom_cells=int(mom["n_cells"]), h_min_um=float(mom["h_min"]), prior_matrix=mom["C"], prior_mesh=mom.get("mesh", {}), - prior_coarse_C=mom.get("C_coarse")) - if kind == "prior": - return _logC(mom["C"]), debug - out_gnn = out_corr = None - if kind in ("gnn", "blend"): - gname = model if kind == "gnn" else gnn_name - t = time.perf_counter() - sc = make_scene(metals[0], metals[1:], names[1:]) - prior_fn = (lambda edges: prior_dict(mom["C"], mom["n_cells"], mom["h_min"], edges, - (mom.get("mesh") or {}).get("min_gap_um"))) if mom is not None else None - far = far_pairs(metals) if mom is not None and len(metals) - 1 > SPARSE_MIN_CONDUCTORS else None - from ._vendor import blocks as _blocks - - _blocks.set_token_variant(reg.model(gname).get("tokens", "exact")) # approximate token variants (PRIOR_SCHEME.md 14.3) - try: - g = scene_graph(sc, prior_fn, None if far is None else (lambda i, j: not far[i, j])) - finally: - _blocks.set_token_variant("exact") - g["target"] = np.ones((len(metals), len(metals))) - timing["features_s"] = time.perf_counter() - t - t = time.perf_counter() - ens = get_component(reg, gname, model_dir) - timing["load_s"] = timing.get("load_s", 0.0) + time.perf_counter() - t - if any((m_sc.get("features") or {}).get("local") for _, m_sc in ens.members): # local context tokens (localtok, E4) - from .localtok import add_tokens - t = time.perf_counter() - g = add_tokens(sc, g) - timing["features_s"] = timing.get("features_s", 0.0) + time.perf_counter() - t - t = time.perf_counter() - seeds = ens.member_outputs([g], proxy_key="proxy_log_C" if mom is not None else None)[:, 0, : len(metals), : len(metals)] - out_gnn = np.mean(seeds, 0) - if far is not None and far.any(): # pairs outside the graph: the prior's value (flagged in far_mask) - out_gnn[far] = _logC(mom["C"])[far] - debug["far_mask"] = far - timing["network_s"] = time.perf_counter() - t - debug["seed_logC"] = seeds - if mom is not None: - out_gnn = ood_trust_gate(debug, out_gnn, seeds, _logC(mom["C"]), g, ens, gname, ood_gate) - debug["graph"] = g - if kind in ("charge_prior", "blend"): - cname = model if kind == "charge_prior" else ch_name - t = time.perf_counter() - gbm = get_component(reg, cname, model_dir) - timing["load_s"] = timing.get("load_s", 0.0) + time.perf_counter() - t - cprior = reg.model(cname).get("prior", "standard") # the mesh the cell GBM was fit on - mom_c = mom - if prior != cprior: - t = time.perf_counter() - mom_c = solve_prior(metals, **PRIORS[cprior]) - timing["charge_prior_s"] = time.perf_counter() - t - t = time.perf_counter() - out_corr = _logC(corrected_matrix_v3(gbm, metals, mom_c) if cprior == "v3" else corrected_matrix(gbm, metals, mom_c)) - timing["charge_correction_s"] = time.perf_counter() - t - if kind == "gnn": - return out_gnn, debug - if kind == "charge_prior": - return out_corr, debug - w, kfun = blend_weights(reg, blend_kinds) - out = out_gnn.copy() - for i in range(len(names)): - for j in range(len(names)): - if i != j: - wk = w[kfun(names[i], names[j])] - out[i, j] = wk * out_gnn[i, j] + (1 - wk) * out_corr[i, j] - debug["gnn_logC"], debug["corr_logC"] = out_gnn, out_corr - return out, debug - - -def ood_trust_gate(debug: dict, out_gnn: np.ndarray, seeds: np.ndarray, logP: np.ndarray, g: dict, ens, name: str, - apply: bool) -> np.ndarray: - """Per-entry network trust (GRID_SCALING.md amendment 4; tlsq_infer.ood): recorded in debug["ood_trust"] when the model - has a training envelope; apply=True returns log P + trust * (network - log P), else out_gnn unchanged.""" - from . import ood - - stats = ood.load_stats(name) - sc = ens.members[0][1] - if stats is None and not (sc.get("features") or {}).get("envelope"): - return out_gnn - k = out_gnn.shape[0] - if (sc.get("features") or {}).get("derive"): - from ._vendor.gnn import derive_features - g = derive_features(g) - t = ood.trust(g, sc, stats, np.asarray(seeds)[:, :k, :k] - logP[None]) - debug["ood_trust"], debug["ood_z"] = t["trust"], t["z"] - if not apply: - return out_gnn - debug["ood_gate_applied"] = True - return ood.gate(logP, out_gnn, t["trust"]) - - -def predict(prepared: PreparedLayout, model: str | None = None, substrate="Si (cryogenic, training)", thickness_um: float = 350.0, - self_from_rows: bool = False, registry=None, model_dir=None, return_debug: bool = False, - row_sum_eps: float | None = None, blend_kinds: str | None = None, large_layouts: str = "route", - ood_gate: bool = False) -> dict: - """Maxwell capacitance matrix (fF) of a prepared layout. - - model: a deployable registry name, or a tier: "fast" (default: defaults.flagship_model, flagship-fast), "coarse" - (defaults.coarse_model) or "fine" (defaults.flagship_accurate_model; alias "accurate"). substrate: a registry substrate name or eps_r. - These models' priors use the half-space kernel their networks were trained on, which cannot represent another substrate - thickness: they are served for the training stack (Si 11.45, 350 µm) only and raise otherwise (no rescaling). Other stacks: - the GNN models (geomgnn: prior solved at the stack) or the final recipes (tlsq_infer.final). - The ground self-capacitance is not predicted (it depends on the chip boundary, excluded from training): NaN. - self_from_rows: C_ii = sum_j |C_ij| / (1 - row_sum_eps); row_sum_eps defaults to the training median 0.0143 (the - never-seen components have a median of 0.0099, so the default overestimates C_ii by ~0.45 % there; deploy/LIMITS.md). - blend_kinds: "invariant" (conductor-conductor / conductor-ground, independent of polygon order) or "published" - (paper file-order kinds); default from registry blend.kinds. Mesh coarsening by the cell cap and a v3-rich prior - without extrapolation are reported in `prior_mesh`, `warnings` and `expected_error["mesh_warning"]`; a prior below - the training regime (< 0.75 panels across the smallest gap) sets `expected_error["out_of_regime"]` with a warning. - large_layouts: "route" (default) re-routes a capped-prior model to the registry's `defaults.large_layout_model` - (flagship prior) when its mesh would fall below the training regime on this layout (reported in `model_used` and - `warnings`); "keep" never re-routes. A prior with zero or non-finite mutual entries raises PriorError. - """ - reg = registry or load_registry() - model = resolve_model(reg, model) - m = reg.model(model) - if m.get("status") != "available" or m.get("kind") == "baseline": - raise ValueError(f"model {model!r} is not deployable ({m.get('status')}); available: {reg.deployable()}") - eps = reg.eps_of(substrate) - if not on_training_stack(eps, thickness_um): - raise ValueError(f"model {model!r} is served for the training stack only (Si, eps_r {EPS_TRAIN:g}, 350 µm; requested eps_r {eps:g}, " - f"{float(thickness_um):g} µm): its half-space-kernel prior cannot be solved at another stack. Use the flagship " - "Accurate tier or the paper model (prior solved at your stack)") - t_all = time.perf_counter() - timing: dict = {} - n = prepared.n_conductors - names = ["G"] + _internal_names(n) - metals = [prepared.ground] + list(prepared.conductors) - fallback_note = None - routed_note = None - if large_layouts == "route": - fb = large_layout_model(reg, model) - if fb is not None: - t = time.perf_counter() - below, cpg = would_hit_cap(metals, m.get("prior", "standard")) - timing["regime_check_s"] = time.perf_counter() - t - if below: - routed_note = (f"large layout: the capped {m.get('prior')} prior of {model!r} would resolve fewer than {cpg:.2f} panels across " - f"the smallest gap (training regime >= {REGIME_MIN_CELLS_PER_GAP}); predicted with {fb!r} " - f"({reg.model(fb).get('title')}) instead") - model, m = fb, reg.model(fb) - try: - logC, debug = run_pipeline(metals, names, model, reg, model_dir, timing, blend_kinds, ood_gate) - except np.linalg.LinAlgError as e: # v3 MoM system not positive definite at gap/3 and gap/6 (e.g. long fine combs) - fb = m.get("fallback") - if not fb: - raise - fallback_note = (f"the {m.get('prior')} MoM prior of {model!r} failed on this layout ({e}); predicted with the fallback " - f"model {fb!r} ({reg.model(fb).get('title')}) instead") - timing.clear() - logC, debug = run_pipeline(metals, names, fb, reg, model_dir, timing, blend_kinds, ood_gate) - k = len(metals) - Cabs = np.exp(logC[:k, :k]) - mesh = debug.get("prior_mesh") or {} - pm = debug.get("prior_matrix") - if pm is not None: - mut = pm[np.triu_indices(k, 1)] - if not np.all(np.isfinite(mut)) or np.any(mut == 0): - raise PriorError(f"the {m.get('prior')} MoM prior of {model!r} returned {int((~np.isfinite(mut)).sum())} non-finite and " - f"{int((mut == 0).sum())} zero mutual entries on this layout ({mesh.get('cells_per_min_gap', float('nan')):.2f} " - f"panels across the smallest gap {mesh.get('min_gap_um', float('nan')):.3g} um at the cap of {mesh.get('max_cells')} " - "panels): no matrix is returned. Use the flagship tier (resolution-controlled prior, `all-data-flagship`) or " - "predict a smaller selection of conductors (prepare(select=...)).") - M = -Cabs.copy() - for i in range(k): - M[i, i] = Cabs[i, i] - if self_from_rows: - e = float(reg["self_capacitance"]["row_sum_eps"] if row_sum_eps is None else row_sum_eps) - for i in range(1, k): - M[i, i] = sum(Cabs[i, j] for j in range(k) if j != i) / (1 - e) - M[0, 0] = np.nan - out_mut = M[np.triu_indices(k, 1)] - if not np.all(np.isfinite(out_mut)) or np.any(out_mut == 0): - raise PriorError(f"model {model!r} produced {int((~np.isfinite(out_mut)).sum())} non-finite and {int((out_mut == 0).sum())} zero " - "mutual entries on this layout: no matrix is returned. Use the flagship tier (`all-data-flagship`) or predict a " - "smaller selection of conductors (prepare(select=...)).") - timing["total_s"] = time.perf_counter() - t_all - labels = ["G"] + list(prepared.names) - iu = [(i, j) for i in range(k) for j in range(i + 1, k)] - mut = np.array([abs(M[i, j]) for i, j in iu]) - mu_name = m.get("fallback") if fallback_note else model - mu = reg.model(mu_name) if mu_name != model else m - base = mu.get("validation") or mu.get("paper", {}).get("never_seen") # deploy held-out sets for models trained on all data - if base is None and mu["kind"] == "blend": - base = reg.model(mu["components"][0]).get("validation") or reg.model(mu["components"][0])["paper"]["never_seen"] - if base is None or base.get("median_pct") is None: # not yet scored (e.g. a flagship-prior entry): the fine tier's numbers, labelled as such - ft = reg.model(reg["defaults"]["flagship_accurate_model"])["validation"] - base = {**ft, "set": f"{ft.get('set')} (fine-tier network with its deployed prior; this model's own score is pending)"} - P = load_params() - L = lateral_extent(prepared.conductors, P) - exp_err = expected_error(P, eps, float(thickness_um), L, {kk: base[kk] for kk in ("median_pct", "mae_ff", "rmse_ff", "set") if kk in base}, - float(np.mean(mut)), float(np.sqrt(np.mean(mut**2)))) - exp_err["validation_sets"] = {s: mu.get("paper", {}).get(s) for s in ("never_seen", "ood60") if mu.get("paper", {}).get(s)} - if mu.get("validation"): - exp_err["validation_sets"]["deploy_heldout"] = mu["validation"] - out = {"names": labels, "matrix_fF": [[None if np.isnan(v) else float(v) for v in row] for row in M], "units": "fF", - "convention": "Maxwell matrix: diagonal = self-capacitance, off-diagonal = -mutual; row/column 0 = ground (its self term not predicted)", - "self_capacitance": "row sums / (1 - eps_rs)" if self_from_rows else "network self term", - "model": model, "model_title": m.get("title"), "repo_id": m.get("repo_id"), "package_version": __version__, - "registry_version": reg["version"], "substrate": substrate if not isinstance(substrate, (int, float)) else f"custom eps={eps:g}", - "eps_r": eps, "thickness_um": float(thickness_um), - "training_stack": {"eps_r": EPS_TRAIN, "thickness_um": 350.0}, "timing_s": timing, "expected_error": exp_err, - "warnings": list(prepared.warnings) + ([exp_err["warning"]] if exp_err.get("warning") else [])} - _per_entry(out, reg, mu_name, debug, labels, 1.0, exp_err) - if debug.get("prior_stage_s"): - out["prior_stage_s"] = debug["prior_stage_s"] - if mesh: - out["prior_mesh"] = mesh - msg = [] - if mesh.get("cap_hit"): - msg.append(f"MoM prior mesh coarsened by the cell cap ({mesh['max_cells']} cells): h_min {mesh['h_min_um']:.3g} µm vs " - f"target {mesh['h_min_target_um']:.3g} µm ({mesh['cells_per_min_gap']:.2f} cells across the smallest gap " - f"{mesh['min_gap_um']:.3g} µm); expect a larger prior error than on the validation sets") - if mesh.get("extrapolated") is False: - msg.append("v3-rich prior not extrapolated (" + (mesh.get("note") or "fine solve only") + ")") - cpg = mesh.get("cells_per_min_gap") - exp_err["cells_per_min_gap"] = cpg - exp_err["out_of_regime"] = bool(cpg is not None and cpg < REGIME_MIN_CELLS_PER_GAP) - if exp_err["out_of_regime"]: - msg.insert(0, f"OUT OF THE TRAINING REGIME: the prior resolves only {cpg:.2f} panels across the smallest gap " - f"({mesh.get('min_gap_um', float('nan')):.3g} µm); the networks were trained on priors with " - f"{REGIME_MIN_CELLS_PER_GAP}-3 panels per gap and their validation errors do not apply. Use the flagship " - "tier (`all-data-flagship`: resolution-controlled prior) or a smaller selection of conductors.") - out["warnings"] += msg - exp_err["mesh_warning"] = "; ".join(msg) if msg else None - tr = debug.get("ood_trust") - if tr is not None: - out["ood_trust"] = tr.tolist() - out["ood_gate"] = bool(debug.get("ood_gate_applied")) - lo = float(tr[np.triu_indices(k, 1)].min()) if k > 1 else 1.0 - if lo < WARN_TRUST: - out["warnings"].append(f"OUT OF THE TRAINING DISTRIBUTION: {int((tr[np.triu_indices(k, 1)] < WARN_TRUST).sum())} entries have " - f"network trust < {WARN_TRUST} (min {lo:.2f}; features beyond the training envelope, see ood_trust); " - + ("their network corrections are shrunk towards the physics prior (ood_gate)." if debug.get("ood_gate_applied") - else "predict(..., ood_gate=True) shrinks them towards the physics prior.")) - fm = debug.get("far_mask") - if fm is not None: - out["far_mask"] = fm.tolist() - out["warnings"].append(f"{int(np.triu(fm, 1).sum())} conductor pairs farther apart than {SPARSE_R_GAPS:g} smallest gaps are " - "not in the network graph (large layout): their entries are the physics prior's (far_mask)") - if routed_note: - out["model_used"] = model - out["warnings"].insert(0, routed_note) - if self_from_rows: - out["row_sum_eps"] = float(reg["self_capacitance"]["row_sum_eps"] if row_sum_eps is None else row_sum_eps) - if fallback_note: - out["model_used"] = m["fallback"] - out["warnings"].insert(0, fallback_note) - if m.get("warning"): - out["warnings"].insert(0, m["warning"]) - if return_debug: - out["debug"] = debug - return out - - -def _per_entry(out: dict, reg, name: str, debug: dict, labels: list[str], scale: float, exp_err: dict) -> None: - """Per-entry error estimates (ERROR_MODEL.md) for the models with an error-model artifact (registry - artifacts.error_model): out["per_entry"] and the layout-level expected error derived from them; the stack terms - (material, thickness) are added in quadrature. Other models keep the global estimate from the validation sets.""" - path = errmodel.find_artifact(name, reg) if debug.get("seed_logC") is not None else None - if path is None: - out["per_entry"] = None - exp_err["source"] = "global: validation-set median scaled to this layout (no per-entry error model for this model)" - return - art = errmodel.load(path) - stack = float(np.hypot(exp_err.get("material_residual_pct", 0.0), exp_err.get("thickness_residual_pct", 0.0))) / 100 - ing = errmodel.ingredients_from_graph(["G"] + labels[1:], debug["seed_logC"], debug["prior_matrix"], debug["graph"], - debug["h_min_um"], debug.get("prior_coarse_C")) - ent = errmodel.predict_entries(art, ing, labels, scale=scale, stack_rel=stack) - out["per_entry"] = ent - med = np.array([e["predicted_median_err_pct"] for e in ent]) / 100 - typ = np.array([e["C_fF"] for e in ent]) * med # predicted median |error| per entry (fF) - glob_keys = ("expected_median_pct", "expected_mae_ff", "expected_rmse_ff") - exp_err["global_estimate"] = {k: exp_err[k] for k in glob_keys if k in exp_err} - # layout level from the per-entry medians; MAE / RMSE assume a half-normal error per entry (mean/median 1.18, rms/median 1.48) - exp_err.update(expected_median_pct=float(100 * np.median(med)), expected_mae_ff=float(1.18 * typ.mean()), - expected_rmse_ff=float(1.48 * np.sqrt(np.mean(typ ** 2))), - n_entries_p_large_gt_0p5=int(sum(e["p_large_error"] > 0.5 for e in ent)), - source=f"per-entry error model {Path(path).name} (protocol ERROR_MODEL.md; trained on held-out-group residuals)", - per_entry_model={"artifact": Path(path).name, "sklearn": art.get("sklearn"), "conformal": art["conformal"], - "threshold_pct": 100 * art.get("threshold", 0.05), - "validation": (art.get("validation") or {}).get("summary"), - "caveat": "intervals are split-conformal at nominal 80 / 95 %; on held-out Qiskit Metal " - "components and TransmonPockets they covered 70-92 % / 86-100 %, and too few " - "of the entries below ~0.3 fF (about 53 %); see ERROR_MODEL.md"}) - exp_err["assumptions"] = list(exp_err.get("assumptions", [])) + [ - "per-entry intervals: split-conformal, calibrated per entry kind on leave-one-group-out residuals; coverage " - "validated on held-out sets (ERROR_MODEL.md); the stack residual is added in quadrature (Gaussian assumption)"] - - -def intervals_csv(result: dict) -> str: - """Per-entry estimates as CSV (empty string when the model has no error model).""" - ent = result.get("per_entry") or [] - if not ent: - return "" - lines = ["i,j,kind,C_fF,interval_80_lo_fF,interval_80_hi_fF,interval_95_lo_fF,interval_95_hi_fF,predicted_median_err_pct,p_large_error"] - for e in ent: - lines.append(",".join([e["i"], e["j"], e["kind"]] + [f"{v:.6g}" for v in (e["C_fF"], *e["interval_80_fF"], *e["interval_95_fF"], - e["predicted_median_err_pct"], e["p_large_error"])])) - return "\n".join(lines) + "\n" - - -def matrix_csv(result: dict, corner: str = "") -> str: - """CSV of the matrix; corner = text of the top-left header cell (e.g. the unit "fF").""" - names = result["names"] - lines = [corner + "," + ",".join(names)] - for nm, row in zip(names, result["matrix_fF"]): - lines.append(nm + "," + ",".join("" if (v is None or (isinstance(v, float) and np.isnan(v))) else f"{v:.6g}" for v in row)) - return "\n".join(lines) + "\n" diff --git a/tlsq_infer/registry.py b/tlsq_infer/registry.py deleted file mode 100644 index c6212894be3fc35149401c7c157e9f15551a1a3c..0000000000000000000000000000000000000000 --- a/tlsq_infer/registry.py +++ /dev/null @@ -1,232 +0,0 @@ -"""Model registry (deploy/registry.yaml) and model loading: local repository checkpoints, an exported model directory, -or the Hugging Face Hub (model repos built by deploy/sync.py).""" - -from __future__ import annotations - -import json -import os -from functools import lru_cache -from pathlib import Path - -import numpy as np -import yaml - -GNN_KINDS = {"gnn"} -PRIORS = {"standard": dict(max_cells=8000, cells_per_gap=3.0), "fine": dict(max_cells=16000, cells_per_gap=6.0), - "v3": dict(mesh="v3", max_cells=8000, cells_per_gap=3.0), "v3-rich": dict(mesh="v3-rich", max_cells=8000, cells_per_gap=3.0), - # flagship: strip-merged conductor-anchored mesh, Richardson between gap/(2 cpg) and gap/cpg, H-matrix solve for - # large systems; max_cells is a safety cap on the merged panels (PRIOR_SCHEME.md section 6) - "flagship": dict(mesh="flagship", max_cells=250000, cells_per_gap=3.0), - "flagship-coarse": dict(mesh="flagship", max_cells=250000, cells_per_gap=1.5), - # flagship-fast cheap priors (PRIOR_SCHEME.md Part III): micro-MoM at a merged-panel budget (one window up to 8 - # conductors, core-graded windows beyond) and the closed-form edge-coupling prior - "lite500": dict(mesh="lite", max_cells=500, cells_per_gap=3.0), "lite1500": dict(mesh="lite", max_cells=1500, cells_per_gap=3.0), - "formula": dict(mesh="formula"), - # resolution-controlled lite priors (PRIOR_SCHEME.md 14.5 E1): no panel budget, finest panel = smallest gap / ppg - **{f"liteppg{x:g}": dict(mesh="lite", max_cells=10**9, cells_per_gap=x) for x in (0.375, 0.75, 1.5, 3.0)}} -for _k in list(PRIORS): # 2026-10-10: the slab kernel is the physics of every prior (PRIOR_SCHEME.md 14.6); the existing names keep - PRIORS[_k] = {**PRIORS[_k], "substrate": "halfspace"} # the half-space kernel their networks were trained on - PRIORS[f"{_k}-slab"] = {**PRIORS[_k], "substrate": "slab_open"} - - -def find_registry(path=None) -> Path: - cands = [path, os.environ.get("TLSQ_REGISTRY"), Path.cwd() / "registry.yaml", Path.cwd() / "deploy" / "registry.yaml", - Path(__file__).resolve().parent / "registry.yaml"] - cands += [p / "registry.yaml" for p in Path(__file__).resolve().parents if (p / "registry.yaml").exists()] - cands += [p / "deploy" / "registry.yaml" for p in Path(__file__).resolve().parents] - for c in cands: - if c and Path(c).exists(): - return Path(c) - raise FileNotFoundError("registry.yaml not found (set TLSQ_REGISTRY)") - - -class Registry: - def __init__(self, path=None): - self.path = find_registry(path) - self.data = yaml.safe_load(self.path.read_text()) - # repository root: registry lives in /deploy/registry.yaml (repo checkout) or next to the app (Space) - self.root = self.path.parent.parent if self.path.parent.name == "deploy" else self.path.parent - - def __getitem__(self, k): - return self.data[k] - - @property - def models(self) -> dict: - return self.data["models"] - - def model(self, name: str) -> dict: - if name not in self.models: - raise KeyError(f"unknown model {name!r}; available: {self.deployable()}") - return {"name": name, **self.models[name]} - - def deployable(self) -> list[str]: - return [k for k, v in self.models.items() if v.get("status") == "available" and v.get("kind") != "baseline"] - - def substrates(self) -> dict: - return dict(self.data["substrates"]) - - def eps_of(self, substrate) -> float: - if isinstance(substrate, (int, float)): - return float(substrate) - subs = self.substrates() - if substrate in subs: - return float(subs[substrate]) - for k, v in subs.items(): # tolerant match: "sapphire", "Si", "GaAs" ... - if k.lower().startswith(str(substrate).lower()): - return float(v) - try: - return float(substrate) - except ValueError: - raise KeyError(f"unknown substrate {substrate!r}; use one of {list(subs)} or a number") from None - - -@lru_cache(maxsize=4) -def load_registry(path=None) -> Registry: - return Registry(path) - - -# ---------------------------------------------------------------- checkpoints - -def export_checkpoint(src, dst) -> dict: - """Training checkpoint (pickled numpy scaling) -> torch file loadable with weights_only=True.""" - import torch - - st = torch.load(src, map_location="cpu", weights_only=False) - sc = st["scaling"] - out = {"state": {k: v.clone() for k, v in st["state"].items()}, - "scaling": {p: [np.asarray(sc[p][0], float).tolist(), np.asarray(sc[p][1], float).tolist()] for p in ("node", "edge", "global")} - | {"keys": [list(x) for x in sc["keys"]]}, - "dims": list(st["dims"]), "w": int(st["w"]), "rounds": int(st["rounds"]), "variant": st.get("variant", ""), - "prior": st.get("prior", ""), "n_train": int(st.get("n_train", 0))} - if sc.get("features"): # dropped columns, clip mode and training envelope (GRID_SCALING.md amendment 4) - f = sc["features"] - out["scaling"]["features"] = {"drop": list(f.get("drop", [])), "clip": f.get("clip", "iqr20"), - "envelope": {p: [np.asarray(v, float).tolist() for v in f["envelope"][p]] for p in ("node", "edge", "global")}} - torch.save(out, dst) - return {k: out[k] for k in ("dims", "w", "rounds", "variant", "prior", "n_train")} - - -def _load_ckpt(path): - import torch - - try: - st = torch.load(path, map_location="cpu", weights_only=True) - except Exception: # noqa: BLE001 local training checkpoints carry numpy arrays: trusted files from this repo only - st = torch.load(path, map_location="cpu", weights_only=False) - sc = st["scaling"] - st["scaling"] = {p: (np.asarray(sc[p][0], float), np.asarray(sc[p][1], float)) for p in ("node", "edge", "global")} | {"keys": sc["keys"]} - if sc.get("features"): - st["scaling"]["features"] = sc["features"] - return st - - -def _hub_download(repo_id: str, filename: str) -> str: - from huggingface_hub import hf_hub_download - - return hf_hub_download(repo_id=repo_id, filename=filename) - - -def resolve_files(reg: Registry, name: str, model_dir=None) -> list[str]: - """Weight files of a model: // (exported), local checkpoints, or the model's Hub repo.""" - m = reg.model(name) - model_dir = model_dir or os.environ.get("TLSQ_MODEL_DIR") - if model_dir and (Path(model_dir) / name / "config.json").exists(): - cfg = json.loads((Path(model_dir) / name / "config.json").read_text()) - return [str(Path(model_dir) / name / f) for f in cfg["files"]] - local = [reg.root / p for p in m.get("checkpoints", [])] - if local and all(p.exists() for p in local): - return [str(p) for p in local] - if m.get("repo_id") and os.environ.get("TLSQ_OFFLINE") != "1": - cfg = json.loads(Path(_hub_download(m["repo_id"], "config.json")).read_text()) - return [_hub_download(m["repo_id"], f) for f in cfg["files"]] - if m.get("status") != "available": - raise FileNotFoundError(f"model {name!r} is {m.get('status')}: {m.get('pending_reason', '')}") - raise FileNotFoundError(f"no weights for {name!r}: looked in {model_dir}, {local}, hub repo {m.get('repo_id')}") - - -def _pair_local_sparse(net, scaling: dict, row: dict, proxy_key: str) -> np.ndarray: - """Pair-local (R = 0) network on one graph evaluated on its edges only (large layouts with sparse graphs): the same - MLPs and scaling as SceneGNN.forward on the dense padded batch, without the N x N edge tensor. Returns (1, N, N) log|C|; - pairs without an edge get the prior's value (predict replaces them by the prior anyway).""" - import torch - - from ._vendor.gnn import derive_features, scale_features - - if (scaling.get("features") or {}).get("derive"): - row = derive_features(row) - nk, ek, gk = scaling["keys"] - sc = lambda A, p: scale_features(A, scaling[p], p, scaling) # noqa: E731 - n = len(row["names"]) - pairs = list(row["edges"]) - X = sc(np.array([[nd[k] for k in nk] for nd in row["nodes"]], float), "node") - E = sc(np.array([[row["edges"][e][k] for k in ek] for e in pairs], float), "edge") - U = sc(np.array([[row["global"][k] for k in gk]], float), "global") - P = np.zeros((n, n)) - for i, nd in enumerate(row["nodes"]): - P[i, i] = nd.get("proxy_log_Cself", 0.0) if proxy_key == "proxy_log_C" else 0.0 - for (i, j), f in row["edges"].items(): - P[i, j] = P[j, i] = f.get(proxy_key, 0.0) if proxy_key else 0.0 - t = lambda a: torch.tensor(a, dtype=torch.float32) # noqa: E731 - with torch.no_grad(): - u = net.enc_u(t(U)) - oe = net.head_e(torch.cat([net.enc_e(t(E)), u.expand(len(pairs), -1)], -1))[:, 0].numpy() - on = net.head_n(torch.cat([net.enc_n(t(X)), u.expand(n, -1)], -1))[:, 0].numpy() - N = max(8, n) - out = np.zeros((1, N, N)) - out[0, :n, :n] = P - ii, jj = np.array(pairs).T - out[0, ii, jj] += oe - out[0, jj, ii] += oe - out[0, np.arange(n), np.arange(n)] += on - return out - - -class Ensemble: - """Mean of log C over the seeds of one GNN model.""" - - def __init__(self, files): - from ._vendor.gnn import SceneGNN - - self.members = [] - for f in files: - st = _load_ckpt(f) - net = SceneGNN(*st["dims"], st["w"], rounds=st["rounds"]) - net.load_state_dict(st["state"]) - net.eval() - self.members.append((net, st["scaling"])) - self.rounds = st["rounds"] - - def member_outputs(self, rows: list[dict], proxy_key="proxy_log_C") -> np.ndarray: - """Per-seed predictions (S, B, N_MAX, N_MAX); the error model uses their spread.""" - from ._vendor.gnn import build_graphset, predict - - if self.rounds == 0 and len(rows) == 1 and len(rows[0]["names"]) > 8 and not any(getattr(n, "gate", False) for n, _ in self.members): - return np.asarray([_pair_local_sparse(net, sc, rows[0], proxy_key) for net, sc in self.members]) - out = [] - for net, sc in self.members: - gs, _ = build_graphset(rows, scaling=sc, proxy_key=proxy_key) - out.append(predict(net, gs, np.arange(len(rows)))) - return np.asarray(out) - - def __call__(self, rows: list[dict], proxy_key="proxy_log_C") -> np.ndarray: - return np.mean(self.member_outputs(rows, proxy_key), 0) - - -_CACHE: dict = {} - - -def get_component(reg: Registry, name: str, model_dir=None): - """Loaded, cached model object: Ensemble for GNNs, the GBM for the charge-corrected prior.""" - key = (str(reg.path), name) - if key not in _CACHE: - m = reg.model(name) - files = resolve_files(reg, name, model_dir) - if m["kind"] in GNN_KINDS: - _CACHE[key] = Ensemble(files) - elif m["kind"] == "charge_prior": - from .charge import load_gbm - - _CACHE[key] = load_gbm(files[0]) - else: - raise ValueError(f"{name}: kind {m['kind']} has no weights") - return _CACHE[key] diff --git a/tlsq_infer/stack_error.json b/tlsq_infer/stack_error.json deleted file mode 100644 index ff40d31201f5c34da22940239679c7d0864c0f25..0000000000000000000000000000000000000000 --- a/tlsq_infer/stack_error.json +++ /dev/null @@ -1,342 +0,0 @@ -{ - "version": 1, - "n_designs": 15, - "groups": [ - "in-family (ncap_fingers)", - "never-seen (shielded_concentric)", - "never-seen (xmon)" - ], - "eps_train": 11.45, - "t_train_um": 350.0, - "material": { - "slope_pct_per_log": 1.278628010748463, - "floor_pct": 0.0, - "q90_extra_pct": 0.18992133122197666, - "n_points": 165, - "max_observed_pct": 1.9339159521641447, - "per_material_median_pct": { - "mat_GaAs": 0.106, - "mat_Ge": 0.284, - "mat_InP": 0.069, - "mat_LaAlO3": 0.534, - "mat_MgO": 0.148, - "mat_SiC": 0.159, - "mat_Si_RT": 0.019, - "mat_diamond": 0.853, - "mat_fused_silica": 1.372, - "mat_quartz": 1.124, - "mat_sapphire": 0.096 - } - }, - "thickness": { - "L_definition": "sqrt_area", - "A_pct": 1.5079787674195164, - "p": 1.3100240061291493, - "logo_log_rmse": 0.728244486631929, - "n_points": 64, - "thick_side_pct": 0.21511320447635818, - "solver_noise_pct": 0.3836033380842397, - "candidates": { - "bbox_diag": { - "A_pct": 0.5699362292208275, - "p": 1.1722109336174098, - "logo_log_rmse": 1.1148061086218972, - "n_points": 64 - }, - "bbox_max": { - "A_pct": 0.7202421947589044, - "p": 1.2100207446152025, - "logo_log_rmse": 1.0451094342685237, - "n_points": 64 - }, - "sqrt_area": { - "A_pct": 1.5079787674195164, - "p": 1.3100240061291493, - "logo_log_rmse": 0.728244486631929, - "n_points": 64 - }, - "pocket_diag": { - "A_pct": 0.4550642645800963, - "p": 1.210018780093613, - "logo_log_rmse": 1.0525505331415834, - "n_points": 64 - } - }, - "per_group": { - "in-family (ncap_fingers)": { - "A_pct": 2.302259643464834, - "p": 1.6322938554491087, - "L_um_median": 37.23399629370986, - "doe_breakdown_t_um": 25.0 - }, - "never-seen (shielded_concentric)": { - "A_pct": 1.0479516989252748, - "p": 1.4069550681680345, - "L_um_median": 248.02303237804313, - "doe_breakdown_t_um": 100.0 - }, - "never-seen (xmon)": { - "A_pct": 1.0239958864956118, - "p": 1.4957064823792836, - "L_um_median": 143.0913193523632, - "doe_breakdown_t_um": 25.0 - } - }, - "per_thickness_median_pct": { - "in-family (ncap_fingers)": { - "10.0": 23.72, - "25.0": 4.211, - "50.0": 0.363, - "100.0": 0.555, - "200.0": 0.292, - "500.0": 0.124, - "675.0": 0.189, - "1000.0": 0.292 - }, - "never-seen (shielded_concentric)": { - "10.0": 132.56, - "25.0": 26.155, - "50.0": 7.642, - "100.0": 5.763, - "200.0": 1.537, - "500.0": 0.204, - "675.0": 0.175, - "1000.0": 0.455 - }, - "never-seen (xmon)": { - "10.0": 101.263, - "25.0": 8.002, - "50.0": 6.58, - "100.0": 1.782, - "200.0": 0.64, - "500.0": 0.155, - "675.0": 0.219, - "1000.0": 0.357 - } - } - }, - "L_um": { - "exp6/q3d_cap_0087": { - "bbox_diag": 49.24428900898052, - "bbox_max": 43.0, - "sqrt_area": 22.891839157219326, - "pocket_diag": 61.71709649683789, - "gap": 2.0 - }, - "exp6/q3d_cap_1503": { - "bbox_diag": 63.631753079732135, - "bbox_max": 55.0, - "sqrt_area": 31.43171115291052, - "pocket_diag": 78.64477096412705, - "gap": 2.0 - }, - "exp6/q3d_cap_1603": { - "bbox_diag": 71.7007670809734, - "bbox_max": 55.0, - "sqrt_area": 37.646954431932485, - "pocket_diag": 88.52683209061533, - "gap": 1.9999999999999998 - }, - "exp15/q3d_cap_0079": { - "bbox_diag": 424.0575328808581, - "bbox_max": 316.15700000000004, - "sqrt_area": 238.0635929011407, - "pocket_diag": 453.80782894084143, - "gap": 2.0 - }, - "exp15/q3d_cap_0161": { - "bbox_diag": 686.9943742659033, - "bbox_max": 520.692, - "sqrt_area": 307.66073536770995, - "pocket_diag": 780.5691326846072, - "gap": 2.0 - }, - "exp15/q3d_cap_0134": { - "bbox_diag": 596.1214684944672, - "bbox_max": 471.192, - "sqrt_area": 238.87703055756518, - "pocket_diag": 718.4225593764439, - "gap": 2.0 - }, - "exp6/q3d_cap_0317": { - "bbox_diag": 80.26207074328447, - "bbox_max": 69.0, - "sqrt_area": 37.23399629370986, - "pocket_diag": 96.17692030835673, - "gap": 2.0 - }, - "exp6/q3d_cap_1691": { - "bbox_diag": 98.47842403288143, - "bbox_max": 83.0, - "sqrt_area": 51.61824698689408, - "pocket_diag": 110.78808600206071, - "gap": 1.9999999999999998 - }, - "exp15/q3d_cap_0123": { - "bbox_diag": 794.2259085354746, - "bbox_max": 582.165, - "sqrt_area": 401.3324007976431, - "pocket_diag": 842.7031715028727, - "gap": 2.0 - }, - "exp15/q3d_cap_0096": { - "bbox_diag": 552.1546761741677, - "bbox_max": 407.655, - "sqrt_area": 248.02303237804313, - "pocket_diag": 585.5440185263615, - "gap": 2.0 - }, - "exp13/q3d_cap_0032": { - "bbox_diag": 500.9710123350452, - "bbox_max": 354.24, - "sqrt_area": 143.0913193523632, - "pocket_diag": 541.380750666294, - "gap": 9.966999999999985 - }, - "exp13/q3d_cap_0580": { - "bbox_diag": 567.2537877899098, - "bbox_max": 401.10900000000004, - "sqrt_area": 143.0080934073313, - "pocket_diag": 617.2402108174742, - "gap": 4.393999999999977 - }, - "exp13/q3d_cap_0380": { - "bbox_diag": 441.7698424519266, - "bbox_max": 346.886, - "sqrt_area": 119.7274361038438, - "pocket_diag": 494.16827953643485, - "gap": 5.144999999999982 - }, - "exp13/q3d_cap_0581": { - "bbox_diag": 768.9465302249565, - "bbox_max": 595.467, - "sqrt_area": 177.69789423062954, - "pocket_diag": 853.4626354006366, - "gap": 5.095000000000006 - }, - "exp13/q3d_cap_0121": { - "bbox_diag": 766.2007495304348, - "bbox_max": 579.441, - "sqrt_area": 166.33747046291168, - "pocket_diag": 810.6574023056843, - "gap": 4.310999999999979 - } - }, - "base_scale": { - "never_seen_mean_abs_ff": 42.840808925401255, - "never_seen_rms_ff": 63.13559865994375, - "entries": 4739 - }, - "empirical_0round_blend_eps_scaled_median_pct": { - "mat_GaAs": { - "in-family (ncap_fingers)": 0.853, - "never-seen (shielded_concentric)": 1.36, - "never-seen (xmon)": 2.026 - }, - "mat_Ge": { - "in-family (ncap_fingers)": 0.869, - "never-seen (shielded_concentric)": 1.496, - "never-seen (xmon)": 1.976 - }, - "mat_InP": { - "in-family (ncap_fingers)": 0.835, - "never-seen (shielded_concentric)": 1.333, - "never-seen (xmon)": 2.02 - }, - "mat_LaAlO3": { - "in-family (ncap_fingers)": 0.787, - "never-seen (shielded_concentric)": 1.561, - "never-seen (xmon)": 1.899 - }, - "mat_MgO": { - "in-family (ncap_fingers)": 0.892, - "never-seen (shielded_concentric)": 1.159, - "never-seen (xmon)": 2.106 - }, - "mat_SiC": { - "in-family (ncap_fingers)": 0.892, - "never-seen (shielded_concentric)": 1.151, - "never-seen (xmon)": 2.107 - }, - "mat_Si_RT": { - "in-family (ncap_fingers)": 0.836, - "never-seen (shielded_concentric)": 1.291, - "never-seen (xmon)": 2.041 - }, - "mat_diamond": { - "in-family (ncap_fingers)": 1.404, - "never-seen (shielded_concentric)": 1.183, - "never-seen (xmon)": 2.205 - }, - "mat_fused_silica": { - "in-family (ncap_fingers)": 1.691, - "never-seen (shielded_concentric)": 1.501, - "never-seen (xmon)": 2.468 - }, - "mat_quartz": { - "in-family (ncap_fingers)": 1.238, - "never-seen (shielded_concentric)": 1.43, - "never-seen (xmon)": 2.336 - }, - "mat_sapphire": { - "in-family (ncap_fingers)": 0.891, - "never-seen (shielded_concentric)": 1.202, - "never-seen (xmon)": 2.089 - }, - "ref": { - "in-family (ncap_fingers)": 0.836, - "never-seen (shielded_concentric)": 1.275, - "never-seen (xmon)": 2.05 - }, - "sub_t10": { - "in-family (ncap_fingers)": 20.952, - "never-seen (shielded_concentric)": 116.056, - "never-seen (xmon)": 71.084 - }, - "sub_t100": { - "in-family (ncap_fingers)": 0.788, - "never-seen (shielded_concentric)": 4.861, - "never-seen (xmon)": 2.289 - }, - "sub_t1000": { - "in-family (ncap_fingers)": 0.994, - "never-seen (shielded_concentric)": 1.193, - "never-seen (xmon)": 2.014 - }, - "sub_t200": { - "in-family (ncap_fingers)": 0.867, - "never-seen (shielded_concentric)": 1.857, - "never-seen (xmon)": 1.921 - }, - "sub_t25": { - "in-family (ncap_fingers)": 4.291, - "never-seen (shielded_concentric)": 30.851, - "never-seen (xmon)": 11.784 - }, - "sub_t50": { - "in-family (ncap_fingers)": 0.889, - "never-seen (shielded_concentric)": 9.393, - "never-seen (xmon)": 3.281 - }, - "sub_t500": { - "in-family (ncap_fingers)": 0.892, - "never-seen (shielded_concentric)": 1.363, - "never-seen (xmon)": 2.103 - }, - "sub_t675": { - "in-family (ncap_fingers)": 0.894, - "never-seen (shielded_concentric)": 1.368, - "never-seen (xmon)": 2.081 - }, - "thin_t0.25": { - "in-family (ncap_fingers)": 0.836, - "never-seen (shielded_concentric)": 1.275, - "never-seen (xmon)": 2.05 - } - }, - "notes": [ - "residuals are Q3D label shifts vs the 350 um Si reference (model-independent)", - "L = sqrt_area of the conductors (chosen by leave-one-group-out log RMSE among ['bbox_diag', 'bbox_max', 'sqrt_area', 'pocket_diag'])", - "15 designs only; shielded concentric breaks down earlier than t/L predicts for Xmon: treat thresholds as indicative" - ] -} \ No newline at end of file diff --git a/tlsq_infer/stack_error.py b/tlsq_infer/stack_error.py deleted file mode 100644 index 5fd4347112804399743aec1c6fad3a5fce9bbc14..0000000000000000000000000000000000000000 --- a/tlsq_infer/stack_error.py +++ /dev/null @@ -1,106 +0,0 @@ -"""Expected extra error when the layer stack differs from the training stack (Si, eps 11.45, 350 µm), evaluated from -the parameters fitted by deploy/stack_error.py on the 15-design stack DoE (deploy/artifacts/stack_error.json). -Study tool only since 2026-11-03: no serving path rescales or calls it (tlsq_infer.substrate: prior solved at the stack). - -Two independent residuals, combined in quadrature with the model's own validation error: - material after the eps correction (1 + eps_sub) / (1 + 11.45): r_mat = a_mat * |ln((1 + eps) / (1 + 11.45))| + floor - thickness finite substrate seen by the fringe field: r_t = A * (t / L)^(-p) for t < 350 µm (L = lateral extent of the - conductors), measured relative to the 350 µm reference; thicker substrates: the measured small shift. -""" - -from __future__ import annotations - -import json -from pathlib import Path - -import numpy as np - -EPS_TRAIN = 11.45 -T_TRAIN = 350.0 - - -def eps_factor(eps_sub: float) -> float: - """Quasi-static half-space correction of every capacitance for another substrate permittivity.""" - return (1.0 + float(eps_sub)) / (1.0 + EPS_TRAIN) - - -def load_params(path=None) -> dict | None: - for p in [path, Path(__file__).resolve().parent / "stack_error.json"] + [q / "artifacts" / "stack_error.json" for q in Path(__file__).resolve().parents]: - if p and Path(p).exists(): - return json.loads(Path(p).read_text()) - return None - - -def lateral_extent(conductors: list, P: dict | None) -> float: - """L of the thickness fit (definition stored in the parameters; default sqrt of the total conductor area).""" - import shapely - - S = shapely.union_all(conductors) - how = (P or {}).get("thickness", {}).get("L_definition", "sqrt_area") - x0, y0, x1, y1 = S.bounds - return float({"sqrt_area": np.sqrt(S.area), "bbox_diag": np.hypot(x1 - x0, y1 - y0), - "bbox_max": max(x1 - x0, y1 - y0)}.get(how, np.sqrt(S.area))) - - -def material_residual_pct(P: dict, eps_sub: float) -> float: - x = abs(np.log(eps_factor(eps_sub))) - m = P["material"] - return 0.0 if x < 1e-9 else float(m["slope_pct_per_log"] * x + m["floor_pct"]) - - -def thickness_residual_pct(P: dict, t_um: float, L_um: float) -> float: - th = P["thickness"] - if t_um >= T_TRAIN: - return float(th["thick_side_pct"]) if t_um > T_TRAIN * 1.01 else 0.0 - x = t_um / max(L_um, 1e-9) - x_ref = T_TRAIN / max(L_um, 1e-9) - r = th["A_pct"] * x ** (-th["p"]) - th["A_pct"] * x_ref ** (-th["p"]) - return float(max(r, 0.0)) - - -def breakdown_thickness_um(P: dict, L_um: float, base_pct: float) -> float: - """Thinnest substrate at which the thickness residual stays below sqrt(3) x base error (total error <= 2x base).""" - th = P["thickness"] - target = np.sqrt(3.0) * base_pct - xr = (T_TRAIN / L_um) ** (-th["p"]) - # A x^-p - A xr = target -> x = ((target / A) + xr)^(-1/p) - x = ((target / th["A_pct"]) + xr) ** (-1.0 / th["p"]) - return float(x * L_um) - - -def expected_error(P: dict | None, eps_sub: float, t_um: float, L_um: float, base: dict, mean_abs_ff: float, rms_ff: float) -> dict: - """base = the model's validation metrics {median_pct, mae_ff, rmse_ff} (never-seen set); mean_abs_ff / rms_ff = the - mean and rms of |mutual C| of THIS prediction (to scale the paper MAE/RMSE to this layout).""" - out = {"validation": base, "assumptions": []} - if P is None: - out["warning"] = "stack-error parameters not available" - return out - rm = material_residual_pct(P, eps_sub) - rt = thickness_residual_pct(P, t_um, L_um) - b = float(base["median_pct"]) - tot = float(np.sqrt(b**2 + rm**2 + rt**2)) - sc = P.get("base_scale", {}) - k_mae = mean_abs_ff / sc["never_seen_mean_abs_ff"] if sc.get("never_seen_mean_abs_ff") else np.nan - k_rms = rms_ff / sc["never_seen_rms_ff"] if sc.get("never_seen_rms_ff") else np.nan - # stack residuals as relative errors on this layout's entries: MAE ~ r * mean|C|, RMSE ~ r * rms|C| - rs = np.sqrt(rm**2 + rt**2) / 100 - mae = float(np.sqrt((base["mae_ff"] * k_mae) ** 2 + (rs * mean_abs_ff) ** 2)) - rmse = float(np.sqrt((base["rmse_ff"] * k_rms) ** 2 + (rs * rms_ff) ** 2)) - t_break = breakdown_thickness_um(P, L_um, b) - out.update({"material_residual_pct": rm, "thickness_residual_pct": rt, "expected_median_pct": tot, - "expected_mae_ff": mae, "expected_rmse_ff": rmse, "breakdown_thickness_um": t_break, - "breakdown": bool(t_um < t_break), "lateral_extent_um": float(L_um), "t_over_L": float(t_um / L_um), - "doe_designs": P.get("n_designs"), - "assumptions": ["errors add in quadrature (model, material, thickness)", - "material residual fitted on 11 substrates x 15 designs after the eps correction", - "thickness residual fitted vs t/L on 8 Si thicknesses x 15 designs (3 design groups)", - "MAE/RMSE scaled from the never-seen validation set by this layout's mean / rms |C|"]}) - if out["breakdown"]: - out["warning"] = (f"substrate {t_um:g} µm is below the breakdown thickness {t_break:.0f} µm for a layout of lateral " - f"extent {L_um:.0f} µm: the zero-shot prediction (training stack 350 µm) is not reliable here") - elif rt > b: - out["warning"] = f"finite-substrate error ({rt:.1f} %) exceeds the model error ({b:.1f} %)" - if not (2.0 <= eps_sub <= 30.0): - out.setdefault("warning", "") - out["warning"] += f" eps={eps_sub:g} is outside the validated range 3.8-24." - return out diff --git a/tlsq_infer/substrate.py b/tlsq_infer/substrate.py deleted file mode 100644 index 187c7eeba7d5a0a8335c9f0a435becd3120ebd4f..0000000000000000000000000000000000000000 --- a/tlsq_infer/substrate.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Substrate stacks other than the training stack (Si, eps_r 11.45, 350 um): the physics prior is solved at the requested -(eps_r, thickness) and the recipe's corrections are applied unchanged (the calibrated route, agents/v4stack; author decision -2026-11-03). No rescaling. Tested on the 15 held-out DoE designs: Si at 10-1000 um and eps_r 3.8-24 at 350 um (paper model); -other combinations are untested and warned. geomgnn.api.substrate_route is the same rule for the GNN models.""" - -from __future__ import annotations - -import math - -EPS_TRAIN, T_TRAIN = 11.45, 350.0 -TESTED_THICKNESS_UM = (10.0, 1000.0) -TESTED_EPS_R = (3.8, 24.0) -ROUTE = "calibrated: physics prior solved at the requested stack, corrections and features at the training stack" -CAVEAT = ("calibrated substrate route: the physics prior is solved at your stack and this recipe's corrections (fit on Si, eps_r 11.45, " - "350 um only) are applied unchanged. Scored with the paper model (not this recipe) on 15 held-out DoE designs: 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") -PHYSICS_CAVEAT = "physics prior alone (no fitted parameter), solved at your stack" - - -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) <= 1e-9 - - -def tested_stack(eps_r: float, thickness_um: float) -> bool: - 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) <= 1e-9 and TESTED_EPS_R[0] <= e <= TESTED_EPS_R[1]) - - -def route(eps_r: float, thickness_um: float, physics_only: bool = False) -> tuple[dict, list]: - """(substrate record, warnings) for a recipe that solves its prior at (eps_r, thickness_um).""" - e, t = float(eps_r), float(thickness_um) - if not (math.isfinite(e) and e >= 1.0): - raise ValueError(f"substrate eps_r must be a finite number >= 1 (got {eps_r!r})") - if not (math.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} - rec = {"eps_r": e, "thickness_um": t, "training_stack": train, "embedding_stack": dict(train), - "prior_solved_at": {"eps_r": e, "thickness_um": t}, "eps_rescale_factor": None, "tested": True} - if on_training_stack(e, t): - rec["route"] = "training stack" - return rec, [] - rec.update(route=ROUTE, tested=tested_stack(e, t), caveat=PHYSICS_CAVEAT if physics_only else 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:g} um): untested, its error is unknown") - return rec, w - - -def 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: " - if sub.get("route", "training stack") == "training stack": - return head + "the training stack" - return head + sub["route"] + ("" if sub.get("tested") else " (UNTESTED combination)") + f". {sub.get('caveat', '')}" diff --git a/warm.py b/warm.py deleted file mode 100644 index 397e6dcad66d20d0fbfaa245314b69ff8519e64e..0000000000000000000000000000000000000000 --- a/warm.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Build-time warm-up (Docker variant): the Space's own preload at import of app.py (every arm / tier on the interdigital -example: the prior's numba kernels, the NN kernel, the surrogates), so the image carries the compiled cache; then (flagship) the -examples' results baked for the response cache. Each step runs in its own process: the preload must succeed; the bake may fail -(e.g. the builder runs out of memory), and the image is then built without it (the Space computes the examples on demand).""" -import os -import resource -import subprocess -import sys -import time -from pathlib import Path - -os.environ["TLSQ_PRELOAD"] = "1" -t = time.perf_counter() -subprocess.run([sys.executable, "-c", "import app"], check=True) # noqa: S603 (app.py preloads at import; no server) -print("warm.py: preload and cache population", round(time.perf_counter() - t, 1), "s", flush=True) -t = time.perf_counter() -r = subprocess.run([sys.executable, "-c", "import app\nif hasattr(app, 'bake'):\n app.bake()"]) # noqa: S603 -peak = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss / 2**10 -if r.returncode: - Path(os.environ.get("TLSQ_RESPONSE_BAKE", "bake/respcache.pkl")).unlink(missing_ok=True) - print(f"warm.py: bake FAILED (exit {r.returncode}, e.g. out of memory): the image is built without baked example results", flush=True) -print("warm.py: bake step", round(time.perf_counter() - t, 1), "s, peak RSS of a step", round(peak), "MB", flush=True)