SQuADDS ML API 2: squadds 53ec2b11, registry 1dbf099a
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +3 -0
- .gitattributes +1 -0
- Dockerfile +16 -15
- README.md +49 -54
- app.py +2 -1
- artifacts/transmon_cross_hamiltonian_inverse/X_names +0 -2
- artifacts/transmon_cross_hamiltonian_inverse/model/best_inverse_model_surrogate_defined_loss.keras +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_anharmonicity_MHz.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_anharmonicity_MHz.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_qubit_frequency_GHz.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_qubit_frequency_GHz.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.cross_length_one_hot_encoding.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.claw_length.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.ground_spacing.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.cross_length.save +0 -0
- artifacts/transmon_cross_hamiltonian_inverse/y_columns.npy +0 -0
- bundle.lock.json +48 -0
- deployment_manifest.json +0 -161
- examples/interdigital.gds +0 -0
- examples/planar_capacitance_fast.json +103 -0
- examples/planar_capacitance_flagship.json +104 -0
- examples/transmon_cross_hamiltonian_inverse.json +48 -0
- registry.yaml +149 -0
- requirements.txt +19 -3
- squadds_ml_api/__init__.py +1 -2
- squadds_ml_api/adapters/__init__.py +0 -0
- squadds_ml_api/adapters/base.py +18 -0
- squadds_ml_api/adapters/keras_tabular.py +121 -0
- squadds_ml_api/api.py +396 -38
- squadds_ml_api/auth.py +39 -0
- squadds_ml_api/registry.py +172 -230
- squadds_ml_api/schemas.py +26 -1
- src/squadds/__init__.py +1 -0
- src/squadds/ml/__init__.py +34 -0
- src/squadds/ml/capacitance/__init__.py +55 -0
- src/squadds/ml/capacitance/_core/SOURCES.json +379 -0
- src/squadds/ml/capacitance/_core/__init__.py +6 -0
- src/squadds/ml/capacitance/_core/_spawn.py +40 -0
- src/squadds/ml/capacitance/_core/_tlsq/__init__.py +0 -0
- src/squadds/ml/capacitance/_core/_tlsq/embed/__init__.py +0 -0
- src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior.py +925 -0
- src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior_loc.py +210 -0
- src/squadds/ml/capacitance/_core/_tlsq/embed/proxy.py +944 -0
- src/squadds/ml/capacitance/_core/_tlsq/geometry.py +256 -0
- src/squadds/ml/capacitance/_core/_tlsq/uge/__init__.py +5 -0
- src/squadds/ml/capacitance/_core/_tlsq/uge/blocks.py +526 -0
- src/squadds/ml/capacitance/_core/_tlsq/uge/graph.py +74 -0
- src/squadds/ml/capacitance/_core/_tlsq/uge/localtok.py +126 -0
.dockerignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
**/__pycache__
|
| 2 |
+
**/*.pyc
|
| 3 |
+
**/.pytest_cache
|
.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.gds filter=lfs diff=lfs merge=lfs -text
|
Dockerfile
CHANGED
|
@@ -1,16 +1,17 @@
|
|
| 1 |
-
FROM python:3.
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
COPY . .
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
EXPOSE 7860
|
| 15 |
-
|
| 16 |
-
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
ARG TARGETARCH
|
| 3 |
+
# gdstk has no Linux arm64 wheel: compile it there (local arm64 builds only; HF builds amd64 and skips this)
|
| 4 |
+
RUN if [ "$TARGETARCH" != "amd64" ]; then apt-get update && apt-get install -y --no-install-recommends build-essential \
|
| 5 |
+
cmake zlib1g-dev libqhull-dev && rm -rf /var/lib/apt/lists/*; fi
|
| 6 |
+
RUN useradd -m -u 1000 user
|
| 7 |
+
USER user
|
| 8 |
+
ENV HOME=/home/user PATH=/home/user/.local/bin:$PATH PYTHONUNBUFFERED=1 PYTHONPATH=/home/user/app/src \
|
| 9 |
+
KERAS_BACKEND=torch NUMBA_CPU_NAME=generic NUMBA_CACHE_DIR=/home/user/app/numba_cache \
|
| 10 |
+
SQUADDS_ML_API_EXIT_ON_LOAD_FAILURE=1
|
| 11 |
+
WORKDIR /home/user/app
|
| 12 |
+
COPY --chown=user requirements.txt .
|
| 13 |
+
RUN pip install --no-cache-dir --user -r requirements.txt
|
| 14 |
+
COPY --chown=user . .
|
| 15 |
+
RUN python warm.py && date -u +%Y-%m-%dT%H:%M:%SZ > IMAGE_BUILT_AT
|
| 16 |
EXPOSE 7860
|
| 17 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
|
|
|
README.md
CHANGED
|
@@ -1,48 +1,30 @@
|
|
| 1 |
---
|
| 2 |
title: SQuADDS ML Inference API
|
|
|
|
|
|
|
|
|
|
| 3 |
sdk: docker
|
| 4 |
app_port: 7860
|
| 5 |
license: mit
|
|
|
|
| 6 |
---
|
| 7 |
|
| 8 |
# SQuADDS ML Inference API
|
| 9 |
|
| 10 |
-
|
| 11 |
|
| 12 |
-
|
| 13 |
|
| 14 |
-
|
| 15 |
|
| 16 |
-
-
|
| 17 |
-
- Space host: https://squadds-squadds-ml-inference-api.hf.space
|
| 18 |
-
|
| 19 |
-
## Endpoints
|
| 20 |
-
|
| 21 |
-
- `GET /health`
|
| 22 |
-
- `GET /models`
|
| 23 |
-
- `POST /predict`
|
| 24 |
-
|
| 25 |
-
## Quickstart
|
| 26 |
-
|
| 27 |
-
List models:
|
| 28 |
-
|
| 29 |
-
```bash
|
| 30 |
-
curl https://squadds-squadds-ml-inference-api.hf.space/models
|
| 31 |
-
```
|
| 32 |
-
|
| 33 |
-
## Included Models
|
| 34 |
-
|
| 35 |
-
Run a sample prediction:
|
| 36 |
|
| 37 |
```bash
|
| 38 |
-
curl -X POST \
|
| 39 |
-
https://squadds-squadds-ml-inference-api.hf.space/predict \
|
| 40 |
-H 'Content-Type: application/json' \
|
| 41 |
-
-d '{"model_id": "transmon_cross_hamiltonian_inverse", "inputs": {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}
|
| 42 |
```
|
| 43 |
|
| 44 |
-
Sample response:
|
| 45 |
-
|
| 46 |
```json
|
| 47 |
{
|
| 48 |
"model_id": "transmon_cross_hamiltonian_inverse",
|
|
@@ -54,34 +36,47 @@ Sample response:
|
|
| 54 |
"design_options.cross_length": 0.0002005973074119538
|
| 55 |
}
|
| 56 |
],
|
| 57 |
-
"metadata": {
|
| 58 |
-
"input_order": [
|
| 59 |
-
"qubit_frequency_GHz",
|
| 60 |
-
"anharmonicity_MHz"
|
| 61 |
-
],
|
| 62 |
-
"output_order": [
|
| 63 |
-
"design_options.connection_pads.readout.claw_length",
|
| 64 |
-
"design_options.connection_pads.readout.ground_spacing",
|
| 65 |
-
"design_options.cross_length"
|
| 66 |
-
],
|
| 67 |
-
"input_units": {
|
| 68 |
-
"qubit_frequency_GHz": "GHz",
|
| 69 |
-
"anharmonicity_MHz": "MHz"
|
| 70 |
-
},
|
| 71 |
-
"output_units": {
|
| 72 |
-
"design_options.connection_pads.readout.claw_length": "m",
|
| 73 |
-
"design_options.connection_pads.readout.ground_spacing": "m",
|
| 74 |
-
"design_options.cross_length": "m"
|
| 75 |
-
},
|
| 76 |
-
"num_predictions": 1
|
| 77 |
-
}
|
| 78 |
}
|
| 79 |
```
|
| 80 |
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
##
|
| 84 |
|
| 85 |
-
|
| 86 |
-
- `coupler_ncap_cap_matrix_inverse`: No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras
|
| 87 |
-
- `cavity_claw_route_meander_inverse`: No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate.keras, model/best_keras_model_model2_surrogate.keras
|
|
|
|
| 1 |
---
|
| 2 |
title: SQuADDS ML Inference API
|
| 3 |
+
emoji: 🧪
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: gray
|
| 6 |
sdk: docker
|
| 7 |
app_port: 7860
|
| 8 |
license: mit
|
| 9 |
+
short_description: REST API for the machine-learning models of SQuADDS
|
| 10 |
---
|
| 11 |
|
| 12 |
# SQuADDS ML Inference API
|
| 13 |
|
| 14 |
+
A REST API for machine-learning models trained on SQuADDS data. Send JSON and get predictions back. The API is free and needs no sign-in.
|
| 15 |
|
| 16 |
+
## TransmonCross Hamiltonian to geometry
|
| 17 |
|
| 18 |
+
The first model served here is `transmon_cross_hamiltonian_inverse`. It takes a target qubit frequency (GHz) and anharmonicity (MHz) and predicts the TransmonCross geometry that gives them, in meters: the readout claw length, the claw ground spacing and the cross length. Feed those values straight into SQuADDS or Qiskit Metal.
|
| 19 |
|
| 20 |
+
The model was developed in collaboration with Taylor Patti, Nicola Pancotti, Enectali Figueroa-Feliciano, Sara Sussman, Abhishek Chakraborty, Olivia Seidel, Firas Abouzahr, Eli Levenson-Falk and Sadman Ahmed Shanto. Olivia Seidel and Firas Abouzahr trained it. The weights are in the model repo [SQuADDS/transmon-cross-hamiltonian-inverse](https://huggingface.co/SQuADDS/transmon-cross-hamiltonian-inverse).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
```bash
|
| 23 |
+
curl -X POST https://squadds-squadds-ml-inference-api.hf.space/predict \
|
|
|
|
| 24 |
-H 'Content-Type: application/json' \
|
| 25 |
+
-d '{"model_id": "transmon_cross_hamiltonian_inverse", "inputs": {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}}'
|
| 26 |
```
|
| 27 |
|
|
|
|
|
|
|
| 28 |
```json
|
| 29 |
{
|
| 30 |
"model_id": "transmon_cross_hamiltonian_inverse",
|
|
|
|
| 36 |
"design_options.cross_length": 0.0002005973074119538
|
| 37 |
}
|
| 38 |
],
|
| 39 |
+
"metadata": {"input_order": ["qubit_frequency_GHz", "anharmonicity_MHz"], "num_predictions": 1, "...": "..."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
}
|
| 41 |
```
|
| 42 |
|
| 43 |
+
`inputs` can also be a list of up to 1000 objects. Add `"options": {"include_scaled_outputs": true}` to get the raw scaled outputs too.
|
| 44 |
+
|
| 45 |
+
## Endpoints
|
| 46 |
+
|
| 47 |
+
These routes work as before:
|
| 48 |
+
|
| 49 |
+
- `GET /health` lists the ready models.
|
| 50 |
+
- `GET /models` lists every model with its status and units.
|
| 51 |
+
- `POST /predict` runs a model, as in the example above.
|
| 52 |
+
|
| 53 |
+
The `/v1` routes work the same way for every model:
|
| 54 |
+
|
| 55 |
+
- `GET /v1/models` lists the models, and `GET /v1/models/{model_id}` describes one.
|
| 56 |
+
- `GET /v1/models/{model_id}/schema` gives the request schema. Add `?format=tool` for a ready agent tool definition.
|
| 57 |
+
- `POST /v1/models/{model_id}/predict` takes `{"inputs": {...}, "options": {...}}`.
|
| 58 |
+
- `GET /v1/health` reports the state of each model and the build.
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
curl -X POST https://squadds-squadds-ml-inference-api.hf.space/v1/models/transmon_cross_hamiltonian_inverse/predict \
|
| 62 |
+
-H 'Content-Type: application/json' \
|
| 63 |
+
-d '{"inputs": {"qubit_frequency_GHz": 4.85, "anharmonicity_MHz": -205.0}}'
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
The answer has the predictions under `outputs`, the names and units under `metadata`, and the time taken under `timing_s`. Errors come back as `{"error": {"code": ..., "message": ...}}`. Interactive documentation is at `/docs`.
|
| 67 |
+
|
| 68 |
+
More SQuADDS models will be added to this API.
|
| 69 |
+
|
| 70 |
+
## Limits
|
| 71 |
+
|
| 72 |
+
Requests run one at a time, and a repeated request is answered from a cache. Each address can send 60 requests per minute. When the queue is full the API answers 429 with a `Retry-After` header.
|
| 73 |
+
|
| 74 |
+
## Links
|
| 75 |
+
|
| 76 |
+
- Code: [github.com/LFL-Lab/SQuADDS](https://github.com/LFL-Lab/SQuADDS)
|
| 77 |
+
- Documentation: [ML models in SQuADDS](https://lfl-lab.github.io/SQuADDS/source/ml_models.html)
|
| 78 |
+
- Organization: [huggingface.co/SQuADDS](https://huggingface.co/SQuADDS)
|
| 79 |
|
| 80 |
+
## Licence
|
| 81 |
|
| 82 |
+
MIT.
|
|
|
|
|
|
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
|
|
| 1 |
from pathlib import Path
|
| 2 |
|
| 3 |
from squadds_ml_api.api import create_app
|
| 4 |
|
| 5 |
-
|
| 6 |
app = create_app(Path(__file__).resolve().parent)
|
|
|
|
| 1 |
+
import logging
|
| 2 |
from pathlib import Path
|
| 3 |
|
| 4 |
from squadds_ml_api.api import create_app
|
| 5 |
|
| 6 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s %(message)s")
|
| 7 |
app = create_app(Path(__file__).resolve().parent)
|
artifacts/transmon_cross_hamiltonian_inverse/X_names
DELETED
|
@@ -1,2 +0,0 @@
|
|
| 1 |
-
qubit_frequency_GHz
|
| 2 |
-
anharmonicity_MHz
|
|
|
|
|
|
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/model/best_inverse_model_surrogate_defined_loss.keras
DELETED
|
Binary file (20.8 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_anharmonicity_MHz.save
DELETED
|
Binary file (1.04 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_anharmonicity_MHz.save
DELETED
|
Binary file (1.04 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_linear_qubit_frequency_GHz.save
DELETED
|
Binary file (1.04 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_X_qubit_frequency_GHz.save
DELETED
|
Binary file (1.04 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save
DELETED
|
Binary file (1.07 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save
DELETED
|
Binary file (1.07 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_design_options.cross_length_one_hot_encoding.save
DELETED
|
Binary file (1.06 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.claw_length.save
DELETED
|
Binary file (1.07 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.connection_pads.readout.ground_spacing.save
DELETED
|
Binary file (1.07 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/scalers/scaler_y_linear_design_options.cross_length.save
DELETED
|
Binary file (1.06 kB)
|
|
|
artifacts/transmon_cross_hamiltonian_inverse/y_columns.npy
DELETED
|
Binary file (433 Bytes)
|
|
|
bundle.lock.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"built_at": "2026-11-14T18:10:35+00:00",
|
| 3 |
+
"squadds": {
|
| 4 |
+
"commit": "53ec2b11f5d2c212e314d858e632c327b97714cc",
|
| 5 |
+
"dirty": false,
|
| 6 |
+
"dirty_files": []
|
| 7 |
+
},
|
| 8 |
+
"registry_sha256": "1dbf099ad5fb9ed2abd1610c1bbfaefb6a5d40ca702d10c11770342ff7ebf7da",
|
| 9 |
+
"models": {
|
| 10 |
+
"transmon_cross_hamiltonian_inverse": {
|
| 11 |
+
"visibility": "public",
|
| 12 |
+
"repo_id": "SQuADDS/transmon-cross-hamiltonian-inverse",
|
| 13 |
+
"revision": "26f2e04eb09ccd816e1c39ca7aa90a88bd737171",
|
| 14 |
+
"files": {
|
| 15 |
+
"inference_manifest.json": "093d984b6e9372ba1f601742a68cfa3f222be9ac7ff3f756be3b87a4acf433fb",
|
| 16 |
+
"model/best_inverse_model_surrogate_defined_loss.keras": "20442b08a83b9d8cba43f5fe4594d04566184b0d4ed399a80b2106ff4f4bda30",
|
| 17 |
+
"X_names": "6eff9d4082d11593ca562b1bb1edb582c1f2033bbee28b6fd65d84c523af4bad",
|
| 18 |
+
"y_columns.npy": "b0ac62e1f9f61d878633cb24cdc9ae9c942dacb7c12cc521b0d8f23bafcc3755",
|
| 19 |
+
"scalers/scaler_X_qubit_frequency_GHz.save": "de2428fcc998fcb6108969fe7d7746e7dcece44b6aeaff2e4c5bcbf91e50f5fc",
|
| 20 |
+
"scalers/scaler_X_anharmonicity_MHz.save": "0386abd75ab411717739b1091a19d510da081038c29e0063685b0cb774fe47d9",
|
| 21 |
+
"scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save": "9576bc4393c987ebf765612df6bb6f0ad3c93de5e5ffcf01c14d5bdf804cd892",
|
| 22 |
+
"scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save": "a38fcfcd1c4ef4b0ed7814dced91a110ee9033da8d5ebb319c14859e9ff786c2",
|
| 23 |
+
"scalers/scaler_y_design_options.cross_length_one_hot_encoding.save": "356bf37ad04ec755d37bc5a09f282bca015c3c8c542e050a110f4ede51a2c1b8"
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
"planar_capacitance_flagship": {
|
| 27 |
+
"visibility": "hidden",
|
| 28 |
+
"repo_id": "SQuADDS/PlanarCapacitance-flagship",
|
| 29 |
+
"revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc",
|
| 30 |
+
"files": {
|
| 31 |
+
"accurate/acc_v2m_sf_s0.pt": "cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5",
|
| 32 |
+
"accurate/acc_v2m_sf_s1.pt": "2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57",
|
| 33 |
+
"accurate/acc_v2m_sf_s2.pt": "d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed"
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"planar_capacitance_fast": {
|
| 37 |
+
"visibility": "hidden",
|
| 38 |
+
"repo_id": "SQuADDS/PlanarCapacitance-flagship",
|
| 39 |
+
"revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc",
|
| 40 |
+
"files": {
|
| 41 |
+
"fast/acc_v1_s0.pt": "9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba",
|
| 42 |
+
"fast/acc_v1_s1.pt": "f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe",
|
| 43 |
+
"fast/acc_v1_s2.pt": "8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4",
|
| 44 |
+
"fast/sall_all_s0.pt": "132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac"
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
}
|
deployment_manifest.json
DELETED
|
@@ -1,161 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"generated_at": "2026-04-11T02:52:17.016202+00:00",
|
| 3 |
-
"space": {
|
| 4 |
-
"repo_id": "SQuADDS/squadds-ml-inference-api",
|
| 5 |
-
"title": "SQuADDS ML Inference API",
|
| 6 |
-
"sdk": "docker",
|
| 7 |
-
"app_port": 7860,
|
| 8 |
-
"license": "mit",
|
| 9 |
-
"host": "https://squadds-squadds-ml-inference-api.hf.space",
|
| 10 |
-
"repo_url": "https://huggingface.co/spaces/SQuADDS/squadds-ml-inference-api"
|
| 11 |
-
},
|
| 12 |
-
"models": [
|
| 13 |
-
{
|
| 14 |
-
"id": "transmon_cross_hamiltonian_inverse",
|
| 15 |
-
"display_name": "TransmonCross Hamiltonian to Geometry",
|
| 16 |
-
"description": "Inverse model that predicts TransmonCross geometry parameters from target Hamiltonian values.",
|
| 17 |
-
"artifact_dir": "artifacts/transmon_cross_hamiltonian_inverse",
|
| 18 |
-
"model_path": "model/best_inverse_model_surrogate_defined_loss.keras",
|
| 19 |
-
"input_names_path": "X_names",
|
| 20 |
-
"input_names_format": "text_lines",
|
| 21 |
-
"output_names_path": "y_columns.npy",
|
| 22 |
-
"output_names_format": "npy",
|
| 23 |
-
"x_scaler_pattern": "scalers/scaler_X_{name}.save",
|
| 24 |
-
"y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save",
|
| 25 |
-
"input_units": {
|
| 26 |
-
"qubit_frequency_GHz": "GHz",
|
| 27 |
-
"anharmonicity_MHz": "MHz"
|
| 28 |
-
},
|
| 29 |
-
"output_units": {
|
| 30 |
-
"design_options.connection_pads.readout.claw_length": "m",
|
| 31 |
-
"design_options.connection_pads.readout.ground_spacing": "m",
|
| 32 |
-
"design_options.cross_length": "m"
|
| 33 |
-
},
|
| 34 |
-
"sample_request": {
|
| 35 |
-
"model_id": "transmon_cross_hamiltonian_inverse",
|
| 36 |
-
"inputs": {
|
| 37 |
-
"qubit_frequency_GHz": 4.85,
|
| 38 |
-
"anharmonicity_MHz": -205.0
|
| 39 |
-
},
|
| 40 |
-
"options": {
|
| 41 |
-
"include_scaled_outputs": false
|
| 42 |
-
}
|
| 43 |
-
},
|
| 44 |
-
"sample_response": {
|
| 45 |
-
"model_id": "transmon_cross_hamiltonian_inverse",
|
| 46 |
-
"display_name": "TransmonCross Hamiltonian to Geometry",
|
| 47 |
-
"predictions": [
|
| 48 |
-
{
|
| 49 |
-
"design_options.connection_pads.readout.claw_length": 0.00011072495544794947,
|
| 50 |
-
"design_options.connection_pads.readout.ground_spacing": 4.571595582092414e-06,
|
| 51 |
-
"design_options.cross_length": 0.0002005973074119538
|
| 52 |
-
}
|
| 53 |
-
],
|
| 54 |
-
"metadata": {
|
| 55 |
-
"input_order": [
|
| 56 |
-
"qubit_frequency_GHz",
|
| 57 |
-
"anharmonicity_MHz"
|
| 58 |
-
],
|
| 59 |
-
"output_order": [
|
| 60 |
-
"design_options.connection_pads.readout.claw_length",
|
| 61 |
-
"design_options.connection_pads.readout.ground_spacing",
|
| 62 |
-
"design_options.cross_length"
|
| 63 |
-
],
|
| 64 |
-
"input_units": {
|
| 65 |
-
"qubit_frequency_GHz": "GHz",
|
| 66 |
-
"anharmonicity_MHz": "MHz"
|
| 67 |
-
},
|
| 68 |
-
"output_units": {
|
| 69 |
-
"design_options.connection_pads.readout.claw_length": "m",
|
| 70 |
-
"design_options.connection_pads.readout.ground_spacing": "m",
|
| 71 |
-
"design_options.cross_length": "m"
|
| 72 |
-
},
|
| 73 |
-
"num_predictions": 1
|
| 74 |
-
}
|
| 75 |
-
},
|
| 76 |
-
"status": "ready",
|
| 77 |
-
"status_detail": "",
|
| 78 |
-
"tags": [
|
| 79 |
-
"inverse-design",
|
| 80 |
-
"transmon",
|
| 81 |
-
"hamiltonian"
|
| 82 |
-
],
|
| 83 |
-
"prediction_output_index": 0
|
| 84 |
-
},
|
| 85 |
-
{
|
| 86 |
-
"id": "transmon_cross_cap_matrix_inverse",
|
| 87 |
-
"display_name": "TransmonCross Cap Matrix to Geometry",
|
| 88 |
-
"description": "Inverse model that predicts TransmonCross geometry parameters from cap matrix targets.",
|
| 89 |
-
"artifact_dir": "",
|
| 90 |
-
"model_path": "",
|
| 91 |
-
"input_names_path": "X_names",
|
| 92 |
-
"input_names_format": "text_lines",
|
| 93 |
-
"output_names_path": "y_columns.npy",
|
| 94 |
-
"output_names_format": "npy",
|
| 95 |
-
"x_scaler_pattern": "scalers/scaler_X_{name}.save",
|
| 96 |
-
"y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save",
|
| 97 |
-
"input_units": {},
|
| 98 |
-
"output_units": {},
|
| 99 |
-
"sample_request": null,
|
| 100 |
-
"sample_response": null,
|
| 101 |
-
"status": "missing_model_artifact",
|
| 102 |
-
"status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras",
|
| 103 |
-
"tags": [
|
| 104 |
-
"inverse-design",
|
| 105 |
-
"transmon",
|
| 106 |
-
"cap-matrix"
|
| 107 |
-
],
|
| 108 |
-
"prediction_output_index": 0
|
| 109 |
-
},
|
| 110 |
-
{
|
| 111 |
-
"id": "coupler_ncap_cap_matrix_inverse",
|
| 112 |
-
"display_name": "NCap Coupler Cap Matrix to Geometry",
|
| 113 |
-
"description": "Inverse model that predicts NCap coupler geometry from cap matrix targets.",
|
| 114 |
-
"artifact_dir": "",
|
| 115 |
-
"model_path": "",
|
| 116 |
-
"input_names_path": "X_names",
|
| 117 |
-
"input_names_format": "text_lines",
|
| 118 |
-
"output_names_path": "y_columns.npy",
|
| 119 |
-
"output_names_format": "npy",
|
| 120 |
-
"x_scaler_pattern": "scalers/scaler_X_{name}.save",
|
| 121 |
-
"y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save",
|
| 122 |
-
"input_units": {},
|
| 123 |
-
"output_units": {},
|
| 124 |
-
"sample_request": null,
|
| 125 |
-
"sample_response": null,
|
| 126 |
-
"status": "missing_model_artifact",
|
| 127 |
-
"status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras",
|
| 128 |
-
"tags": [
|
| 129 |
-
"inverse-design",
|
| 130 |
-
"coupler",
|
| 131 |
-
"cap-matrix"
|
| 132 |
-
],
|
| 133 |
-
"prediction_output_index": 0
|
| 134 |
-
},
|
| 135 |
-
{
|
| 136 |
-
"id": "cavity_claw_route_meander_inverse",
|
| 137 |
-
"display_name": "Cavity Claw RouteMeander Targets to Geometry",
|
| 138 |
-
"description": "Inverse model that predicts cavity claw RouteMeander geometry from target cavity frequency and kappa.",
|
| 139 |
-
"artifact_dir": "",
|
| 140 |
-
"model_path": "",
|
| 141 |
-
"input_names_path": "X_names",
|
| 142 |
-
"input_names_format": "text_lines",
|
| 143 |
-
"output_names_path": "y_columns.npy",
|
| 144 |
-
"output_names_format": "npy",
|
| 145 |
-
"x_scaler_pattern": "scalers/scaler_X_{name}.save",
|
| 146 |
-
"y_scaler_pattern": "scalers/scaler_y_{name}_one_hot_encoding.save",
|
| 147 |
-
"input_units": {},
|
| 148 |
-
"output_units": {},
|
| 149 |
-
"sample_request": null,
|
| 150 |
-
"sample_response": null,
|
| 151 |
-
"status": "missing_model_artifact",
|
| 152 |
-
"status_detail": "No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate.keras, model/best_keras_model_model2_surrogate.keras",
|
| 153 |
-
"tags": [
|
| 154 |
-
"inverse-design",
|
| 155 |
-
"cavity",
|
| 156 |
-
"readout"
|
| 157 |
-
],
|
| 158 |
-
"prediction_output_index": 0
|
| 159 |
-
}
|
| 160 |
-
]
|
| 161 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
examples/interdigital.gds
ADDED
|
Binary file (4.25 kB). View file
|
|
|
examples/planar_capacitance_fast.json
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"file": "examples/interdigital.gds",
|
| 3 |
+
"request": {
|
| 4 |
+
"inputs": {}
|
| 5 |
+
},
|
| 6 |
+
"response": {
|
| 7 |
+
"model_id": "planar_capacitance_fast",
|
| 8 |
+
"family": "planar_capacitance",
|
| 9 |
+
"revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc",
|
| 10 |
+
"outputs": {
|
| 11 |
+
"names": [
|
| 12 |
+
"G",
|
| 13 |
+
"C1",
|
| 14 |
+
"C2"
|
| 15 |
+
],
|
| 16 |
+
"matrix_fF": [
|
| 17 |
+
[
|
| 18 |
+
31.592315673828125,
|
| 19 |
+
-4.261831760406494,
|
| 20 |
+
-5.681989669799805
|
| 21 |
+
],
|
| 22 |
+
[
|
| 23 |
+
-4.261831760406494,
|
| 24 |
+
6.577047824859619,
|
| 25 |
+
-2.2709009647369385
|
| 26 |
+
],
|
| 27 |
+
[
|
| 28 |
+
-5.681989669799805,
|
| 29 |
+
-2.2709009647369385,
|
| 30 |
+
7.988653659820557
|
| 31 |
+
]
|
| 32 |
+
],
|
| 33 |
+
"units": "fF",
|
| 34 |
+
"convention": "Maxwell matrix, ground first (row and column 0), nets never merged",
|
| 35 |
+
"sim_results": {
|
| 36 |
+
"C1_to_C1": 6.577047824859619,
|
| 37 |
+
"C1_to_C2": 2.2709009647369385,
|
| 38 |
+
"C1_to_ground": 4.261831760406494,
|
| 39 |
+
"C2_to_C2": 7.988653659820557,
|
| 40 |
+
"C2_to_ground": 5.681989669799805,
|
| 41 |
+
"ground_to_ground": 31.592315673828125,
|
| 42 |
+
"maxwell_matrix": {
|
| 43 |
+
"C_G_G": 31.592315673828125,
|
| 44 |
+
"C_G_C1": -4.261831760406494,
|
| 45 |
+
"C_G_C2": -5.681989669799805,
|
| 46 |
+
"C_C1_G": -4.261831760406494,
|
| 47 |
+
"C_C1_C1": 6.577047824859619,
|
| 48 |
+
"C_C1_C2": -2.2709009647369385,
|
| 49 |
+
"C_C2_G": -5.681989669799805,
|
| 50 |
+
"C_C2_C1": -2.2709009647369385,
|
| 51 |
+
"C_C2_C2": 7.988653659820557
|
| 52 |
+
},
|
| 53 |
+
"units": "fF"
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"metadata": {
|
| 57 |
+
"n_conductors": 3,
|
| 58 |
+
"checks": {
|
| 59 |
+
"symmetric_max_abs": 0.0,
|
| 60 |
+
"symmetric": true,
|
| 61 |
+
"diagonal_positive": true,
|
| 62 |
+
"offdiag_all_negative": true,
|
| 63 |
+
"closure_min_row_sum": 0.03576302528381348,
|
| 64 |
+
"closure": true,
|
| 65 |
+
"signal_block_min_eig": 4.904795034420886,
|
| 66 |
+
"positive_definite": true,
|
| 67 |
+
"passed": true
|
| 68 |
+
},
|
| 69 |
+
"warnings": [
|
| 70 |
+
"Use the fast model only for quick screening of the component families it was trained on (interdigital, paddle, concentric, star, multipad star, Xmon, TransmonPocket, shielded concentric, two-net, random, procedurally generated and synthetic campaign layouts). On new designs of a trained family (B5) it was worse than the physics alone, 3.175 % (MAE 0.583 / RMSE 0.824 fF) against 1.765 % (0.275 / 0.376 fF), and the paper's version of it was worse than the physics alone on a held-out family too, 3.11 % (0.533 / 0.633 fF) against 1.55 % (0.166 / 0.205 fF). Use the flagship model for anything that matters.",
|
| 71 |
+
"metal on layer 2/0 inside the window is not assigned (ground / conductor) and is ignored",
|
| 72 |
+
"metal on layer 3/0 inside the window is not assigned (ground / conductor) and is ignored"
|
| 73 |
+
],
|
| 74 |
+
"substrate": {
|
| 75 |
+
"eps_r": 11.45,
|
| 76 |
+
"thickness_um": 350.0,
|
| 77 |
+
"training_stack": {
|
| 78 |
+
"eps_r": 11.45,
|
| 79 |
+
"thickness_um": 350.0
|
| 80 |
+
},
|
| 81 |
+
"embedding_stack": {
|
| 82 |
+
"eps_r": 11.45,
|
| 83 |
+
"thickness_um": 350.0
|
| 84 |
+
},
|
| 85 |
+
"tested": true,
|
| 86 |
+
"route": "training stack",
|
| 87 |
+
"prior_solved_at": null,
|
| 88 |
+
"eps_rescale_factor": 1.0
|
| 89 |
+
},
|
| 90 |
+
"ground_detection": null,
|
| 91 |
+
"threads": 2,
|
| 92 |
+
"prior_version": "learned prior surrogate",
|
| 93 |
+
"weights_sha256": [
|
| 94 |
+
"9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba",
|
| 95 |
+
"f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe",
|
| 96 |
+
"8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4"
|
| 97 |
+
],
|
| 98 |
+
"learned_prior_sha256": "132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac"
|
| 99 |
+
}
|
| 100 |
+
},
|
| 101 |
+
"rtol": 1e-05,
|
| 102 |
+
"note": "generated on macOS arm64 (Apple M5 Pro, 2 threads) with squadds.ml.capacitance.serving; priors on x86 differ by up to ~2.4e-3 relative, so compare with rtol 5e-3 there"
|
| 103 |
+
}
|
examples/planar_capacitance_flagship.json
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"file": "examples/interdigital.gds",
|
| 3 |
+
"request": {
|
| 4 |
+
"inputs": {}
|
| 5 |
+
},
|
| 6 |
+
"response": {
|
| 7 |
+
"model_id": "planar_capacitance_flagship",
|
| 8 |
+
"family": "planar_capacitance",
|
| 9 |
+
"revision": "bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc",
|
| 10 |
+
"outputs": {
|
| 11 |
+
"names": [
|
| 12 |
+
"G",
|
| 13 |
+
"C1",
|
| 14 |
+
"C2"
|
| 15 |
+
],
|
| 16 |
+
"matrix_fF": [
|
| 17 |
+
[
|
| 18 |
+
31.726598739624023,
|
| 19 |
+
-4.264019012451172,
|
| 20 |
+
-5.710771560668945
|
| 21 |
+
],
|
| 22 |
+
[
|
| 23 |
+
-4.264019012451172,
|
| 24 |
+
6.598451614379883,
|
| 25 |
+
-2.2851016521453857
|
| 26 |
+
],
|
| 27 |
+
[
|
| 28 |
+
-5.710771560668945,
|
| 29 |
+
-2.2851016521453857,
|
| 30 |
+
8.045040130615234
|
| 31 |
+
]
|
| 32 |
+
],
|
| 33 |
+
"units": "fF",
|
| 34 |
+
"convention": "Maxwell matrix, ground first (row and column 0), nets never merged",
|
| 35 |
+
"sim_results": {
|
| 36 |
+
"C1_to_C1": 6.598451614379883,
|
| 37 |
+
"C1_to_C2": 2.2851016521453857,
|
| 38 |
+
"C1_to_ground": 4.264019012451172,
|
| 39 |
+
"C2_to_C2": 8.045040130615234,
|
| 40 |
+
"C2_to_ground": 5.710771560668945,
|
| 41 |
+
"ground_to_ground": 31.726598739624023,
|
| 42 |
+
"maxwell_matrix": {
|
| 43 |
+
"C_G_G": 31.726598739624023,
|
| 44 |
+
"C_G_C1": -4.264019012451172,
|
| 45 |
+
"C_G_C2": -5.710771560668945,
|
| 46 |
+
"C_C1_G": -4.264019012451172,
|
| 47 |
+
"C_C1_C1": 6.598451614379883,
|
| 48 |
+
"C_C1_C2": -2.2851016521453857,
|
| 49 |
+
"C_C2_G": -5.710771560668945,
|
| 50 |
+
"C_C2_C1": -2.2851016521453857,
|
| 51 |
+
"C_C2_C2": 8.045040130615234
|
| 52 |
+
},
|
| 53 |
+
"units": "fF"
|
| 54 |
+
}
|
| 55 |
+
},
|
| 56 |
+
"metadata": {
|
| 57 |
+
"n_conductors": 3,
|
| 58 |
+
"checks": {
|
| 59 |
+
"symmetric_max_abs": 0.0,
|
| 60 |
+
"symmetric": true,
|
| 61 |
+
"diagonal_positive": true,
|
| 62 |
+
"offdiag_all_negative": true,
|
| 63 |
+
"closure_min_row_sum": 0.04916691780090332,
|
| 64 |
+
"closure": true,
|
| 65 |
+
"signal_block_min_eig": 4.924905422141389,
|
| 66 |
+
"positive_definite": true,
|
| 67 |
+
"passed": true
|
| 68 |
+
},
|
| 69 |
+
"warnings": [
|
| 70 |
+
"metal on layer 2/0 inside the window is not assigned (ground / conductor) and is ignored",
|
| 71 |
+
"metal on layer 3/0 inside the window is not assigned (ground / conductor) and is ignored"
|
| 72 |
+
],
|
| 73 |
+
"substrate": {
|
| 74 |
+
"eps_r": 11.45,
|
| 75 |
+
"thickness_um": 350.0,
|
| 76 |
+
"training_stack": {
|
| 77 |
+
"eps_r": 11.45,
|
| 78 |
+
"thickness_um": 350.0
|
| 79 |
+
},
|
| 80 |
+
"embedding_stack": {
|
| 81 |
+
"eps_r": 11.45,
|
| 82 |
+
"thickness_um": 350.0
|
| 83 |
+
},
|
| 84 |
+
"tested": true,
|
| 85 |
+
"route": "training stack",
|
| 86 |
+
"prior_solved_at": {
|
| 87 |
+
"eps_r": 11.45,
|
| 88 |
+
"thickness_um": 350.0
|
| 89 |
+
},
|
| 90 |
+
"eps_rescale_factor": 1.0
|
| 91 |
+
},
|
| 92 |
+
"ground_detection": null,
|
| 93 |
+
"threads": 2,
|
| 94 |
+
"prior_version": "v2m_sf_fc_dipfill_margin_slabfar",
|
| 95 |
+
"weights_sha256": [
|
| 96 |
+
"cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5",
|
| 97 |
+
"2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57",
|
| 98 |
+
"d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed"
|
| 99 |
+
]
|
| 100 |
+
}
|
| 101 |
+
},
|
| 102 |
+
"rtol": 1e-05,
|
| 103 |
+
"note": "generated on macOS arm64 (Apple M5 Pro, 2 threads) with squadds.ml.capacitance.serving; priors on x86 differ by up to ~2.4e-3 relative, so compare with rtol 5e-3 there"
|
| 104 |
+
}
|
examples/transmon_cross_hamiltonian_inverse.json
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"request": {
|
| 3 |
+
"inputs": {
|
| 4 |
+
"qubit_frequency_GHz": 4.85,
|
| 5 |
+
"anharmonicity_MHz": -205.0
|
| 6 |
+
},
|
| 7 |
+
"options": {
|
| 8 |
+
"include_scaled_outputs": false
|
| 9 |
+
}
|
| 10 |
+
},
|
| 11 |
+
"response": {
|
| 12 |
+
"model_id": "transmon_cross_hamiltonian_inverse",
|
| 13 |
+
"family": "keras_tabular",
|
| 14 |
+
"revision": "26f2e04eb09ccd816e1c39ca7aa90a88bd737171",
|
| 15 |
+
"outputs": {
|
| 16 |
+
"predictions": [
|
| 17 |
+
{
|
| 18 |
+
"design_options.connection_pads.readout.claw_length": 0.00011072495544794947,
|
| 19 |
+
"design_options.connection_pads.readout.ground_spacing": 4.571595582092414e-06,
|
| 20 |
+
"design_options.cross_length": 0.0002005973074119538
|
| 21 |
+
}
|
| 22 |
+
]
|
| 23 |
+
},
|
| 24 |
+
"metadata": {
|
| 25 |
+
"input_order": [
|
| 26 |
+
"qubit_frequency_GHz",
|
| 27 |
+
"anharmonicity_MHz"
|
| 28 |
+
],
|
| 29 |
+
"output_order": [
|
| 30 |
+
"design_options.connection_pads.readout.claw_length",
|
| 31 |
+
"design_options.connection_pads.readout.ground_spacing",
|
| 32 |
+
"design_options.cross_length"
|
| 33 |
+
],
|
| 34 |
+
"input_units": {
|
| 35 |
+
"qubit_frequency_GHz": "GHz",
|
| 36 |
+
"anharmonicity_MHz": "MHz"
|
| 37 |
+
},
|
| 38 |
+
"output_units": {
|
| 39 |
+
"design_options.connection_pads.readout.claw_length": "m",
|
| 40 |
+
"design_options.connection_pads.readout.ground_spacing": "m",
|
| 41 |
+
"design_options.cross_length": "m"
|
| 42 |
+
},
|
| 43 |
+
"num_predictions": 1
|
| 44 |
+
}
|
| 45 |
+
},
|
| 46 |
+
"rtol": 1e-05,
|
| 47 |
+
"note": "the stored sample response of the model's inference_manifest.json"
|
| 48 |
+
}
|
registry.yaml
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Generated by build.py from deploy/squadds_ml_api/registry.yaml (weights.from_manifest expanded).
|
| 2 |
+
version: 1
|
| 3 |
+
models:
|
| 4 |
+
transmon_cross_hamiltonian_inverse:
|
| 5 |
+
family: keras_tabular
|
| 6 |
+
adapter: squadds_ml_api.adapters.keras_tabular:Adapter
|
| 7 |
+
display_name: TransmonCross Hamiltonian to Geometry
|
| 8 |
+
description: Inverse model that predicts TransmonCross geometry parameters from target Hamiltonian values.
|
| 9 |
+
tags:
|
| 10 |
+
- inverse-design
|
| 11 |
+
- transmon
|
| 12 |
+
- hamiltonian
|
| 13 |
+
visibility: public
|
| 14 |
+
weights:
|
| 15 |
+
repo_id: SQuADDS/transmon-cross-hamiltonian-inverse
|
| 16 |
+
revision: 26f2e04eb09ccd816e1c39ca7aa90a88bd737171
|
| 17 |
+
files:
|
| 18 |
+
- path: inference_manifest.json
|
| 19 |
+
sha256: 093d984b6e9372ba1f601742a68cfa3f222be9ac7ff3f756be3b87a4acf433fb
|
| 20 |
+
- path: model/best_inverse_model_surrogate_defined_loss.keras
|
| 21 |
+
sha256: 20442b08a83b9d8cba43f5fe4594d04566184b0d4ed399a80b2106ff4f4bda30
|
| 22 |
+
- path: X_names
|
| 23 |
+
sha256: 6eff9d4082d11593ca562b1bb1edb582c1f2033bbee28b6fd65d84c523af4bad
|
| 24 |
+
- path: y_columns.npy
|
| 25 |
+
sha256: b0ac62e1f9f61d878633cb24cdc9ae9c942dacb7c12cc521b0d8f23bafcc3755
|
| 26 |
+
- path: scalers/scaler_X_qubit_frequency_GHz.save
|
| 27 |
+
sha256: de2428fcc998fcb6108969fe7d7746e7dcece44b6aeaff2e4c5bcbf91e50f5fc
|
| 28 |
+
- path: scalers/scaler_X_anharmonicity_MHz.save
|
| 29 |
+
sha256: 0386abd75ab411717739b1091a19d510da081038c29e0063685b0cb774fe47d9
|
| 30 |
+
- path: scalers/scaler_y_design_options.connection_pads.readout.claw_length_one_hot_encoding.save
|
| 31 |
+
sha256: 9576bc4393c987ebf765612df6bb6f0ad3c93de5e5ffcf01c14d5bdf804cd892
|
| 32 |
+
- path: scalers/scaler_y_design_options.connection_pads.readout.ground_spacing_one_hot_encoding.save
|
| 33 |
+
sha256: a38fcfcd1c4ef4b0ed7814dced91a110ee9033da8d5ebb319c14859e9ff786c2
|
| 34 |
+
- path: scalers/scaler_y_design_options.cross_length_one_hot_encoding.save
|
| 35 |
+
sha256: 356bf37ad04ec755d37bc5a09f282bca015c3c8c542e050a110f4ede51a2c1b8
|
| 36 |
+
config:
|
| 37 |
+
manifest: inference_manifest.json
|
| 38 |
+
limits:
|
| 39 |
+
max_batch_rows: 1000
|
| 40 |
+
legacy_predict: true
|
| 41 |
+
warm: examples/transmon_cross_hamiltonian_inverse.json
|
| 42 |
+
example: examples/transmon_cross_hamiltonian_inverse.json
|
| 43 |
+
transmon_cross_cap_matrix_inverse:
|
| 44 |
+
display_name: TransmonCross Cap Matrix to Geometry
|
| 45 |
+
description: Inverse model that predicts TransmonCross geometry parameters from cap matrix targets.
|
| 46 |
+
tags:
|
| 47 |
+
- inverse-design
|
| 48 |
+
- transmon
|
| 49 |
+
- cap-matrix
|
| 50 |
+
visibility: hidden
|
| 51 |
+
status: missing_model_artifact
|
| 52 |
+
status_detail: 'No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras'
|
| 53 |
+
legacy_predict: true
|
| 54 |
+
coupler_ncap_cap_matrix_inverse:
|
| 55 |
+
display_name: NCap Coupler Cap Matrix to Geometry
|
| 56 |
+
description: Inverse model that predicts NCap coupler geometry from cap matrix targets.
|
| 57 |
+
tags:
|
| 58 |
+
- inverse-design
|
| 59 |
+
- coupler
|
| 60 |
+
- cap-matrix
|
| 61 |
+
visibility: hidden
|
| 62 |
+
status: missing_model_artifact
|
| 63 |
+
status_detail: 'No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate_defined_loss.keras, model/best_keras_model_model2_surrogate.keras'
|
| 64 |
+
legacy_predict: true
|
| 65 |
+
cavity_claw_route_meander_inverse:
|
| 66 |
+
display_name: Cavity Claw RouteMeander Targets to Geometry
|
| 67 |
+
description: Inverse model that predicts cavity claw RouteMeander geometry from target cavity frequency and kappa.
|
| 68 |
+
tags:
|
| 69 |
+
- inverse-design
|
| 70 |
+
- cavity
|
| 71 |
+
- readout
|
| 72 |
+
visibility: hidden
|
| 73 |
+
status: missing_model_artifact
|
| 74 |
+
status_detail: 'No model checkpoint found. Expected one of: model/best_keras_model_one_hot_encoding.keras, model/best_keras_model_surrogate.keras, model/best_keras_model_model2_surrogate.keras'
|
| 75 |
+
legacy_predict: true
|
| 76 |
+
planar_capacitance_flagship:
|
| 77 |
+
family: planar_capacitance
|
| 78 |
+
adapter: squadds.ml.capacitance.serving:Adapter
|
| 79 |
+
display_name: Planar capacitance, flagship (Accurate)
|
| 80 |
+
description: GDS layout in, full Maxwell capacitance matrix out (fF, ground first, nets never merged).
|
| 81 |
+
tags:
|
| 82 |
+
- capacitance
|
| 83 |
+
- gds
|
| 84 |
+
- graph-neural-network
|
| 85 |
+
visibility: hidden
|
| 86 |
+
weights:
|
| 87 |
+
repo_id: SQuADDS/PlanarCapacitance-flagship
|
| 88 |
+
revision: bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc
|
| 89 |
+
files:
|
| 90 |
+
- path: accurate/acc_v2m_sf_s0.pt
|
| 91 |
+
sha256: cc69c5818f5028c26177159b88239116520abbb290743d6a6c091657e8dbf1c5
|
| 92 |
+
- path: accurate/acc_v2m_sf_s1.pt
|
| 93 |
+
sha256: 2f88606dbec5c599550d088213a4c37af3b3ad5134ebad2e60519fb534553a57
|
| 94 |
+
- path: accurate/acc_v2m_sf_s2.pt
|
| 95 |
+
sha256: d13bafc6b2eb7cadcd97a387d791c0210976db1a9d618f9acc1b614e3701daed
|
| 96 |
+
source: squadds/ml/capacitance/manifest.json#models.flagship
|
| 97 |
+
config:
|
| 98 |
+
model: flagship
|
| 99 |
+
threads: 2
|
| 100 |
+
limits:
|
| 101 |
+
max_upload_mb: 20
|
| 102 |
+
max_conductors: 70
|
| 103 |
+
numbers:
|
| 104 |
+
error_39_new_layouts:
|
| 105 |
+
median_pct: 1.05
|
| 106 |
+
mae_fF: 0.132
|
| 107 |
+
rmse_fF: 0.188
|
| 108 |
+
median_time_s: 1.1
|
| 109 |
+
source: 39 generated layouts (rings with a neighbour, 3 or 4 conductors) that no part of the model saw in training; median time on two CPUs of an Intel Xeon E5-2640 v4 cluster node, not on this Space
|
| 110 |
+
warm: examples/interdigital.gds
|
| 111 |
+
example: examples/planar_capacitance_flagship.json
|
| 112 |
+
planar_capacitance_fast:
|
| 113 |
+
family: planar_capacitance
|
| 114 |
+
adapter: squadds.ml.capacitance.serving:Adapter
|
| 115 |
+
display_name: Planar capacitance, fast
|
| 116 |
+
description: GDS layout in, full Maxwell capacitance matrix out, without a field solve. For quick screening of the trained component families only.
|
| 117 |
+
tags:
|
| 118 |
+
- capacitance
|
| 119 |
+
- gds
|
| 120 |
+
- graph-neural-network
|
| 121 |
+
visibility: hidden
|
| 122 |
+
weights:
|
| 123 |
+
repo_id: SQuADDS/PlanarCapacitance-flagship
|
| 124 |
+
revision: bb9d0ce792d9803d8e76d4e6cfc8580ae5b102fc
|
| 125 |
+
files:
|
| 126 |
+
- path: fast/acc_v1_s0.pt
|
| 127 |
+
sha256: 9dff20ade26619e7713c2d145dada65e4554a623780290673cfe9452cf9b64ba
|
| 128 |
+
- path: fast/acc_v1_s1.pt
|
| 129 |
+
sha256: f1ad2ca065dd650ccabcad73a3c6ad2ac1042f4f68bb828893bbdecc47411ffe
|
| 130 |
+
- path: fast/acc_v1_s2.pt
|
| 131 |
+
sha256: 8cbada211724df5cc05a7b4fdd232607de047b248a43993d3844bd68ff8060c4
|
| 132 |
+
- path: fast/sall_all_s0.pt
|
| 133 |
+
sha256: 132d6f389eda798d31bd5654a96e24cce18fa750134a9fb2a9725eafed339dac
|
| 134 |
+
source: squadds/ml/capacitance/manifest.json#models.fast
|
| 135 |
+
config:
|
| 136 |
+
model: fast
|
| 137 |
+
threads: 2
|
| 138 |
+
limits:
|
| 139 |
+
max_upload_mb: 20
|
| 140 |
+
max_conductors: 70
|
| 141 |
+
numbers:
|
| 142 |
+
error_39_new_layouts:
|
| 143 |
+
median_pct: 3.175
|
| 144 |
+
mae_fF: 0.583
|
| 145 |
+
rmse_fF: 0.824
|
| 146 |
+
median_time_s: 0.24
|
| 147 |
+
source: 39 generated layouts (rings with a neighbour, 3 or 4 conductors) that no part of the model saw in training; median time on two CPUs of an Intel Xeon E5-2640 v4 cluster node, not on this Space
|
| 148 |
+
warm: examples/interdigital.gds
|
| 149 |
+
example: examples/planar_capacitance_fast.json
|
requirements.txt
CHANGED
|
@@ -1,7 +1,23 @@
|
|
|
|
|
|
|
|
| 1 |
fastapi==0.115.12
|
| 2 |
uvicorn[standard]==0.34.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
numpy==1.26.4
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
keras==3.11.3
|
| 7 |
-
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
# serving
|
| 3 |
fastapi==0.115.12
|
| 4 |
uvicorn[standard]==0.34.0
|
| 5 |
+
python-multipart==0.0.20
|
| 6 |
+
pydantic>=2
|
| 7 |
+
pyyaml
|
| 8 |
+
huggingface_hub
|
| 9 |
+
httpx==0.28.1
|
| 10 |
+
# planar_capacitance (squadds[ml], vendored under src/)
|
| 11 |
+
torch==2.8.0
|
| 12 |
numpy==1.26.4
|
| 13 |
+
scipy
|
| 14 |
+
shapely>=2.0
|
| 15 |
+
gdstk==1.0.2
|
| 16 |
+
pandas
|
| 17 |
+
numba==0.68.0
|
| 18 |
+
llvmlite==0.50.0
|
| 19 |
+
threadpoolctl
|
| 20 |
+
# keras_tabular (Keras 3 on the torch backend, KERAS_BACKEND=torch; scikit-learn pinned to the version that pickled the scalers)
|
| 21 |
keras==3.11.3
|
| 22 |
+
scikit-learn==1.6.1
|
| 23 |
+
joblib==1.4.2
|
squadds_ml_api/__init__.py
CHANGED
|
@@ -1,2 +1 @@
|
|
| 1 |
-
"""
|
| 2 |
-
|
|
|
|
| 1 |
+
"""SQuADDS ML API: one registry-driven FastAPI app for every SQuADDS model."""
|
|
|
squadds_ml_api/adapters/__init__.py
ADDED
|
File without changes
|
squadds_ml_api/adapters/base.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The adapter protocol (duck-typed; tests/test_registry.py enforces it).
|
| 2 |
+
|
| 3 |
+
class Adapter:
|
| 4 |
+
input_kind: "json" | "file" json: inputs is an object (or a list when batch = True); file: one uploaded file + inputs
|
| 5 |
+
InputModel: pydantic model request schema of `inputs` (drives /docs, validation and the tool schema)
|
| 6 |
+
OptionsModel: pydantic model optional, schema of `options`
|
| 7 |
+
batch: bool optional, inputs may be a list of objects
|
| 8 |
+
|
| 9 |
+
def __init__(self, model_id, root, config, limits) root = verified local weights
|
| 10 |
+
def describe(self) -> dict merged into GET /v1/models/{id}
|
| 11 |
+
def predict(self, inputs, file=None, options=None) -> {"outputs": {...}, "metadata": {...}, "timing_s": {...}}
|
| 12 |
+
def warm(self, example: Path) -> None optional
|
| 13 |
+
|
| 14 |
+
predict validates its own raw inputs: pydantic.ValidationError -> 422, ValueError -> 400, a ValueError with
|
| 15 |
+
`too_large = True` -> 413, anything else -> 500.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
REQUIRED = ("input_kind", "describe", "predict")
|
squadds_ml_api/adapters/keras_tabular.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tabular Keras models with joblib scalers (ML_qubit_design): JSON parameters in, JSON parameters out."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import joblib
|
| 10 |
+
import numpy as np
|
| 11 |
+
from pydantic import BaseModel, ConfigDict, Field, create_model
|
| 12 |
+
|
| 13 |
+
os.environ.setdefault("KERAS_BACKEND", "torch")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Options(BaseModel):
|
| 17 |
+
include_scaled_outputs: bool = Field(
|
| 18 |
+
default=False, description="Include raw scaled model outputs alongside inverse-transformed values."
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class TooLarge(ValueError):
|
| 23 |
+
too_large = True
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _read_names(path: Path, fmt: str) -> list[str]:
|
| 27 |
+
if fmt == "text_lines":
|
| 28 |
+
return [line.strip() for line in path.read_text().splitlines() if line.strip()]
|
| 29 |
+
if fmt == "csv_header":
|
| 30 |
+
return [item.strip() for item in path.read_text().splitlines()[0].split(",") if item.strip()]
|
| 31 |
+
if fmt == "npy":
|
| 32 |
+
return [str(item) for item in np.load(path, allow_pickle=True).tolist()]
|
| 33 |
+
raise ValueError(f"Unsupported name file format: {fmt}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Adapter:
|
| 37 |
+
input_kind = "json"
|
| 38 |
+
batch = True
|
| 39 |
+
OptionsModel = Options
|
| 40 |
+
|
| 41 |
+
def __init__(self, model_id: str, root: Path, config: dict, limits: dict):
|
| 42 |
+
import keras
|
| 43 |
+
|
| 44 |
+
root = Path(root)
|
| 45 |
+
m = json.loads((root / config.get("manifest", "inference_manifest.json")).read_text())
|
| 46 |
+
self.model_id = model_id
|
| 47 |
+
self.input_names = _read_names(root / m["input_names_path"], m["input_names_format"])
|
| 48 |
+
self.output_names = _read_names(root / m["output_names_path"], m["output_names_format"])
|
| 49 |
+
self.input_units = m.get("input_units", {})
|
| 50 |
+
self.output_units = m.get("output_units", {})
|
| 51 |
+
self.output_index = int(m.get("prediction_output_index", 0))
|
| 52 |
+
self.model = keras.models.load_model(root / m["model_path"], compile=False)
|
| 53 |
+
xp, yp = m.get("x_scaler_pattern"), m.get("y_scaler_pattern")
|
| 54 |
+
self.x_scalers = [joblib.load(root / xp.format(name=n)) for n in self.input_names] if xp else None
|
| 55 |
+
self.y_scalers = [joblib.load(root / yp.format(name=n)) for n in self.output_names] if yp else None
|
| 56 |
+
self.max_rows = int(limits.get("max_batch_rows", 1000))
|
| 57 |
+
self.backend = f"keras {keras.__version__} ({keras.backend.backend()})"
|
| 58 |
+
fields = {
|
| 59 |
+
f"x{i}": (float, Field(..., alias=n, description=f"{n} ({self.input_units[n]})" if n in self.input_units else n))
|
| 60 |
+
for i, n in enumerate(self.input_names)
|
| 61 |
+
}
|
| 62 |
+
self.InputModel = create_model(f"{model_id}_inputs", __config__=ConfigDict(extra="forbid"), **fields)
|
| 63 |
+
|
| 64 |
+
def describe(self) -> dict:
|
| 65 |
+
return {
|
| 66 |
+
"input_order": self.input_names,
|
| 67 |
+
"output_order": self.output_names,
|
| 68 |
+
"input_units": self.input_units,
|
| 69 |
+
"output_units": self.output_units,
|
| 70 |
+
"runtime": self.backend,
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
def _rows(self, inputs) -> list[dict]:
|
| 74 |
+
rows = inputs if isinstance(inputs, list) else [inputs]
|
| 75 |
+
if len(rows) > self.max_rows:
|
| 76 |
+
raise TooLarge(f"batch of {len(rows)} rows; this server takes at most {self.max_rows}")
|
| 77 |
+
out = []
|
| 78 |
+
for index, row in enumerate(rows):
|
| 79 |
+
if not isinstance(row, dict):
|
| 80 |
+
raise ValueError(f"Each input row must be an object, got {type(row).__name__} at index {index}.")
|
| 81 |
+
missing = [n for n in self.input_names if n not in row]
|
| 82 |
+
extras = [n for n in row if n not in self.input_names]
|
| 83 |
+
if missing or extras:
|
| 84 |
+
raise ValueError(
|
| 85 |
+
f"Model '{self.model_id}' expects inputs {self.input_names}. "
|
| 86 |
+
f"Missing: {missing or 'none'}. Extra: {extras or 'none'}."
|
| 87 |
+
)
|
| 88 |
+
try:
|
| 89 |
+
out.append({n: float(row[n]) for n in self.input_names})
|
| 90 |
+
except (TypeError, ValueError) as exc:
|
| 91 |
+
raise ValueError(f"Input values must be numbers: {exc}") from exc
|
| 92 |
+
return out
|
| 93 |
+
|
| 94 |
+
def predict(self, inputs, file: bytes | None = None, options: dict | None = None) -> dict:
|
| 95 |
+
opts = Options.model_validate(options or {})
|
| 96 |
+
rows = self._rows(inputs)
|
| 97 |
+
X = np.array([[r[n] for n in self.input_names] for r in rows], dtype=np.float64)
|
| 98 |
+
if self.x_scalers:
|
| 99 |
+
X = np.column_stack([s.transform(X[:, [j]])[:, 0] for j, s in enumerate(self.x_scalers)])
|
| 100 |
+
raw = self.model.predict(X.astype(np.float32), verbose=0)
|
| 101 |
+
scaled = np.asarray(raw[self.output_index] if isinstance(raw, list) else raw)
|
| 102 |
+
Y = np.asarray(scaled, dtype=np.float32).copy()
|
| 103 |
+
if self.y_scalers:
|
| 104 |
+
for j, s in enumerate(self.y_scalers):
|
| 105 |
+
Y[:, j] = s.inverse_transform(Y[:, j].reshape(-1, 1)).reshape(-1)
|
| 106 |
+
outputs = {"predictions": [{n: float(Y[i, j]) for j, n in enumerate(self.output_names)} for i in range(len(Y))]}
|
| 107 |
+
if opts.include_scaled_outputs:
|
| 108 |
+
outputs["scaled_predictions"] = [
|
| 109 |
+
{n: float(scaled[i, j]) for j, n in enumerate(self.output_names)} for i in range(len(scaled))
|
| 110 |
+
]
|
| 111 |
+
metadata = {
|
| 112 |
+
"input_order": self.input_names,
|
| 113 |
+
"output_order": self.output_names,
|
| 114 |
+
"input_units": self.input_units,
|
| 115 |
+
"output_units": self.output_units,
|
| 116 |
+
"num_predictions": len(outputs["predictions"]),
|
| 117 |
+
}
|
| 118 |
+
return {"outputs": outputs, "metadata": metadata}
|
| 119 |
+
|
| 120 |
+
def warm(self, example: Path) -> None:
|
| 121 |
+
self.predict(json.loads(Path(example).read_text())["request"]["inputs"])
|
squadds_ml_api/api.py
CHANGED
|
@@ -1,61 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from pathlib import Path
|
| 2 |
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
app = FastAPI(
|
| 13 |
-
title=
|
| 14 |
-
version="0.
|
| 15 |
-
description=
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
),
|
| 19 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
@app.get("/")
|
| 22 |
-
def
|
| 23 |
return {
|
| 24 |
-
"service":
|
| 25 |
"docs": "/docs",
|
|
|
|
|
|
|
|
|
|
| 26 |
"models_endpoint": "/models",
|
| 27 |
"predict_endpoint": "/predict",
|
| 28 |
}
|
| 29 |
|
| 30 |
-
@app.get("/health")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
def health() -> dict:
|
| 32 |
-
return {
|
| 33 |
-
"status": "ok",
|
| 34 |
-
"available_models": registry.available_model_ids(),
|
| 35 |
-
"bundle_root": str(bundle_root),
|
| 36 |
-
}
|
| 37 |
|
| 38 |
-
@app.get("/models")
|
| 39 |
def list_models() -> dict:
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
@app.post("/predict")
|
| 43 |
-
def predict(
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
-
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
| 52 |
-
except BundleConfigError as exc:
|
| 53 |
-
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
| 54 |
-
except Exception as exc:
|
| 55 |
raise HTTPException(
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI factory: the /v1 routes, the legacy routes of the original Space, errors, limits, queue and cache."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import binascii
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import os
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
from collections import OrderedDict
|
| 14 |
+
from contextlib import asynccontextmanager
|
| 15 |
from pathlib import Path
|
| 16 |
|
| 17 |
+
import pydantic
|
| 18 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 19 |
+
from fastapi.exception_handlers import request_validation_exception_handler
|
| 20 |
+
from fastapi.exceptions import RequestValidationError
|
| 21 |
+
from fastapi.responses import JSONResponse
|
| 22 |
+
from starlette.concurrency import run_in_threadpool
|
| 23 |
+
|
| 24 |
+
from .auth import Gate, bearer
|
| 25 |
+
from .registry import Model, Registry
|
| 26 |
+
from .schemas import ApiError, PredictionRequest, PredictResponse
|
| 27 |
+
|
| 28 |
+
log = logging.getLogger("squadds_ml_api")
|
| 29 |
+
SERVICE = "SQuADDS ML API"
|
| 30 |
+
MB = 2**20
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Runner:
|
| 34 |
+
"""One prediction at a time; at most `depth` requests in flight (running + waiting), the next one gets 429."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, depth: int):
|
| 37 |
+
self.lock = threading.Lock()
|
| 38 |
+
self.slots = threading.BoundedSemaphore(depth)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Cache:
|
| 42 |
+
def __init__(self, size: int = 64):
|
| 43 |
+
self.size, self.data, self.lock = size, OrderedDict(), threading.Lock()
|
| 44 |
+
|
| 45 |
+
def get(self, k):
|
| 46 |
+
with self.lock:
|
| 47 |
+
if k in self.data:
|
| 48 |
+
self.data.move_to_end(k)
|
| 49 |
+
return self.data[k]
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
def put(self, k, v):
|
| 53 |
+
with self.lock:
|
| 54 |
+
self.data[k] = v
|
| 55 |
+
while len(self.data) > self.size:
|
| 56 |
+
self.data.popitem(last=False)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class RateLimiter:
|
| 60 |
+
"""Token bucket per client IP: `per_minute` requests, refilled continuously (0 disables it)."""
|
| 61 |
|
| 62 |
+
def __init__(self, per_minute: int):
|
| 63 |
+
self.rate, self.buckets, self.lock = per_minute, {}, threading.Lock()
|
| 64 |
|
| 65 |
+
def allow(self, ip: str) -> bool:
|
| 66 |
+
if self.rate <= 0:
|
| 67 |
+
return True
|
| 68 |
+
now = time.monotonic()
|
| 69 |
+
with self.lock:
|
| 70 |
+
tokens, last = self.buckets.get(ip, (float(self.rate), now))
|
| 71 |
+
tokens = min(float(self.rate), tokens + (now - last) * self.rate / 60.0)
|
| 72 |
+
ok = tokens >= 1.0
|
| 73 |
+
self.buckets[ip] = (tokens - 1.0 if ok else tokens, now)
|
| 74 |
+
if len(self.buckets) > 10000:
|
| 75 |
+
self.buckets.clear()
|
| 76 |
+
return ok
|
| 77 |
|
| 78 |
+
|
| 79 |
+
def client_ip(request: Request) -> str:
|
| 80 |
+
fwd = request.headers.get("x-forwarded-for")
|
| 81 |
+
return fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "?")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
PREDICT_OPENAPI = {
|
| 85 |
+
"requestBody": {
|
| 86 |
+
"required": True,
|
| 87 |
+
"content": {
|
| 88 |
+
"application/json": {
|
| 89 |
+
"schema": {
|
| 90 |
+
"type": "object",
|
| 91 |
+
"properties": {
|
| 92 |
+
"inputs": {"description": "The model's inputs (see GET /v1/models/{model_id}/schema); file "
|
| 93 |
+
"models take the file as inputs.file_base64"},
|
| 94 |
+
"options": {"type": "object"},
|
| 95 |
+
},
|
| 96 |
+
"required": ["inputs"],
|
| 97 |
+
}
|
| 98 |
+
},
|
| 99 |
+
"multipart/form-data": {
|
| 100 |
+
"schema": {
|
| 101 |
+
"type": "object",
|
| 102 |
+
"properties": {
|
| 103 |
+
"file": {"type": "string", "format": "binary"},
|
| 104 |
+
"inputs": {"type": "string", "description": "JSON of the other input fields"},
|
| 105 |
+
"options": {"type": "string", "description": "JSON of the options"},
|
| 106 |
+
},
|
| 107 |
+
"required": ["file"],
|
| 108 |
+
}
|
| 109 |
+
},
|
| 110 |
+
},
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def create_app(root: Path, registry_file: Path | None = None, load: bool = True) -> FastAPI:
|
| 116 |
+
root = Path(root)
|
| 117 |
+
reg = Registry(root, registry_file or os.environ.get("SQUADDS_ML_API_REGISTRY"))
|
| 118 |
+
gate = Gate(os.environ.get("SQUADDS_ML_API_ORG", "SQuADDS"))
|
| 119 |
+
depth = int(os.environ.get("SQUADDS_ML_API_QUEUE", "8"))
|
| 120 |
+
runner = Runner(depth)
|
| 121 |
+
cache = Cache(int(os.environ.get("SQUADDS_ML_API_CACHE", "64")))
|
| 122 |
+
limiter = RateLimiter(int(os.environ.get("SQUADDS_ML_API_RATE_PER_MIN", "60")))
|
| 123 |
+
built = root / "IMAGE_BUILT_AT"
|
| 124 |
+
build_info = {
|
| 125 |
+
"squadds_commit": reg.lock_info.get("squadds", {}).get("commit"),
|
| 126 |
+
"squadds_dirty": reg.lock_info.get("squadds", {}).get("dirty"),
|
| 127 |
+
"registry_sha256": reg.sha256,
|
| 128 |
+
"image_built_at": built.read_text().strip() if built.exists() else None,
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
@asynccontextmanager
|
| 132 |
+
async def lifespan(_app):
|
| 133 |
+
if load:
|
| 134 |
+
reg.start(exit_on_failure=os.environ.get("SQUADDS_ML_API_EXIT_ON_LOAD_FAILURE") == "1")
|
| 135 |
+
yield
|
| 136 |
|
| 137 |
app = FastAPI(
|
| 138 |
+
title=SERVICE,
|
| 139 |
+
version="2.0.0",
|
| 140 |
+
description="HTTP API for the machine-learning models of SQuADDS. Every model is an entry of the registry; "
|
| 141 |
+
"`/v1` is the API, and the original routes `/health`, `/models` and `/predict` are kept unchanged.",
|
| 142 |
+
lifespan=lifespan,
|
|
|
|
| 143 |
)
|
| 144 |
+
app.state.registry, app.state.cache, app.state.runner = reg, cache, runner
|
| 145 |
+
|
| 146 |
+
@app.exception_handler(ApiError)
|
| 147 |
+
async def _api_error(_request: Request, exc: ApiError):
|
| 148 |
+
return JSONResponse(exc.body(), status_code=exc.status, headers=exc.headers)
|
| 149 |
+
|
| 150 |
+
@app.exception_handler(RequestValidationError)
|
| 151 |
+
async def _validation(request: Request, exc: RequestValidationError):
|
| 152 |
+
if request.url.path.startswith("/v1"):
|
| 153 |
+
err = ApiError(422, "validation_error", "the request does not match the schema",
|
| 154 |
+
request.path_params.get("model_id"), details=jsonable(exc.errors()))
|
| 155 |
+
return JSONResponse(err.body(), status_code=422)
|
| 156 |
+
return await request_validation_exception_handler(request, exc)
|
| 157 |
+
|
| 158 |
+
def member(request: Request) -> bool | None:
|
| 159 |
+
tok = bearer(request.headers)
|
| 160 |
+
if tok is None:
|
| 161 |
+
return None
|
| 162 |
+
try:
|
| 163 |
+
return gate.is_member(tok)
|
| 164 |
+
except Exception as exc: # noqa: BLE001
|
| 165 |
+
raise ApiError(503, "loading", f"could not verify the token with Hugging Face: {exc}",
|
| 166 |
+
headers={"Retry-After": "30"}) from exc
|
| 167 |
+
|
| 168 |
+
def visible(m: Model, who: bool | None) -> bool:
|
| 169 |
+
return m.status == "ready" and (m.visibility == "public" or (m.visibility == "gated" and who is True))
|
| 170 |
+
|
| 171 |
+
def access(model_id: str, request: Request, need_ready: bool = True) -> Model:
|
| 172 |
+
m = reg.models.get(model_id)
|
| 173 |
+
if m is None or m.visibility == "hidden" or m.status != "ready":
|
| 174 |
+
raise ApiError(404, "unknown_model", f"unknown model '{model_id}'", model_id)
|
| 175 |
+
if m.visibility == "gated":
|
| 176 |
+
who = member(request)
|
| 177 |
+
if who is None:
|
| 178 |
+
raise ApiError(401, "auth_required", "this model needs 'Authorization: Bearer <Hugging Face token>' "
|
| 179 |
+
"of a member of the SQuADDS organization", model_id)
|
| 180 |
+
if not who:
|
| 181 |
+
raise ApiError(403, "forbidden", "this token does not belong to a member of the SQuADDS organization",
|
| 182 |
+
model_id)
|
| 183 |
+
if need_ready and m.state != "ready":
|
| 184 |
+
if m.state == "failed":
|
| 185 |
+
raise ApiError(500, "inference_error", f"model failed to load: {m.error}", model_id)
|
| 186 |
+
raise ApiError(503, "loading", "the model is still loading", model_id, headers={"Retry-After": "10"})
|
| 187 |
+
return m
|
| 188 |
+
|
| 189 |
+
def entry(m: Model) -> dict:
|
| 190 |
+
s = m.spec
|
| 191 |
+
return {
|
| 192 |
+
"id": m.id,
|
| 193 |
+
"family": s.get("family"),
|
| 194 |
+
"display_name": s["display_name"],
|
| 195 |
+
"description": s["description"],
|
| 196 |
+
"tags": s.get("tags", []),
|
| 197 |
+
"input_kind": getattr(m.adapter_cls, "input_kind", None),
|
| 198 |
+
"visibility": m.visibility,
|
| 199 |
+
"revision": m.revision,
|
| 200 |
+
"status": m.state,
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
def rate(request: Request) -> None:
|
| 204 |
+
if not limiter.allow(client_ip(request)):
|
| 205 |
+
raise ApiError(429, "rate_limited", f"more than {limiter.rate} requests per minute from this address",
|
| 206 |
+
headers={"Retry-After": "60"})
|
| 207 |
+
|
| 208 |
+
def run_predict(m: Model, inputs, options, data: bytes | None) -> dict:
|
| 209 |
+
t0 = time.perf_counter()
|
| 210 |
+
key = hashlib.sha256(json.dumps([m.id, m.revision, inputs, options], sort_keys=True, default=str).encode()
|
| 211 |
+
+ (data or b"")).hexdigest()
|
| 212 |
+
|
| 213 |
+
def hit(v):
|
| 214 |
+
return {**v, "timing_s": {"total": round(time.perf_counter() - t0, 6), "queue": 0.0}, "cached": True}
|
| 215 |
+
|
| 216 |
+
v = cache.get(key)
|
| 217 |
+
if v is not None:
|
| 218 |
+
return hit(v)
|
| 219 |
+
if not runner.slots.acquire(blocking=False):
|
| 220 |
+
raise ApiError(429, "busy", "the server is busy; retry later", m.id, headers={"Retry-After": "30"})
|
| 221 |
+
try:
|
| 222 |
+
tq = time.perf_counter()
|
| 223 |
+
with runner.lock:
|
| 224 |
+
queue_s = time.perf_counter() - tq
|
| 225 |
+
v = cache.get(key)
|
| 226 |
+
if v is not None:
|
| 227 |
+
return hit(v)
|
| 228 |
+
try:
|
| 229 |
+
out = m.adapter.predict(inputs, file=data, options=options)
|
| 230 |
+
except pydantic.ValidationError as exc:
|
| 231 |
+
raise ApiError(422, "validation_error", "the inputs do not match the schema", m.id,
|
| 232 |
+
details=jsonable(exc.errors())) from exc
|
| 233 |
+
except ValueError as exc:
|
| 234 |
+
if getattr(exc, "too_large", False):
|
| 235 |
+
raise ApiError(413, "too_large", str(exc), m.id) from exc
|
| 236 |
+
raise ApiError(400, "invalid_input", str(exc), m.id) from exc
|
| 237 |
+
except Exception as exc: # noqa: BLE001
|
| 238 |
+
log.exception("inference error in %s", m.id)
|
| 239 |
+
raise ApiError(500, "inference_error", f"{type(exc).__name__}: {exc}", m.id) from exc
|
| 240 |
+
finally:
|
| 241 |
+
runner.slots.release()
|
| 242 |
+
v = {
|
| 243 |
+
"model_id": m.id,
|
| 244 |
+
"family": m.spec["family"],
|
| 245 |
+
"revision": m.revision,
|
| 246 |
+
"outputs": out["outputs"],
|
| 247 |
+
"metadata": out.get("metadata", {}),
|
| 248 |
+
}
|
| 249 |
+
cache.put(key, v)
|
| 250 |
+
timing = {"total": round(time.perf_counter() - t0, 6), "queue": round(queue_s, 6)}
|
| 251 |
+
timing.update({k: round(x, 6) if isinstance(x, float) else x for k, x in (out.get("timing_s") or {}).items()})
|
| 252 |
+
return {**v, "timing_s": timing, "cached": False}
|
| 253 |
+
|
| 254 |
+
def request_schema(m: Model) -> dict:
|
| 255 |
+
ad = m.adapter
|
| 256 |
+
ins = ad.InputModel.model_json_schema()
|
| 257 |
+
if getattr(ad, "batch", False):
|
| 258 |
+
items = {"type": "array", "items": ins, "maxItems": m.limits.get("max_batch_rows", 1000)}
|
| 259 |
+
ins = {"anyOf": [ins, items]}
|
| 260 |
+
opts = ad.OptionsModel.model_json_schema() if getattr(ad, "OptionsModel", None) else {"type": "object"}
|
| 261 |
+
return {"type": "object", "properties": {"inputs": ins, "options": opts}, "required": ["inputs"]}
|
| 262 |
+
|
| 263 |
+
# ---------- root and /v1 ----------
|
| 264 |
|
| 265 |
@app.get("/")
|
| 266 |
+
def root_route() -> dict:
|
| 267 |
return {
|
| 268 |
+
"service": SERVICE,
|
| 269 |
"docs": "/docs",
|
| 270 |
+
"openapi": "/openapi.json",
|
| 271 |
+
"v1": {"health": "/v1/health", "models": "/v1/models", "model": "/v1/models/{model_id}",
|
| 272 |
+
"schema": "/v1/models/{model_id}/schema", "predict": "/v1/models/{model_id}/predict"},
|
| 273 |
"models_endpoint": "/models",
|
| 274 |
"predict_endpoint": "/predict",
|
| 275 |
}
|
| 276 |
|
| 277 |
+
@app.get("/v1/health", tags=["v1"])
|
| 278 |
+
def health_v1(request: Request) -> dict:
|
| 279 |
+
who = member(request)
|
| 280 |
+
return {"status": "ok", "models": {m.id: m.state for m in reg.models.values() if visible(m, who)},
|
| 281 |
+
"build": build_info}
|
| 282 |
+
|
| 283 |
+
@app.get("/v1/models", tags=["v1"])
|
| 284 |
+
def models_v1(request: Request) -> dict:
|
| 285 |
+
who = member(request)
|
| 286 |
+
return {"models": [entry(m) for m in reg.models.values() if visible(m, who)]}
|
| 287 |
+
|
| 288 |
+
@app.get("/v1/models/{model_id}", tags=["v1"])
|
| 289 |
+
def model_v1(model_id: str, request: Request) -> dict:
|
| 290 |
+
m = access(model_id, request)
|
| 291 |
+
out = {**entry(m), **m.adapter.describe(), "limits": {**m.limits, "queue_depth": depth}}
|
| 292 |
+
if m.spec.get("numbers"):
|
| 293 |
+
out["numbers"] = m.spec["numbers"]
|
| 294 |
+
if m.spec.get("example"):
|
| 295 |
+
ex = json.loads((root / m.spec["example"]).read_text())
|
| 296 |
+
out["example"] = {k: ex[k] for k in ("file", "request") if k in ex}
|
| 297 |
+
return out
|
| 298 |
+
|
| 299 |
+
@app.get("/v1/models/{model_id}/schema", tags=["v1"])
|
| 300 |
+
def schema_v1(model_id: str, request: Request, format: str = "json") -> dict:
|
| 301 |
+
m = access(model_id, request)
|
| 302 |
+
req = request_schema(m)
|
| 303 |
+
if format == "tool":
|
| 304 |
+
how = (" Send a GDS file as inputs.file_base64." if m.adapter.input_kind == "file" else "")
|
| 305 |
+
return {"name": f"squadds_{m.id}",
|
| 306 |
+
"description": f"{m.spec['display_name']}: {m.spec['description']} POST the input to "
|
| 307 |
+
f"/v1/models/{m.id}/predict.{how}",
|
| 308 |
+
"input_schema": req}
|
| 309 |
+
if format != "json":
|
| 310 |
+
raise ApiError(400, "invalid_input", "format must be 'json' or 'tool'", model_id)
|
| 311 |
+
return {"request": req, "response": PredictResponse.model_json_schema()}
|
| 312 |
+
|
| 313 |
+
@app.post("/v1/models/{model_id}/predict", tags=["v1"], response_model=PredictResponse,
|
| 314 |
+
openapi_extra=PREDICT_OPENAPI)
|
| 315 |
+
async def predict_v1(model_id: str, request: Request):
|
| 316 |
+
rate(request)
|
| 317 |
+
m = access(model_id, request)
|
| 318 |
+
file_model = m.adapter.input_kind == "file"
|
| 319 |
+
max_bytes = int(float(m.limits.get("max_upload_mb", 20)) * MB)
|
| 320 |
+
length = request.headers.get("content-length")
|
| 321 |
+
if length and length.isdigit() and int(length) > max_bytes * 1.4 + MB:
|
| 322 |
+
raise ApiError(413, "too_large", f"request larger than {max_bytes // MB} MB", model_id)
|
| 323 |
+
data = None
|
| 324 |
+
if request.headers.get("content-type", "").startswith("multipart/form-data"):
|
| 325 |
+
if not file_model:
|
| 326 |
+
raise ApiError(400, "invalid_input", "this model takes a JSON body", model_id)
|
| 327 |
+
form = await request.form()
|
| 328 |
+
up = form.get("file")
|
| 329 |
+
if up is None or isinstance(up, str):
|
| 330 |
+
raise ApiError(400, "invalid_input", "multipart requests need the file in the field 'file'", model_id)
|
| 331 |
+
data = await up.read(max_bytes + 1)
|
| 332 |
+
try:
|
| 333 |
+
inputs = json.loads(form.get("inputs") or "{}")
|
| 334 |
+
options = json.loads(form.get("options") or "{}")
|
| 335 |
+
except json.JSONDecodeError as exc:
|
| 336 |
+
raise ApiError(400, "invalid_input", f"the fields 'inputs' and 'options' must be JSON: {exc}",
|
| 337 |
+
model_id) from exc
|
| 338 |
+
else:
|
| 339 |
+
try:
|
| 340 |
+
body = await request.json()
|
| 341 |
+
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
|
| 342 |
+
raise ApiError(400, "invalid_input", "the body must be JSON (or multipart for file models)",
|
| 343 |
+
model_id) from exc
|
| 344 |
+
if not isinstance(body, dict) or "inputs" not in body:
|
| 345 |
+
raise ApiError(422, "validation_error", "the body must be an object with 'inputs'", model_id)
|
| 346 |
+
inputs, options = body["inputs"], body.get("options") or {}
|
| 347 |
+
if file_model and isinstance(inputs, dict) and inputs.get("file_base64") is not None:
|
| 348 |
+
inputs = dict(inputs)
|
| 349 |
+
try:
|
| 350 |
+
data = base64.b64decode(inputs.pop("file_base64"), validate=True)
|
| 351 |
+
except (binascii.Error, ValueError, TypeError) as exc:
|
| 352 |
+
raise ApiError(400, "invalid_input", "inputs.file_base64 is not valid base64", model_id) from exc
|
| 353 |
+
if not isinstance(options, dict):
|
| 354 |
+
raise ApiError(422, "validation_error", "options must be an object", model_id)
|
| 355 |
+
if data is not None and len(data) > max_bytes:
|
| 356 |
+
raise ApiError(413, "too_large", f"file larger than {max_bytes // MB} MB", model_id)
|
| 357 |
+
return await run_in_threadpool(run_predict, m, inputs, options, data)
|
| 358 |
+
|
| 359 |
+
# ---------- legacy routes of the original Space (same shapes, {"detail": ...} errors) ----------
|
| 360 |
+
|
| 361 |
+
def legacy_models() -> list[Model]:
|
| 362 |
+
return [m for m in reg.models.values() if m.spec.get("legacy_predict")]
|
| 363 |
+
|
| 364 |
+
def legacy_ready() -> list[str]:
|
| 365 |
+
return [m.id for m in legacy_models() if m.status == "ready" and m.visibility == "public"]
|
| 366 |
+
|
| 367 |
+
@app.get("/health", tags=["legacy"])
|
| 368 |
def health() -> dict:
|
| 369 |
+
return {"status": "ok", "available_models": legacy_ready(), "bundle_root": str(root)}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
|
| 371 |
+
@app.get("/models", tags=["legacy"])
|
| 372 |
def list_models() -> dict:
|
| 373 |
+
out = []
|
| 374 |
+
for m in legacy_models():
|
| 375 |
+
d = m.adapter.describe() if m.adapter is not None else {}
|
| 376 |
+
out.append({
|
| 377 |
+
"id": m.id,
|
| 378 |
+
"display_name": m.spec["display_name"],
|
| 379 |
+
"description": m.spec["description"],
|
| 380 |
+
"status": m.status,
|
| 381 |
+
"status_detail": m.spec.get("status_detail", ""),
|
| 382 |
+
"input_units": d.get("input_units", {}),
|
| 383 |
+
"output_units": d.get("output_units", {}),
|
| 384 |
+
"tags": m.spec.get("tags", []),
|
| 385 |
+
})
|
| 386 |
+
return {"models": out}
|
| 387 |
|
| 388 |
+
@app.post("/predict", tags=["legacy"])
|
| 389 |
+
def predict(body: PredictionRequest, request: Request) -> dict:
|
| 390 |
+
if not limiter.allow(client_ip(request)):
|
| 391 |
+
raise HTTPException(429, f"more than {limiter.rate} requests per minute from this address",
|
| 392 |
+
headers={"Retry-After": "60"})
|
| 393 |
+
m = reg.models.get(body.model_id)
|
| 394 |
+
if m is None or not m.spec.get("legacy_predict") or (m.visibility != "public" and m.status == "ready"):
|
| 395 |
+
raise HTTPException(400, f"Unknown model_id '{body.model_id}'. Available models: {legacy_ready()}.")
|
| 396 |
+
if m.status != "ready":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
raise HTTPException(
|
| 398 |
+
400, f"Model '{m.id}' is not deployable in this bundle: {m.spec.get('status_detail') or m.status}.")
|
| 399 |
+
if m.state != "ready":
|
| 400 |
+
raise HTTPException(503 if m.state != "failed" else 500, f"Model '{m.id}' is {m.state}.")
|
| 401 |
+
try:
|
| 402 |
+
v = run_predict(m, body.inputs, body.options.model_dump(), None)
|
| 403 |
+
except ApiError as exc:
|
| 404 |
+
if exc.status in (400, 413, 422):
|
| 405 |
+
raise HTTPException(400, exc.message) from exc
|
| 406 |
+
if exc.status == 429:
|
| 407 |
+
raise HTTPException(429, exc.message, headers=exc.headers) from exc
|
| 408 |
+
raise HTTPException(500, f"Unexpected inference error for model '{m.id}': {exc.message}") from exc
|
| 409 |
+
out = {"model_id": m.id, "display_name": m.spec["display_name"], "predictions": v["outputs"]["predictions"],
|
| 410 |
+
"metadata": v["metadata"]}
|
| 411 |
+
if "scaled_predictions" in v["outputs"]:
|
| 412 |
+
out["scaled_predictions"] = v["outputs"]["scaled_predictions"]
|
| 413 |
+
return out
|
| 414 |
|
| 415 |
return app
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def jsonable(x):
|
| 419 |
+
return json.loads(json.dumps(x, default=str))
|
squadds_ml_api/auth.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gate for gated models: a Hugging Face token of a member of the organization (whoami, cached for ten minutes)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def bearer(headers) -> str | None:
|
| 11 |
+
h = headers.get("authorization", "")
|
| 12 |
+
return h[7:].strip() or None if h.lower().startswith("bearer ") else None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Gate:
|
| 16 |
+
def __init__(self, org: str = "SQuADDS", ttl_s: float = 600):
|
| 17 |
+
self.org, self.ttl_s = org, ttl_s
|
| 18 |
+
self._memo: dict = {}
|
| 19 |
+
self._lock = threading.Lock()
|
| 20 |
+
|
| 21 |
+
def is_member(self, token: str) -> bool:
|
| 22 |
+
from huggingface_hub import whoami
|
| 23 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 24 |
+
|
| 25 |
+
k = hashlib.sha256(token.encode()).hexdigest()
|
| 26 |
+
with self._lock:
|
| 27 |
+
hit = self._memo.get(k)
|
| 28 |
+
if hit and time.monotonic() - hit[1] < self.ttl_s:
|
| 29 |
+
return hit[0]
|
| 30 |
+
try:
|
| 31 |
+
info = whoami(token=token)
|
| 32 |
+
ok = any(o.get("name") == self.org for o in info.get("orgs", []))
|
| 33 |
+
except HfHubHTTPError as exc:
|
| 34 |
+
if getattr(exc.response, "status_code", None) not in (401, 403):
|
| 35 |
+
raise
|
| 36 |
+
ok = False
|
| 37 |
+
with self._lock:
|
| 38 |
+
self._memo[k] = (ok, time.monotonic())
|
| 39 |
+
return ok
|
squadds_ml_api/registry.py
CHANGED
|
@@ -1,237 +1,179 @@
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
|
|
|
| 3 |
import json
|
|
|
|
|
|
|
|
|
|
| 4 |
from dataclasses import dataclass, field
|
| 5 |
from pathlib import Path
|
| 6 |
-
from typing import Any, Dict, Iterable, List
|
| 7 |
-
|
| 8 |
-
import joblib
|
| 9 |
-
import numpy as np
|
| 10 |
-
from keras.models import load_model
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class BundleConfigError(RuntimeError):
|
| 14 |
-
"""Raised when the deployed bundle is missing required files or config."""
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
class RequestValidationError(ValueError):
|
| 18 |
-
"""Raised when an inference request does not match the model contract."""
|
| 19 |
-
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
id: str
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
self.
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
self.
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
normalized.append({name: float(row[name]) for name in self.input_names})
|
| 111 |
-
return normalized
|
| 112 |
-
|
| 113 |
-
def _scale_inputs(self, rows: List[Dict[str, float]]) -> np.ndarray:
|
| 114 |
-
matrix = np.zeros((len(rows), len(self.input_names)), dtype=np.float32)
|
| 115 |
-
for row_idx, row in enumerate(rows):
|
| 116 |
-
for col_idx, name in enumerate(self.input_names):
|
| 117 |
-
value = row[name]
|
| 118 |
-
if self.spec.x_scaler_pattern:
|
| 119 |
-
scaler = self._load_scaler(self.spec.x_scaler_pattern, name)
|
| 120 |
-
scaled = scaler.transform([[value]])[0][0]
|
| 121 |
-
else:
|
| 122 |
-
scaled = value
|
| 123 |
-
matrix[row_idx, col_idx] = float(scaled)
|
| 124 |
-
return matrix
|
| 125 |
-
|
| 126 |
-
def _unscale_outputs(self, scaled_outputs: np.ndarray) -> np.ndarray:
|
| 127 |
-
matrix = np.asarray(scaled_outputs, dtype=np.float32).copy()
|
| 128 |
-
if not self.spec.y_scaler_pattern:
|
| 129 |
-
return matrix
|
| 130 |
-
|
| 131 |
-
for col_idx, name in enumerate(self.output_names):
|
| 132 |
-
scaler = self._load_scaler(self.spec.y_scaler_pattern, name)
|
| 133 |
-
column = matrix[:, col_idx].reshape(-1, 1)
|
| 134 |
-
matrix[:, col_idx] = scaler.inverse_transform(column).reshape(-1)
|
| 135 |
-
return matrix
|
| 136 |
-
|
| 137 |
-
def predict(
|
| 138 |
-
self,
|
| 139 |
-
inputs: Dict[str, float] | List[Dict[str, float]],
|
| 140 |
-
include_scaled_outputs: bool = False,
|
| 141 |
-
) -> Dict[str, Any]:
|
| 142 |
-
rows = self._normalize_rows(inputs)
|
| 143 |
-
scaled_inputs = self._scale_inputs(rows)
|
| 144 |
-
raw_predictions = self.model.predict(scaled_inputs, verbose=0)
|
| 145 |
-
|
| 146 |
-
if isinstance(raw_predictions, list):
|
| 147 |
-
scaled_outputs = np.asarray(raw_predictions[self.spec.prediction_output_index])
|
| 148 |
-
else:
|
| 149 |
-
scaled_outputs = np.asarray(raw_predictions)
|
| 150 |
-
|
| 151 |
-
unscaled_outputs = self._unscale_outputs(scaled_outputs)
|
| 152 |
-
|
| 153 |
-
predictions = [
|
| 154 |
-
{
|
| 155 |
-
output_name: float(unscaled_outputs[row_idx, col_idx])
|
| 156 |
-
for col_idx, output_name in enumerate(self.output_names)
|
| 157 |
-
}
|
| 158 |
-
for row_idx in range(unscaled_outputs.shape[0])
|
| 159 |
-
]
|
| 160 |
-
|
| 161 |
-
response: Dict[str, Any] = {
|
| 162 |
-
"model_id": self.spec.id,
|
| 163 |
-
"display_name": self.spec.display_name,
|
| 164 |
-
"predictions": predictions,
|
| 165 |
-
"metadata": {
|
| 166 |
-
"input_order": self.input_names,
|
| 167 |
-
"output_order": self.output_names,
|
| 168 |
-
"input_units": self.spec.input_units,
|
| 169 |
-
"output_units": self.spec.output_units,
|
| 170 |
-
"num_predictions": len(predictions),
|
| 171 |
-
},
|
| 172 |
-
}
|
| 173 |
-
if include_scaled_outputs:
|
| 174 |
-
response["scaled_predictions"] = [
|
| 175 |
-
{
|
| 176 |
-
output_name: float(scaled_outputs[row_idx, col_idx])
|
| 177 |
-
for col_idx, output_name in enumerate(self.output_names)
|
| 178 |
-
}
|
| 179 |
-
for row_idx in range(scaled_outputs.shape[0])
|
| 180 |
-
]
|
| 181 |
-
return response
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
class ModelRegistry:
|
| 185 |
-
def __init__(self, bundle_root: Path):
|
| 186 |
-
self.bundle_root = Path(bundle_root)
|
| 187 |
-
manifest_path = self.bundle_root / "deployment_manifest.json"
|
| 188 |
-
if not manifest_path.exists():
|
| 189 |
-
raise BundleConfigError(
|
| 190 |
-
f"Deployment manifest is missing from bundle: {manifest_path}"
|
| 191 |
-
)
|
| 192 |
-
|
| 193 |
-
payload = json.loads(manifest_path.read_text())
|
| 194 |
-
self.bundle_info = payload.get("space", {})
|
| 195 |
-
self.specs = [ModelSpec.from_dict(item) for item in payload.get("models", [])]
|
| 196 |
-
self._models: Dict[str, EndpointModel] = {}
|
| 197 |
-
|
| 198 |
-
def available_model_ids(self) -> List[str]:
|
| 199 |
-
return [spec.id for spec in self.specs if spec.status == "ready"]
|
| 200 |
-
|
| 201 |
-
def describe_models(self) -> List[Dict[str, Any]]:
|
| 202 |
-
return [
|
| 203 |
-
{
|
| 204 |
-
"id": spec.id,
|
| 205 |
-
"display_name": spec.display_name,
|
| 206 |
-
"description": spec.description,
|
| 207 |
-
"status": spec.status,
|
| 208 |
-
"status_detail": spec.status_detail,
|
| 209 |
-
"input_units": spec.input_units,
|
| 210 |
-
"output_units": spec.output_units,
|
| 211 |
-
"tags": spec.tags,
|
| 212 |
-
}
|
| 213 |
-
for spec in self.specs
|
| 214 |
-
]
|
| 215 |
-
|
| 216 |
-
def _get_model(self, model_id: str) -> EndpointModel:
|
| 217 |
-
spec = next((item for item in self.specs if item.id == model_id), None)
|
| 218 |
-
if spec is None:
|
| 219 |
-
raise RequestValidationError(
|
| 220 |
-
f"Unknown model_id '{model_id}'. Available models: {self.available_model_ids()}."
|
| 221 |
-
)
|
| 222 |
-
if spec.status != "ready":
|
| 223 |
-
raise RequestValidationError(
|
| 224 |
-
f"Model '{model_id}' is not deployable in this bundle: {spec.status_detail or spec.status}."
|
| 225 |
-
)
|
| 226 |
-
if model_id not in self._models:
|
| 227 |
-
self._models[model_id] = EndpointModel(self.bundle_root, spec)
|
| 228 |
-
return self._models[model_id]
|
| 229 |
-
|
| 230 |
-
def predict(
|
| 231 |
-
self,
|
| 232 |
-
model_id: str,
|
| 233 |
-
inputs: Dict[str, float] | List[Dict[str, float]],
|
| 234 |
-
include_scaled_outputs: bool = False,
|
| 235 |
-
) -> Dict[str, Any]:
|
| 236 |
-
model = self._get_model(model_id)
|
| 237 |
-
return model.predict(inputs=inputs, include_scaled_outputs=include_scaled_outputs)
|
|
|
|
| 1 |
+
"""registry.yaml: schema checks, adapter imports, weight fetching (pinned revision, sha256) and the loaded adapters."""
|
| 2 |
+
|
| 3 |
from __future__ import annotations
|
| 4 |
|
| 5 |
+
import hashlib
|
| 6 |
+
import importlib
|
| 7 |
import json
|
| 8 |
+
import logging
|
| 9 |
+
import re
|
| 10 |
+
import threading
|
| 11 |
from dataclasses import dataclass, field
|
| 12 |
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
import yaml
|
| 15 |
+
|
| 16 |
+
from .adapters.base import REQUIRED
|
| 17 |
+
|
| 18 |
+
log = logging.getLogger("squadds_ml_api")
|
| 19 |
+
VISIBILITY = ("public", "gated", "hidden")
|
| 20 |
+
HEX40 = re.compile(r"^[0-9a-f]{40}$")
|
| 21 |
+
HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class RegistryError(RuntimeError):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def import_object(path: str):
|
| 29 |
+
module, _, name = path.partition(":")
|
| 30 |
+
return getattr(importlib.import_module(module), name)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def sha256_file(p: Path) -> str:
|
| 34 |
+
h = hashlib.sha256()
|
| 35 |
+
with open(p, "rb") as f:
|
| 36 |
+
for b in iter(lambda: f.read(1 << 20), b""):
|
| 37 |
+
h.update(b)
|
| 38 |
+
return h.hexdigest()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def validate(data: dict, root: Path | None = None) -> None:
|
| 42 |
+
"""Raise RegistryError on the first violation of the registry rules."""
|
| 43 |
+
if not isinstance(data, dict) or data.get("version") != 1 or not isinstance(data.get("models"), dict):
|
| 44 |
+
raise RegistryError("registry must have version: 1 and a models mapping")
|
| 45 |
+
for mid, e in data["models"].items():
|
| 46 |
+
where = f"registry model {mid!r}"
|
| 47 |
+
if e.get("visibility") not in VISIBILITY:
|
| 48 |
+
raise RegistryError(f"{where}: visibility must be one of {VISIBILITY}")
|
| 49 |
+
for k in ("display_name", "description"):
|
| 50 |
+
if not e.get(k):
|
| 51 |
+
raise RegistryError(f"{where}: {k} missing")
|
| 52 |
+
if e.get("status", "ready") != "ready":
|
| 53 |
+
continue
|
| 54 |
+
for k in ("family", "adapter", "weights"):
|
| 55 |
+
if not e.get(k):
|
| 56 |
+
raise RegistryError(f"{where}: {k} missing")
|
| 57 |
+
w = e["weights"]
|
| 58 |
+
if "from_manifest" in w:
|
| 59 |
+
raise RegistryError(f"{where}: weights.from_manifest is not expanded (run build.py)")
|
| 60 |
+
if not HEX40.match(str(w.get("revision", ""))):
|
| 61 |
+
raise RegistryError(f"{where}: weights.revision must be a full 40-character commit hash")
|
| 62 |
+
if not w.get("repo_id") or not w.get("files"):
|
| 63 |
+
raise RegistryError(f"{where}: weights need repo_id and files")
|
| 64 |
+
for f in w["files"]:
|
| 65 |
+
if not f.get("path") or not HEX64.match(str(f.get("sha256", ""))):
|
| 66 |
+
raise RegistryError(f"{where}: every weights file needs a path and a sha256")
|
| 67 |
+
if root is not None:
|
| 68 |
+
for k in ("example", "warm"):
|
| 69 |
+
if e.get(k) and not (root / e[k]).exists():
|
| 70 |
+
raise RegistryError(f"{where}: {k} file {e[k]} missing")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def fetch(weights: dict) -> Path:
|
| 74 |
+
"""Download every file at the pinned revision, check its sha256 and return the local snapshot root."""
|
| 75 |
+
from huggingface_hub import hf_hub_download
|
| 76 |
+
|
| 77 |
+
root = None
|
| 78 |
+
for f in weights["files"]:
|
| 79 |
+
p = Path(hf_hub_download(repo_id=weights["repo_id"], filename=f["path"], revision=weights["revision"]))
|
| 80 |
+
got = sha256_file(p)
|
| 81 |
+
if got != f["sha256"]:
|
| 82 |
+
raise RegistryError(f"{weights['repo_id']}/{f['path']}: sha256 {got[:12]} differs from the registry")
|
| 83 |
+
r = p
|
| 84 |
+
for _ in Path(f["path"]).parts:
|
| 85 |
+
r = r.parent
|
| 86 |
+
if root is not None and r != root:
|
| 87 |
+
raise RegistryError(f"files of {weights['repo_id']} resolved to different snapshots")
|
| 88 |
+
root = r
|
| 89 |
+
return root
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclass
|
| 93 |
+
class Model:
|
| 94 |
id: str
|
| 95 |
+
spec: dict
|
| 96 |
+
adapter_cls: type | None = None
|
| 97 |
+
adapter: object | None = None
|
| 98 |
+
state: str = "pending"
|
| 99 |
+
error: str | None = None
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def visibility(self) -> str:
|
| 103 |
+
return self.spec["visibility"]
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def status(self) -> str:
|
| 107 |
+
return self.spec.get("status", "ready")
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def revision(self) -> str | None:
|
| 111 |
+
return (self.spec.get("weights") or {}).get("revision")
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def limits(self) -> dict:
|
| 115 |
+
return self.spec.get("limits") or {}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@dataclass
|
| 119 |
+
class Registry:
|
| 120 |
+
root: Path
|
| 121 |
+
path: Path | None = None
|
| 122 |
+
models: dict = field(default_factory=dict)
|
| 123 |
+
fetched: list = field(default_factory=list)
|
| 124 |
+
lock_info: dict = field(default_factory=dict)
|
| 125 |
+
|
| 126 |
+
def __post_init__(self):
|
| 127 |
+
self.root = Path(self.root)
|
| 128 |
+
self.path = Path(self.path or self.root / "registry.yaml")
|
| 129 |
+
self.raw = self.path.read_bytes()
|
| 130 |
+
data = yaml.safe_load(self.raw)
|
| 131 |
+
validate(data, self.root)
|
| 132 |
+
for mid, e in data["models"].items():
|
| 133 |
+
m = Model(mid, e)
|
| 134 |
+
if e.get("adapter"):
|
| 135 |
+
m.adapter_cls = import_object(e["adapter"])
|
| 136 |
+
missing = [k for k in REQUIRED if not hasattr(m.adapter_cls, k)]
|
| 137 |
+
if missing:
|
| 138 |
+
raise RegistryError(f"adapter of {mid!r} lacks {missing}")
|
| 139 |
+
self.models[mid] = m
|
| 140 |
+
lock = self.root / "bundle.lock.json"
|
| 141 |
+
self.lock_info = json.loads(lock.read_text()) if lock.exists() else {}
|
| 142 |
+
self.sha256 = hashlib.sha256(self.raw).hexdigest()
|
| 143 |
+
|
| 144 |
+
def servable(self) -> list[Model]:
|
| 145 |
+
return [m for m in self.models.values() if m.visibility != "hidden" and m.status == "ready"]
|
| 146 |
+
|
| 147 |
+
def load_all(self) -> list[Model]:
|
| 148 |
+
"""Fetch, verify, instantiate and warm every public and gated model; hidden ones are never touched."""
|
| 149 |
+
failed = []
|
| 150 |
+
for m in self.servable():
|
| 151 |
+
m.state = "loading"
|
| 152 |
+
for m in self.servable():
|
| 153 |
+
try:
|
| 154 |
+
root = fetch(m.spec["weights"])
|
| 155 |
+
self.fetched.append(m.spec["weights"]["repo_id"])
|
| 156 |
+
m.adapter = m.adapter_cls(m.id, root, m.spec.get("config") or {}, m.limits)
|
| 157 |
+
if m.spec.get("warm") and hasattr(m.adapter, "warm"):
|
| 158 |
+
m.adapter.warm(self.root / m.spec["warm"])
|
| 159 |
+
log.info("warm prediction done for %s", m.id)
|
| 160 |
+
m.state = "ready"
|
| 161 |
+
except Exception as exc: # noqa: BLE001
|
| 162 |
+
m.state, m.error = "failed", f"{type(exc).__name__}: {exc}"
|
| 163 |
+
log.error("model %s failed to load: %s", m.id, m.error)
|
| 164 |
+
failed.append(m)
|
| 165 |
+
return failed
|
| 166 |
+
|
| 167 |
+
def start(self, exit_on_failure: bool = False) -> threading.Thread:
|
| 168 |
+
def run():
|
| 169 |
+
failed = self.load_all()
|
| 170 |
+
if failed and exit_on_failure:
|
| 171 |
+
import os
|
| 172 |
+
|
| 173 |
+
os._exit(1)
|
| 174 |
+
|
| 175 |
+
for m in self.servable():
|
| 176 |
+
m.state = "loading"
|
| 177 |
+
t = threading.Thread(target=run, name="registry-load", daemon=True)
|
| 178 |
+
t.start()
|
| 179 |
+
return t
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
squadds_ml_api/schemas.py
CHANGED
|
@@ -1,10 +1,35 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
-
from typing import Dict, List, Union
|
| 4 |
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
class PredictionOptions(BaseModel):
|
| 9 |
include_scaled_outputs: bool = Field(
|
| 10 |
default=False,
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
from typing import Any, Dict, List, Union
|
| 4 |
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
|
| 7 |
|
| 8 |
+
class ApiError(Exception):
|
| 9 |
+
def __init__(self, status: int, code: str, message: str, model_id: str | None = None, headers: dict | None = None,
|
| 10 |
+
details: Any = None):
|
| 11 |
+
super().__init__(message)
|
| 12 |
+
self.status, self.code, self.message, self.model_id, self.headers, self.details = (
|
| 13 |
+
status, code, message, model_id, headers or {}, details)
|
| 14 |
+
|
| 15 |
+
def body(self) -> dict:
|
| 16 |
+
err = {"code": self.code, "message": self.message, "model_id": self.model_id}
|
| 17 |
+
if self.details is not None:
|
| 18 |
+
err["details"] = self.details
|
| 19 |
+
return {"error": err}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class PredictResponse(BaseModel):
|
| 23 |
+
model_id: str
|
| 24 |
+
family: str
|
| 25 |
+
revision: str
|
| 26 |
+
outputs: Dict[str, Any] = Field(description="Family specific outputs")
|
| 27 |
+
metadata: Dict[str, Any] = Field(description="Family specific metadata: names, units, orders, checks")
|
| 28 |
+
timing_s: Dict[str, Any] = Field(description="Seconds: total, queue and family specific steps")
|
| 29 |
+
cached: bool
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# Legacy request of the original Space (POST /predict), unchanged.
|
| 33 |
class PredictionOptions(BaseModel):
|
| 34 |
include_scaled_outputs: bool = Field(
|
| 35 |
default=False,
|
src/squadds/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Inference-only subset of SQuADDS (squadds.ml)."""
|
src/squadds/ml/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Machine-learning models for SQuADDS (optional extra: ``pip install squadds[ml]``).
|
| 2 |
+
|
| 3 |
+
Submodules import torch / gdstk / numba lazily, so ``import squadds`` works without the extra.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import importlib.util
|
| 9 |
+
|
| 10 |
+
ML_REQUIREMENTS = ("torch", "gdstk", "numba", "threadpoolctl", "shapely", "yaml")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def missing_ml_dependencies() -> list[str]:
|
| 14 |
+
return [m for m in ML_REQUIREMENTS if importlib.util.find_spec(m) is None]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def require_ml() -> None:
|
| 18 |
+
"""Raise ImportError naming the missing packages when the ``[ml]`` extra is not installed."""
|
| 19 |
+
missing = missing_ml_dependencies()
|
| 20 |
+
if missing:
|
| 21 |
+
raise ImportError(
|
| 22 |
+
f"squadds.ml needs the optional ML dependencies (missing: {', '.join(missing)}). "
|
| 23 |
+
"Install them with: pip install 'squadds[ml]'"
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def __getattr__(name):
|
| 28 |
+
if name == "capacitance":
|
| 29 |
+
require_ml()
|
| 30 |
+
return importlib.import_module("squadds.ml.capacitance")
|
| 31 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
__all__ = ["ML_REQUIREMENTS", "missing_ml_dependencies", "require_ml"]
|
src/squadds/ml/capacitance/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Planar capacitance models: GDS layout -> full N x N Maxwell capacitance matrix (fF, ground first).
|
| 2 |
+
|
| 3 |
+
from squadds.ml.capacitance import CapacitancePredictor, load_model
|
| 4 |
+
res = CapacitancePredictor(load_model("flagship")).predict("chip.gds")
|
| 5 |
+
res.names, res.matrix_fF, res.to_sim_results()
|
| 6 |
+
|
| 7 |
+
Models: ``flagship`` (the default) and ``fast`` (both trained on all data), and ``paper`` (the paper's model, TRAIN split
|
| 8 |
+
only; use it for benchmarks). Physics priors: ``coarse_physics_prior`` and ``optimized_physics_prior``.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import importlib
|
| 14 |
+
|
| 15 |
+
from .. import require_ml
|
| 16 |
+
|
| 17 |
+
_EXPORTS = {
|
| 18 |
+
"CapacitancePredictor": "predictor",
|
| 19 |
+
"CapacitanceResult": "result",
|
| 20 |
+
"CapacitanceModel": "models",
|
| 21 |
+
"ModelIntegrityError": "models",
|
| 22 |
+
"list_models": "models",
|
| 23 |
+
"load_model": "models",
|
| 24 |
+
"PriorResult": "priors",
|
| 25 |
+
"coarse_physics_prior": "priors",
|
| 26 |
+
"optimized_physics_prior": "priors",
|
| 27 |
+
"prepare_layout": "_runtime",
|
| 28 |
+
"inspect_layout": "_runtime",
|
| 29 |
+
"MLSimulator": "bridge",
|
| 30 |
+
"TrainConfig": "train",
|
| 31 |
+
"fit": "train",
|
| 32 |
+
"fit_in_family": "train",
|
| 33 |
+
"retrain_collective": "train",
|
| 34 |
+
"build_shards": "training_data",
|
| 35 |
+
"resolve_dataset_names": "training_data",
|
| 36 |
+
"score": "benchmark",
|
| 37 |
+
"PlanarCapacitanceDB": "dataset",
|
| 38 |
+
"label_qc": "qc",
|
| 39 |
+
"validate_capacitance_contribution": "contribute",
|
| 40 |
+
"contribute_capacitance": "contribute",
|
| 41 |
+
"validate_model": "contribute",
|
| 42 |
+
"contribute_model": "contribute",
|
| 43 |
+
}
|
| 44 |
+
_NO_ML_NEEDED = {"PlanarCapacitanceDB", "label_qc"}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def __getattr__(name):
|
| 48 |
+
if name in _EXPORTS:
|
| 49 |
+
if name not in _NO_ML_NEEDED:
|
| 50 |
+
require_ml()
|
| 51 |
+
return getattr(importlib.import_module(f"{__name__}.{_EXPORTS[name]}"), name)
|
| 52 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
__all__ = sorted(_EXPORTS)
|
src/squadds/ml/capacitance/_core/SOURCES.json
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"note": "Frozen inference stage of the tl-squadds Spaces (deploy/geomgnn/src/geomgnn, deploy/tlsq_infer/src/tlsq_infer/layout.py), namespaced under squadds.ml.capacitance._core. Edits: import lines; the network builder moved to squadds.ml.capacitance.network (verbatim from pilot_p2.build_model); spawned worker pools start through _spawn.boot (same worker functions and arguments, the squadds package __init__ is not executed in the workers). Numerics unchanged.",
|
| 3 |
+
"tl_squadds_repo": "github.com/shanto268/tl-squadds (private), branch paper-backup",
|
| 4 |
+
"files": {
|
| 5 |
+
"api.py": {
|
| 6 |
+
"source": "deploy/geomgnn/src/geomgnn/api.py",
|
| 7 |
+
"source_sha256": "7905e805e48377dc36f60241e042a597bb7afb5491b5f4c89d8a0a5b28ff975f",
|
| 8 |
+
"sha256": "3e6cb02f180b6c2138511fbcb628daa07e0529f80b31ee4add26111738179549",
|
| 9 |
+
"rewrites": [
|
| 10 |
+
{
|
| 11 |
+
"pattern": "module=r\"geomgnn\\\\\\.fastprior_pkg\"",
|
| 12 |
+
"replacement": "module=r\"squadds\\.ml\\.capacitance\\._core\\.fastprior_pkg\"",
|
| 13 |
+
"count": 1
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"pattern": "from tlsq_infer\\.layout import prepare",
|
| 17 |
+
"replacement": "from .layout import prepare",
|
| 18 |
+
"count": 1
|
| 19 |
+
}
|
| 20 |
+
]
|
| 21 |
+
},
|
| 22 |
+
"paper.py": {
|
| 23 |
+
"source": "deploy/geomgnn/src/geomgnn/paper.py",
|
| 24 |
+
"source_sha256": "fc951f350f5d0bc4de0b1cf93209a4dfa7770fde2661330c6bde6c92c9f6a31f",
|
| 25 |
+
"sha256": "3d1f95dcf06d005a6bf0ff3d545fead3c18bed4db9a1629469ef2d2375644a8c",
|
| 26 |
+
"rewrites": [
|
| 27 |
+
{
|
| 28 |
+
"pattern": "from tlsq_infer\\.layout import prepare",
|
| 29 |
+
"replacement": "from .layout import prepare",
|
| 30 |
+
"count": 1
|
| 31 |
+
}
|
| 32 |
+
]
|
| 33 |
+
},
|
| 34 |
+
"flagship.py": {
|
| 35 |
+
"source": "deploy/geomgnn/src/geomgnn/flagship.py",
|
| 36 |
+
"source_sha256": "f86bf5bab11dbedbdd1e07626b172dae4d4f53ed356f47e26da18bd008df448b",
|
| 37 |
+
"sha256": "f86bf5bab11dbedbdd1e07626b172dae4d4f53ed356f47e26da18bd008df448b",
|
| 38 |
+
"rewrites": []
|
| 39 |
+
},
|
| 40 |
+
"infer.py": {
|
| 41 |
+
"source": "deploy/geomgnn/src/geomgnn/infer.py",
|
| 42 |
+
"source_sha256": "cee37e8ed6f229363801b9a8118aea9dfb4ce5f476e6e2d8ff13cfa734e87b96",
|
| 43 |
+
"sha256": "ed77e7456af217a4ee438068c4ee1c7b07a9e1768424156e64a40e5480bc9376",
|
| 44 |
+
"rewrites": [
|
| 45 |
+
{
|
| 46 |
+
"pattern": "from \\.pilot_p2 import build_model",
|
| 47 |
+
"replacement": "from ..network import build_model",
|
| 48 |
+
"count": 1
|
| 49 |
+
}
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
"x1_core.py": {
|
| 53 |
+
"source": "deploy/geomgnn/src/geomgnn/x1_core.py",
|
| 54 |
+
"source_sha256": "0a4be5ec3b8819bdc6d6314775c7f8acf46f4a54569d975011726ec1912c5100",
|
| 55 |
+
"sha256": "0a4be5ec3b8819bdc6d6314775c7f8acf46f4a54569d975011726ec1912c5100",
|
| 56 |
+
"rewrites": []
|
| 57 |
+
},
|
| 58 |
+
"farfield.py": {
|
| 59 |
+
"source": "deploy/geomgnn/src/geomgnn/farfield.py",
|
| 60 |
+
"source_sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836",
|
| 61 |
+
"sha256": "6c877b47c2894fe78a38ad4199b29e450b610c2c45a261c8cf4d53efc1912836",
|
| 62 |
+
"rewrites": []
|
| 63 |
+
},
|
| 64 |
+
"fastprior_pkg.py": {
|
| 65 |
+
"source": "deploy/geomgnn/src/geomgnn/fastprior_pkg.py",
|
| 66 |
+
"source_sha256": "956f2b62c308ec1561bbc033716b52c24dc63a916b9373cc44090eb6514e5dde",
|
| 67 |
+
"sha256": "26a2c03786bacf85fd48005968d53e8661b66cd3367b66dd86adac12a2bd3e92",
|
| 68 |
+
"rewrites": [
|
| 69 |
+
{
|
| 70 |
+
"pattern": "from geomgnn\\._tlsq",
|
| 71 |
+
"replacement": "from squadds.ml.capacitance._core._tlsq",
|
| 72 |
+
"count": 1
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"pattern": "\"geomgnn\\._tlsq\\.embed\\.fastprior\" in sys\\.modules",
|
| 76 |
+
"replacement": "\"squadds.ml.capacitance._core._tlsq.embed.fastprior\" in sys.modules",
|
| 77 |
+
"count": 1
|
| 78 |
+
}
|
| 79 |
+
]
|
| 80 |
+
},
|
| 81 |
+
"priorv2.py": {
|
| 82 |
+
"source": "deploy/geomgnn/src/geomgnn/priorv2.py",
|
| 83 |
+
"source_sha256": "64057e92e37a04a0231dfdc34df52a20542f88c2b2a3e8c2cc00a32d9ec1d21b",
|
| 84 |
+
"sha256": "64057e92e37a04a0231dfdc34df52a20542f88c2b2a3e8c2cc00a32d9ec1d21b",
|
| 85 |
+
"rewrites": []
|
| 86 |
+
},
|
| 87 |
+
"rejtail_fv.py": {
|
| 88 |
+
"source": "deploy/geomgnn/src/geomgnn/rejtail_fv.py",
|
| 89 |
+
"source_sha256": "35659484c44f1c84e3767b33979bb78b972f03d64c05810d81635ee4409ce3ba",
|
| 90 |
+
"sha256": "35659484c44f1c84e3767b33979bb78b972f03d64c05810d81635ee4409ce3ba",
|
| 91 |
+
"rewrites": []
|
| 92 |
+
},
|
| 93 |
+
"learned_prior.py": {
|
| 94 |
+
"source": "deploy/geomgnn/src/geomgnn/learned_prior.py",
|
| 95 |
+
"source_sha256": "de9d1351dfbaa93ef1be18ed18f3a3628ba2b477955f58c58db80758163156dc",
|
| 96 |
+
"sha256": "de9d1351dfbaa93ef1be18ed18f3a3628ba2b477955f58c58db80758163156dc",
|
| 97 |
+
"rewrites": []
|
| 98 |
+
},
|
| 99 |
+
"lp_surrogate.py": {
|
| 100 |
+
"source": "deploy/geomgnn/src/geomgnn/lp_surrogate.py",
|
| 101 |
+
"source_sha256": "55804c9349a2ca4a74f3ae821a19c4637dbaf16d25b65c8ee70c746b767d2707",
|
| 102 |
+
"sha256": "55804c9349a2ca4a74f3ae821a19c4637dbaf16d25b65c8ee70c746b767d2707",
|
| 103 |
+
"rewrites": []
|
| 104 |
+
},
|
| 105 |
+
"levelpar.py": {
|
| 106 |
+
"source": "deploy/geomgnn/src/geomgnn/levelpar.py",
|
| 107 |
+
"source_sha256": "69e7d1199e9642cfef399d5ee6737f4bcd768ef863372065d60082d81398eb22",
|
| 108 |
+
"sha256": "e929ecf97131d45533b2bd3b2bec4645935df1fbb13824375f55d10f5dc36729",
|
| 109 |
+
"rewrites": [
|
| 110 |
+
{
|
| 111 |
+
"pattern": "from geomgnn\\._tlsq",
|
| 112 |
+
"replacement": "from squadds.ml.capacitance._core._tlsq",
|
| 113 |
+
"count": 2
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"pattern": "from geomgnn import",
|
| 117 |
+
"replacement": "from squadds.ml.capacitance._core import",
|
| 118 |
+
"count": 3
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"pattern": "here = os\\.path\\.dirname\\(os\\.path\\.dirname\\(os\\.path\\.abspath\\(__file__\\)\\)\\)",
|
| 122 |
+
"replacement": "here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds",
|
| 123 |
+
"count": 1
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"pattern": "ex = ProcessPoolExecutor\\(n, mp_context=get_context\\(\\\"spawn\\\"\\), initializer=_init,\\n\\s*initargs=\\(\\[here\\], A._STATE\\[\\\"prior_impl\\\"\\], A._STATE\\[\\\"pr\\\"\\], threads\\)\\)",
|
| 127 |
+
"replacement": "from ._spawn import boot\n ini, args = boot(_init, [here], A._STATE[\"prior_impl\"], A._STATE[\"pr\"], threads)\n ex = ProcessPoolExecutor(n, mp_context=get_context(\"spawn\"), initializer=ini, initargs=args)",
|
| 128 |
+
"count": 1
|
| 129 |
+
}
|
| 130 |
+
]
|
| 131 |
+
},
|
| 132 |
+
"overlap.py": {
|
| 133 |
+
"source": "deploy/geomgnn/src/geomgnn/overlap.py",
|
| 134 |
+
"source_sha256": "30cb40ead9146603b9c0a32cebc7d79bc762b79c1526b95be3b6deefc3419753",
|
| 135 |
+
"sha256": "cf226d87b9a099ca5543d6f4dd4f3706f8fc13bb6d0f2bbb1e76fc52b3630cfb",
|
| 136 |
+
"rewrites": [
|
| 137 |
+
{
|
| 138 |
+
"pattern": "from geomgnn\\._tlsq",
|
| 139 |
+
"replacement": "from squadds.ml.capacitance._core._tlsq",
|
| 140 |
+
"count": 5
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"pattern": "here = os\\.path\\.dirname\\(os\\.path\\.dirname\\(os\\.path\\.abspath\\(__file__\\)\\)\\)",
|
| 144 |
+
"replacement": "here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds",
|
| 145 |
+
"count": 1
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"pattern": "ex = ProcessPoolExecutor\\(1, mp_context=get_context\\(\\\"spawn\\\"\\), initializer=_init, initargs=\\(threads, \\[here\\]\\)\\)",
|
| 149 |
+
"replacement": "from ._spawn import boot\n ini, args = boot(_init, threads, [here])\n ex = ProcessPoolExecutor(1, mp_context=get_context(\"spawn\"), initializer=ini, initargs=args)",
|
| 150 |
+
"count": 1
|
| 151 |
+
}
|
| 152 |
+
]
|
| 153 |
+
},
|
| 154 |
+
"winpool.py": {
|
| 155 |
+
"source": "deploy/geomgnn/src/geomgnn/winpool.py",
|
| 156 |
+
"source_sha256": "c726a7c86737058660600f9f40276843add598f6245d586eb32e206a660f342f",
|
| 157 |
+
"sha256": "56e7142019e44e872c65ce283ad9afbd27f4a664cb53c1656295062c4a1d657a",
|
| 158 |
+
"rewrites": [
|
| 159 |
+
{
|
| 160 |
+
"pattern": "from geomgnn\\._tlsq",
|
| 161 |
+
"replacement": "from squadds.ml.capacitance._core._tlsq",
|
| 162 |
+
"count": 2
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"pattern": "from geomgnn import",
|
| 166 |
+
"replacement": "from squadds.ml.capacitance._core import",
|
| 167 |
+
"count": 1
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"pattern": "here = os\\.path\\.dirname\\(os\\.path\\.dirname\\(os\\.path\\.abspath\\(__file__\\)\\)\\)",
|
| 171 |
+
"replacement": "here = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 4)) # the directory holding squadds",
|
| 172 |
+
"count": 1
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"pattern": "super\\(\\).__init__\\(max_workers, mp_context=get_context\\(\\\"spawn\\\"\\), initializer=_init,\\n\\s*initargs=\\(\\[here\\], A._STATE\\[\\\"prior_impl\\\"\\], A._STATE\\[\\\"pr\\\"\\], state\\)\\)",
|
| 176 |
+
"replacement": "from ._spawn import boot\n ini, args = boot(_init, [here], A._STATE[\"prior_impl\"], A._STATE[\"pr\"], state)\n super().__init__(max_workers, mp_context=get_context(\"spawn\"), initializer=ini, initargs=args)",
|
| 177 |
+
"count": 1
|
| 178 |
+
}
|
| 179 |
+
]
|
| 180 |
+
},
|
| 181 |
+
"fastmom.py": {
|
| 182 |
+
"source": "deploy/geomgnn/src/geomgnn/fastmom.py",
|
| 183 |
+
"source_sha256": "7447474366ddae654100467125c84ddb7fb503a1c9d4fd1264825bde164de951",
|
| 184 |
+
"sha256": "7447474366ddae654100467125c84ddb7fb503a1c9d4fd1264825bde164de951",
|
| 185 |
+
"rewrites": []
|
| 186 |
+
},
|
| 187 |
+
"schema_p2d.json": {
|
| 188 |
+
"source": "deploy/geomgnn/src/geomgnn/schema_p2d.json",
|
| 189 |
+
"source_sha256": "17eba5f7b5d01668019df9301507133dfe4e38689acbde5256f3ade2107df8e9",
|
| 190 |
+
"sha256": "17eba5f7b5d01668019df9301507133dfe4e38689acbde5256f3ade2107df8e9",
|
| 191 |
+
"rewrites": []
|
| 192 |
+
},
|
| 193 |
+
"_tlsq/__init__.py": {
|
| 194 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/__init__.py",
|
| 195 |
+
"source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 196 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 197 |
+
"rewrites": [],
|
| 198 |
+
"upstream": {
|
| 199 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/__init__.py",
|
| 200 |
+
"source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 201 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 202 |
+
"rewrites": []
|
| 203 |
+
}
|
| 204 |
+
},
|
| 205 |
+
"_tlsq/embed/__init__.py": {
|
| 206 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/__init__.py",
|
| 207 |
+
"source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 208 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 209 |
+
"rewrites": [],
|
| 210 |
+
"upstream": {
|
| 211 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/__init__.py",
|
| 212 |
+
"source_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 213 |
+
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 214 |
+
"rewrites": []
|
| 215 |
+
}
|
| 216 |
+
},
|
| 217 |
+
"_tlsq/embed/fastprior.py": {
|
| 218 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/fastprior.py",
|
| 219 |
+
"source_sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1",
|
| 220 |
+
"sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1",
|
| 221 |
+
"rewrites": [],
|
| 222 |
+
"upstream": {
|
| 223 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/fastprior.py",
|
| 224 |
+
"source_sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1",
|
| 225 |
+
"sha256": "1755668ca197bc56bcc4ef1d23a01464df75ba27e79eb2f447c8f147152cbbf1",
|
| 226 |
+
"rewrites": []
|
| 227 |
+
}
|
| 228 |
+
},
|
| 229 |
+
"_tlsq/embed/fastprior_loc.py": {
|
| 230 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/fastprior_loc.py",
|
| 231 |
+
"source_sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b",
|
| 232 |
+
"sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b",
|
| 233 |
+
"rewrites": [],
|
| 234 |
+
"upstream": {
|
| 235 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/fastprior_loc.py",
|
| 236 |
+
"source_sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b",
|
| 237 |
+
"sha256": "3642ebac602a0767cad2cdd51e04dc602055c0045022b71f14d93298af943a2b",
|
| 238 |
+
"rewrites": []
|
| 239 |
+
}
|
| 240 |
+
},
|
| 241 |
+
"_tlsq/embed/proxy.py": {
|
| 242 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/embed/proxy.py",
|
| 243 |
+
"source_sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e",
|
| 244 |
+
"sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e",
|
| 245 |
+
"rewrites": [],
|
| 246 |
+
"upstream": {
|
| 247 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/embed/proxy.py",
|
| 248 |
+
"source_sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e",
|
| 249 |
+
"sha256": "78d8dffd2fac75632a91ebee151247afe4157716ffb11e624e6b2932c618c86e",
|
| 250 |
+
"rewrites": []
|
| 251 |
+
}
|
| 252 |
+
},
|
| 253 |
+
"_tlsq/geometry.py": {
|
| 254 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/geometry.py",
|
| 255 |
+
"source_sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b",
|
| 256 |
+
"sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b",
|
| 257 |
+
"rewrites": [],
|
| 258 |
+
"upstream": {
|
| 259 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/geometry.py",
|
| 260 |
+
"source_sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b",
|
| 261 |
+
"sha256": "0bb8d3ead358870a026eebf8e26a212bdf1a838565bd30251a684fab7c97c99b",
|
| 262 |
+
"rewrites": []
|
| 263 |
+
}
|
| 264 |
+
},
|
| 265 |
+
"_tlsq/uge/__init__.py": {
|
| 266 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/__init__.py",
|
| 267 |
+
"source_sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22",
|
| 268 |
+
"sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22",
|
| 269 |
+
"rewrites": [],
|
| 270 |
+
"upstream": {
|
| 271 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/__init__.py",
|
| 272 |
+
"source_sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22",
|
| 273 |
+
"sha256": "2c9ab4995b49e228e84ff19f44c79f944a3f5d0489db0a688ccaf76546995c22",
|
| 274 |
+
"rewrites": []
|
| 275 |
+
}
|
| 276 |
+
},
|
| 277 |
+
"_tlsq/uge/blocks.py": {
|
| 278 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/blocks.py",
|
| 279 |
+
"source_sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c",
|
| 280 |
+
"sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c",
|
| 281 |
+
"rewrites": [],
|
| 282 |
+
"upstream": {
|
| 283 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/blocks.py",
|
| 284 |
+
"source_sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c",
|
| 285 |
+
"sha256": "a30c62b8be382b48d41e3ac9ff09e8be7df7ae55041b90b2fbd2e62ee2063a3c",
|
| 286 |
+
"rewrites": [],
|
| 287 |
+
"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).",
|
| 288 |
+
"frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/blocks.py",
|
| 289 |
+
"frozen_stage_sha256": "c58313f167f7df0ef0de6b321ab6b7214a661aef10b461e2bf90a60999fb4632"
|
| 290 |
+
}
|
| 291 |
+
},
|
| 292 |
+
"_tlsq/uge/graph.py": {
|
| 293 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/graph.py",
|
| 294 |
+
"source_sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa",
|
| 295 |
+
"sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa",
|
| 296 |
+
"rewrites": [],
|
| 297 |
+
"upstream": {
|
| 298 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/graph.py",
|
| 299 |
+
"source_sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa",
|
| 300 |
+
"sha256": "979002b1b6c4068553ca014f4078f396166b16d2148b60b7587cb27b878309fa",
|
| 301 |
+
"rewrites": [],
|
| 302 |
+
"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).",
|
| 303 |
+
"frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/graph.py",
|
| 304 |
+
"frozen_stage_sha256": "aeb8c58cf6c1d2169eab8a58fba362634d7489f3414f260a9fc55a02048217ee"
|
| 305 |
+
}
|
| 306 |
+
},
|
| 307 |
+
"_tlsq/uge/localtok.py": {
|
| 308 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/localtok.py",
|
| 309 |
+
"source_sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd",
|
| 310 |
+
"sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd",
|
| 311 |
+
"rewrites": [],
|
| 312 |
+
"upstream": {
|
| 313 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/localtok.py",
|
| 314 |
+
"source_sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd",
|
| 315 |
+
"sha256": "c0226dc8920f6cdf9c7b6a7c6d1d872b3490b0725ed93e70378af29bb74cbccd",
|
| 316 |
+
"rewrites": [],
|
| 317 |
+
"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).",
|
| 318 |
+
"frozen_stage_source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/localtok.py",
|
| 319 |
+
"frozen_stage_sha256": "8b47bd454353709a29ad996243d0f8b4b0d94991ee43715145af41a912dd9319"
|
| 320 |
+
}
|
| 321 |
+
},
|
| 322 |
+
"_tlsq/uge/nnk.py": {
|
| 323 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/nnk.py",
|
| 324 |
+
"source_sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84",
|
| 325 |
+
"sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84",
|
| 326 |
+
"rewrites": [],
|
| 327 |
+
"upstream": {
|
| 328 |
+
"source": "/Users/shanto/LFL/tl_squadds/src/tlsq/uge/nnk.py",
|
| 329 |
+
"source_sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84",
|
| 330 |
+
"sha256": "646e48eec701cb11cf5bff7e9f045b2e853d1b8346bda8be94204d3ae960fe84",
|
| 331 |
+
"rewrites": [],
|
| 332 |
+
"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)."
|
| 333 |
+
}
|
| 334 |
+
},
|
| 335 |
+
"_tlsq/uge/proxies.py": {
|
| 336 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/proxies.py",
|
| 337 |
+
"source_sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38",
|
| 338 |
+
"sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38",
|
| 339 |
+
"rewrites": [],
|
| 340 |
+
"upstream": {
|
| 341 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/proxies.py",
|
| 342 |
+
"source_sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38",
|
| 343 |
+
"sha256": "1726d068105f88f2654fd84a07919b7ecd9852cc5f826f6dd812109e6ce55b38",
|
| 344 |
+
"rewrites": []
|
| 345 |
+
}
|
| 346 |
+
},
|
| 347 |
+
"_tlsq/uge/scene.py": {
|
| 348 |
+
"source": "deploy/geomgnn/src/geomgnn/_tlsq/uge/scene.py",
|
| 349 |
+
"source_sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285",
|
| 350 |
+
"sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285",
|
| 351 |
+
"rewrites": [],
|
| 352 |
+
"upstream": {
|
| 353 |
+
"source": "/Users/shanto/Documents/ChatGPT/transfer_learning/geomfast_stage/vendor/tlsq/uge/scene.py",
|
| 354 |
+
"source_sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285",
|
| 355 |
+
"sha256": "f990d3028092ca59e4bbb274bcc181eb52cc7d0c73c158cbc1b23003d0368285",
|
| 356 |
+
"rewrites": []
|
| 357 |
+
}
|
| 358 |
+
},
|
| 359 |
+
"layout.py": {
|
| 360 |
+
"source": "deploy/tlsq_infer/src/tlsq_infer/layout.py",
|
| 361 |
+
"source_sha256": "2f88d25f7984f470a7fc361e54bf054e98c682d667383a6991c59760a08c7113",
|
| 362 |
+
"sha256": "3cd0601522056ee82630d2ea829c14bca0e172e7a24a6391433af9b8038fbe95",
|
| 363 |
+
"rewrites": [
|
| 364 |
+
{
|
| 365 |
+
"pattern": "from \\._vendor\\.scene import _valid",
|
| 366 |
+
"replacement": "from ._tlsq.uge.scene import _valid",
|
| 367 |
+
"count": 1
|
| 368 |
+
}
|
| 369 |
+
]
|
| 370 |
+
},
|
| 371 |
+
"../network.py": {
|
| 372 |
+
"source": "deploy/geomgnn/src/geomgnn/pilot_p2.py",
|
| 373 |
+
"source_sha256": "c38264c43ab342ba64338892edf23c8abd4b88503b99bce322431efb7db77c77",
|
| 374 |
+
"extract": "build_model (lines 89-117), verbatim",
|
| 375 |
+
"extract_sha256": "e64a9482d41562c8de1c795a25f63ff21c3db1e19b8e8e60dc585feda2c2fbfa",
|
| 376 |
+
"upstream": "scripts/geomfast/pilot_p2.py (frozen geomfast stage)"
|
| 377 |
+
}
|
| 378 |
+
}
|
| 379 |
+
}
|
src/squadds/ml/capacitance/_core/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen inference stage of the planar-capacitance models, ported from tl-squadds (geomgnn 0.1.0); see SOURCES.json.
|
| 2 |
+
|
| 3 |
+
Do not edit the numerics here: every file records the sha256 of its tl-squadds source and the import lines rewritten.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
__version__ = "0.1.0"
|
src/squadds/ml/capacitance/_core/_spawn.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Start spawned worker processes without executing ``squadds/__init__.py`` (which imports the database and analysis stack).
|
| 2 |
+
|
| 3 |
+
``boot(fn, *args)`` returns ``(initializer, initargs)`` for a ``ProcessPoolExecutor``: the worker registers a bare ``squadds``
|
| 4 |
+
package module, then imports ``fn`` by name and calls ``fn(*args)``; at exit it undoes the prior stack (quiet shutdown). The worker functions and their arguments are unchanged.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import pickle
|
| 11 |
+
|
| 12 |
+
_PKG_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), *[os.pardir] * 3))
|
| 13 |
+
|
| 14 |
+
_CODE = """
|
| 15 |
+
import importlib, pickle, sys, types
|
| 16 |
+
if "squadds" not in sys.modules:
|
| 17 |
+
_m = types.ModuleType("squadds")
|
| 18 |
+
_m.__path__ = [{pkg!r}]
|
| 19 |
+
sys.modules["squadds"] = _m
|
| 20 |
+
_f = getattr(importlib.import_module({mod!r}), {name!r})
|
| 21 |
+
_f(*pickle.loads({blob!r}))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _teardown():
|
| 25 |
+
a = sys.modules.get("squadds.ml.capacitance._core.api")
|
| 26 |
+
if a is not None and a._STATE.get("stack") is not None:
|
| 27 |
+
try:
|
| 28 |
+
a._teardown()
|
| 29 |
+
except Exception:
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
import atexit
|
| 34 |
+
atexit.register(_teardown)
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def boot(fn, *args) -> tuple:
|
| 39 |
+
code = _CODE.format(pkg=_PKG_DIR, mod=fn.__module__, name=fn.__name__, blob=pickle.dumps(args))
|
| 40 |
+
return exec, (code, {})
|
src/squadds/ml/capacitance/_core/_tlsq/__init__.py
ADDED
|
File without changes
|
src/squadds/ml/capacitance/_core/_tlsq/embed/__init__.py
ADDED
|
File without changes
|
src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior.py
ADDED
|
@@ -0,0 +1,925 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local (windowed) MoM prior: PRIOR_SCHEME.md Part III prototype.
|
| 2 |
+
|
| 3 |
+
The Maxwell entry C_ij is defined with every other conductor at 0 V, and a ground plane screens the field, so the
|
| 4 |
+
entries of a conductor are set by its neighbourhood. The layout is partitioned into windows (recursive bisection of
|
| 5 |
+
the conductor sites until the metal edge length inside each window fits a panel budget); a window models its core
|
| 6 |
+
conductors (whose matrix rows it provides), the halo conductors within R_g of the core as separate nets at 0 V, the
|
| 7 |
+
ground plane cropped by a margin around core + halo, and every farther conductor filled into the ground. Each window
|
| 8 |
+
is a strip-merged conductor-anchored mesh (the flagship mesh family, PRIOR_SCHEME.md Part II) solved densely with the
|
| 9 |
+
exact near field and one right-hand side per core conductor, optionally Richardson-extrapolated (h and 2 h). Windows
|
| 10 |
+
that are translation copies of one another are solved once (geometric hash). Cost: O(number of distinct windows) x
|
| 11 |
+
(a bounded dense solve), independent of the chip size; a layout that fits one window is one global solve.
|
| 12 |
+
Pairs never co-windowed (farther than R_g apart) are not predicted: NaN in C and True in far_mask.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import hashlib
|
| 18 |
+
import time
|
| 19 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 20 |
+
from multiprocessing import get_context
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import shapely
|
| 24 |
+
from scipy.spatial import cKDTree
|
| 25 |
+
|
| 26 |
+
from ..geometry import sample_boundary
|
| 27 |
+
from ..uge.blocks import _kratio
|
| 28 |
+
from . import proxy as P
|
| 29 |
+
|
| 30 |
+
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)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _valid(g):
|
| 34 |
+
g = shapely.make_valid(g)
|
| 35 |
+
parts = [p for p in getattr(g, "geoms", [g]) if p.geom_type in ("Polygon", "MultiPolygon")]
|
| 36 |
+
return shapely.union_all(parts) if parts else shapely.Polygon()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def gap_of(metals: list) -> float:
|
| 40 |
+
tree = shapely.STRtree(metals)
|
| 41 |
+
d = np.inf
|
| 42 |
+
for i, g in enumerate(metals):
|
| 43 |
+
j, dist = tree.query_nearest(g, return_distance=True, exclusive=True, all_matches=False)
|
| 44 |
+
if len(dist):
|
| 45 |
+
d = min(d, float(dist[0]))
|
| 46 |
+
return d
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def within(geoms: list, targets: list, R: float) -> np.ndarray:
|
| 50 |
+
"""Boolean (len(geoms),): geometry within distance R of any target (STRtree, O(n log n))."""
|
| 51 |
+
out = np.zeros(len(geoms), bool)
|
| 52 |
+
if not targets or not geoms:
|
| 53 |
+
return out
|
| 54 |
+
tree = shapely.STRtree(geoms)
|
| 55 |
+
for t in targets:
|
| 56 |
+
out[tree.query(t, predicate="dwithin", distance=R)] = True
|
| 57 |
+
return out
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def plan_windows(G, conds: list, h: float, R_g: float, margin: float, panel_budget: int, global_budget: int | None = None,
|
| 61 |
+
split_gain: float = 0.75, level_rings: tuple = ()) -> list:
|
| 62 |
+
"""Windows (dicts: core, halo, box). One global window (every conductor in the core, no halo, no crop) when the
|
| 63 |
+
metal edge length of the whole layout fits global_budget panels; otherwise recursive bisection of the conductor
|
| 64 |
+
sites (bbox centres) until the estimated merged panel count of the window fits panel_budget. The estimate weights
|
| 65 |
+
the metal edge length by the grading level it will be meshed at (1, 1/2, 1/4, ... beyond each of level_rings um
|
| 66 |
+
from the core; ground edges beyond R_g of the members are filled and count 0), so the budget measures the core
|
| 67 |
+
content, not the fixed halo + margin overhead. Each split is snapped to the widest coordinate gap between sites in
|
| 68 |
+
the central half of the sorted order (cores follow the natural cell structure); a split whose child is not below
|
| 69 |
+
split_gain x the parent (a dense cluster) is not made and the window is solved whole (H-matrix above dense_max)."""
|
| 70 |
+
sites = np.array([[(b[0] + b[2]) / 2, (b[1] + b[3]) / 2] for b in shapely.bounds(np.array(conds, dtype=object))])
|
| 71 |
+
per_panel = h / PANELS_PER_EDGE_H
|
| 72 |
+
all_idx = np.arange(len(conds))
|
| 73 |
+
L_all = G.length + sum(c.length for c in conds)
|
| 74 |
+
if L_all <= (global_budget if global_budget is not None else panel_budget) * per_panel:
|
| 75 |
+
return [{"core": all_idx, "halo": np.zeros(0, int), "box": None, "n_core": len(conds), "n_halo": 0}]
|
| 76 |
+
out = []
|
| 77 |
+
Gb = G.boundary
|
| 78 |
+
gtree = shapely.STRtree(list(getattr(Gb, "geoms", [Gb])))
|
| 79 |
+
rings = list(level_rings) + [np.inf]
|
| 80 |
+
|
| 81 |
+
def window_of(core):
|
| 82 |
+
halo = within(conds, [conds[i] for i in core], R_g)
|
| 83 |
+
halo[core] = False
|
| 84 |
+
halo = np.nonzero(halo)[0]
|
| 85 |
+
x0, y0, x1, y1 = shapely.union_all([conds[i] for i in np.concatenate([core, halo])]).bounds
|
| 86 |
+
box = (x0 - margin, y0 - margin, x1 + margin, y1 + margin)
|
| 87 |
+
return halo, box
|
| 88 |
+
|
| 89 |
+
def est_panels(core, halo, box):
|
| 90 |
+
cg = shapely.union_all([conds[i] for i in core])
|
| 91 |
+
members = shapely.union_all([conds[i] for i in np.concatenate([core, halo])])
|
| 92 |
+
b = shapely.box(*box)
|
| 93 |
+
gl = shapely.union_all([gtree.geometries[k] for k in gtree.query(b)]) if len(gtree.geometries) else Gb
|
| 94 |
+
edges = shapely.union_all([shapely.intersection(gl, b).intersection(members.buffer(R_g)), members.boundary])
|
| 95 |
+
L, prev, w = 0.0, None, 1.0
|
| 96 |
+
for r in rings:
|
| 97 |
+
ring = cg.buffer(r) if np.isfinite(r) else b
|
| 98 |
+
if prev is not None:
|
| 99 |
+
ring = ring.difference(prev)
|
| 100 |
+
L += w * shapely.intersection(edges, ring).length
|
| 101 |
+
prev, w = (cg.buffer(r) if np.isfinite(r) else b), w / 2
|
| 102 |
+
return L / per_panel
|
| 103 |
+
|
| 104 |
+
def rec(idx, n_parent=None):
|
| 105 |
+
halo, box = window_of(idx)
|
| 106 |
+
n = est_panels(idx, halo, box)
|
| 107 |
+
if len(idx) == 1 or n <= panel_budget or (n_parent is not None and n > split_gain * n_parent):
|
| 108 |
+
out.append({"core": idx, "halo": halo, "box": box, "est_panels": n})
|
| 109 |
+
return
|
| 110 |
+
s = sites[idx]
|
| 111 |
+
ax = int(np.argmax(s.max(0) - s.min(0)))
|
| 112 |
+
order = idx[np.argsort(s[:, ax], kind="stable")]
|
| 113 |
+
x = sites[order, ax]
|
| 114 |
+
lo = max(1, len(order) // 4)
|
| 115 |
+
hi = max(lo + 1, min(len(order), (3 * len(order)) // 4 + 1))
|
| 116 |
+
gaps = x[lo:hi] - x[lo - 1:hi - 1]
|
| 117 |
+
m = lo + int(np.argmax(gaps))
|
| 118 |
+
rec(order[:m], n), rec(order[m:], n)
|
| 119 |
+
|
| 120 |
+
rec(all_idx)
|
| 121 |
+
for w in out:
|
| 122 |
+
w["n_core"], w["n_halo"] = len(w["core"]), len(w["halo"])
|
| 123 |
+
return out
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def window_metals(G, conds: list, w: dict, fill_um: float = 250.0, keep_um: float = 0.0) -> list:
|
| 127 |
+
"""[ground, core..., halo...] of window w: ground = chip ground cropped to the box plus every farther conductor
|
| 128 |
+
inside the box as ground metal (0 V), whose etched surroundings within fill_um are filled in where they are more
|
| 129 |
+
than keep_um from any member (their edges leave the mesh; nothing changes within keep_um of a member)."""
|
| 130 |
+
members = np.concatenate([w["core"], w["halo"]]).astype(int)
|
| 131 |
+
if w["box"] is None:
|
| 132 |
+
return [G] + [conds[i] for i in members]
|
| 133 |
+
box = shapely.box(*w["box"])
|
| 134 |
+
far = np.setdiff1d(np.nonzero(within(conds, [box], 0.0))[0], members)
|
| 135 |
+
Gw = shapely.intersection(G, box)
|
| 136 |
+
if len(far):
|
| 137 |
+
chip = shapely.box(*G.bounds)
|
| 138 |
+
farg = shapely.union_all([conds[i] for i in far])
|
| 139 |
+
fill = shapely.intersection(shapely.intersection(chip.difference(G), farg.buffer(fill_um)), box)
|
| 140 |
+
fill = fill.difference(shapely.union_all([conds[i] for i in members]).buffer(keep_um))
|
| 141 |
+
Gw = shapely.union_all([Gw, shapely.intersection(farg, box), fill])
|
| 142 |
+
return [_valid(Gw)] + [conds[i] for i in members]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def anchored_cells_graded(metals: list, h_f: float, core, levels: tuple, grade: float = 2.0, majority: bool = False):
|
| 146 |
+
"""`proxy.anchored_cells` with the finest panel graded by the distance to the core conductors: h_f within levels[0]
|
| 147 |
+
of `core`, 2 h_f up to levels[1], 4 h_f up to levels[2], ... (same lattice; with levels=() identical to the plain
|
| 148 |
+
mesh). Returns centres (n, 2), sizes (n, 2), owner (n,)."""
|
| 149 |
+
edges = shapely.union_all([g.boundary for g in metals])
|
| 150 |
+
sig = metals[1:] if len(metals) > 1 else metals
|
| 151 |
+
ax, ay = shapely.union_all(sig).bounds[:2]
|
| 152 |
+
X0, Y0, X1, Y1 = shapely.union_all(metals).bounds
|
| 153 |
+
span = max(X1 - X0, Y1 - Y0)
|
| 154 |
+
K = max(0, int(np.ceil(np.log2(max(span / 16, h_f) / h_f))))
|
| 155 |
+
h0 = h_f * 2**K
|
| 156 |
+
ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0))
|
| 157 |
+
ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0))
|
| 158 |
+
gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1))
|
| 159 |
+
xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0)
|
| 160 |
+
gq = P._Geoms(list(metals) + [edges, core])
|
| 161 |
+
lv = np.asarray(levels, float)
|
| 162 |
+
tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool)
|
| 163 |
+
out_c, out_h, out_o = [], [], []
|
| 164 |
+
while len(xs):
|
| 165 |
+
boxes = shapely.box(xs, ys, xs + h, ys + h)
|
| 166 |
+
cov, hit, inn, pcs = P._cover(gq, boxes, h, tst, inn)
|
| 167 |
+
keep = cov.sum(0) > 1e-3
|
| 168 |
+
xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep]
|
| 169 |
+
pcs = [p[keep] for p in pcs]
|
| 170 |
+
cx, cy = xs + h / 2, ys + h / 2
|
| 171 |
+
full = cov.max(0) > 0.999
|
| 172 |
+
if len(lv):
|
| 173 |
+
maybe = h <= h_f * 2 ** len(lv) * 1.0001 # cells that can be at their last level
|
| 174 |
+
hl = np.zeros(len(xs))
|
| 175 |
+
if maybe.any():
|
| 176 |
+
dc = P._distance(gq, len(metals) + 1, boxes[maybe])
|
| 177 |
+
hl[maybe] = h_f * 2.0 ** np.searchsorted(lv, dc, side="right")
|
| 178 |
+
last = h <= hl * 1.0001
|
| 179 |
+
else:
|
| 180 |
+
last = h <= h_f * 1.0001
|
| 181 |
+
d = np.full(len(xs), np.inf)
|
| 182 |
+
far = full & ~last
|
| 183 |
+
d[far] = P._distance(gq, len(metals), boxes[far])
|
| 184 |
+
leaf = full & (last | (h <= grade * d + 1e-12))
|
| 185 |
+
out_c.append(np.stack([cx[leaf], cy[leaf]], 1))
|
| 186 |
+
out_h.append(np.stack([h[leaf], h[leaf]], 1))
|
| 187 |
+
out_o.append(cov[:, leaf].argmax(0))
|
| 188 |
+
cut = last & ~leaf
|
| 189 |
+
if majority and cut.any():
|
| 190 |
+
take = cut & (cov.max(0) >= 0.5)
|
| 191 |
+
out_c.append(np.stack([cx[take], cy[take]], 1))
|
| 192 |
+
out_h.append(np.stack([h[take], h[take]], 1))
|
| 193 |
+
out_o.append(cov[:, take].argmax(0))
|
| 194 |
+
cut = cut & False
|
| 195 |
+
if cut.any():
|
| 196 |
+
gs = gq.get()
|
| 197 |
+
for k, g in enumerate(gs[:len(metals)]):
|
| 198 |
+
shapely.prepare(g)
|
| 199 |
+
sel = np.nonzero(cut & (cov[k] > 1e-3))[0]
|
| 200 |
+
if not len(sel):
|
| 201 |
+
continue
|
| 202 |
+
pcs_k = pcs[k][sel]
|
| 203 |
+
bb = shapely.bounds(pcs_k)
|
| 204 |
+
cen = shapely.get_coordinates(shapely.centroid(pcs_k))
|
| 205 |
+
inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1])
|
| 206 |
+
if not inside.all():
|
| 207 |
+
cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside]))
|
| 208 |
+
out_c.append(cen)
|
| 209 |
+
out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6))
|
| 210 |
+
out_o.append(np.full(len(sel), k))
|
| 211 |
+
gq.put(gs)
|
| 212 |
+
split = ~leaf & ~last
|
| 213 |
+
hs = h[split] / 2
|
| 214 |
+
xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs])
|
| 215 |
+
ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs])
|
| 216 |
+
h = np.concatenate([hs] * 4)
|
| 217 |
+
tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4)
|
| 218 |
+
return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def strip_merge(c, wh, o, metals, h_f: float, lmax_mult: float = 16.0, grade: float = 1.0):
|
| 222 |
+
"""`proxy.strip_merge` with the strip length bounded by lmax_mult x the panel's own lattice level (max(width across
|
| 223 |
+
the edge, h_f), so coarser regions get proportionally longer strips) and by grade x the distance to the nearest
|
| 224 |
+
polygon vertex (coarse square cells therefore merge into longer strips than in proxy.strip_merge)."""
|
| 225 |
+
lines, S, verts = P._segments(metals)
|
| 226 |
+
near = shapely.STRtree(lines).nearest(shapely.points(c))
|
| 227 |
+
d = S[near, 1] - S[near, 0]
|
| 228 |
+
horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1])
|
| 229 |
+
dv, _ = P.cKDTree(verts).query(c, workers=-1)
|
| 230 |
+
allow = np.minimum(lmax_mult * np.maximum(wh.min(1), h_f), grade * dv)
|
| 231 |
+
out_c, out_wh, out_o = [], [], []
|
| 232 |
+
for axis, mask in ((0, horiz), (1, ~horiz)):
|
| 233 |
+
if not mask.any():
|
| 234 |
+
continue
|
| 235 |
+
idx = np.nonzero(mask)[0]
|
| 236 |
+
other = 1 - axis
|
| 237 |
+
key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1)
|
| 238 |
+
order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]])
|
| 239 |
+
idx, key = idx[order], key[order]
|
| 240 |
+
same = np.all(key[1:] == key[:-1], 1)
|
| 241 |
+
lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2
|
| 242 |
+
adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6)
|
| 243 |
+
start = 0
|
| 244 |
+
while start < len(idx):
|
| 245 |
+
end, length, cap = start, wh[idx[start], axis], allow[idx[start]]
|
| 246 |
+
while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]):
|
| 247 |
+
end += 1
|
| 248 |
+
length += wh[idx[end], axis]
|
| 249 |
+
cap = min(cap, allow[idx[end]])
|
| 250 |
+
cc, ww = np.zeros(2), np.zeros(2)
|
| 251 |
+
cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other]
|
| 252 |
+
ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other]
|
| 253 |
+
out_c.append(cc)
|
| 254 |
+
out_wh.append(ww)
|
| 255 |
+
out_o.append(o[idx[start]])
|
| 256 |
+
start = end + 1
|
| 257 |
+
return np.array(out_c), np.array(out_wh), np.array(out_o)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
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,
|
| 261 |
+
grade: float = 2.0, rich: bool = True, dense_max: int = 12000, levels: tuple = ()) -> tuple:
|
| 262 |
+
"""Rows of the Maxwell matrix for the core conductors (metals[1:1+n_core]): (rows (n_core, len(metals)), info).
|
| 263 |
+
levels: distances (um) from the core beyond which the finest panel doubles (core-graded mesh); () = uniform."""
|
| 264 |
+
info = {}
|
| 265 |
+
core = shapely.union_all(metals[1:1 + n_core])
|
| 266 |
+
|
| 267 |
+
def one(hh, tag, majority=False):
|
| 268 |
+
t = time.perf_counter()
|
| 269 |
+
raw = anchored_cells_graded(metals, hh, core, levels, grade, majority=majority)
|
| 270 |
+
c, wh, o = strip_merge(*raw, metals, hh, lmax_mult, merge_grade)
|
| 271 |
+
info[f"mesh_s_{tag}"], info[f"raw_{tag}"], info[f"panels_{tag}"] = time.perf_counter() - t, len(raw[0]), len(c)
|
| 272 |
+
info[f"share_{tag}"] = [float(np.mean(o == 0)), float(np.mean((o >= 1) & (o <= n_core))), float(np.mean(o > n_core))]
|
| 273 |
+
t = time.perf_counter()
|
| 274 |
+
B = (o[:, None] == np.arange(1, 1 + n_core)[None, :]).astype(float)
|
| 275 |
+
if len(c) <= dense_max:
|
| 276 |
+
A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential)
|
| 277 |
+
info[f"assemble_s_{tag}"] = time.perf_counter() - t
|
| 278 |
+
t = time.perf_counter()
|
| 279 |
+
try:
|
| 280 |
+
Q = P._chol_solve(A, B)
|
| 281 |
+
except np.linalg.LinAlgError: # cut panels of different nets overlap: whole finest cells by majority (as the flagship)
|
| 282 |
+
if majority:
|
| 283 |
+
raise
|
| 284 |
+
del A
|
| 285 |
+
info[f"majority_{tag}"] = True
|
| 286 |
+
return one(hh, tag, majority=True)
|
| 287 |
+
info[f"solver_{tag}"] = "dense"
|
| 288 |
+
else:
|
| 289 |
+
H = P._HMatrix(c, wh, eps_r, P.HMAT["leaf"], P.HMAT["eta"], P.HMAT["eps"])
|
| 290 |
+
info[f"assemble_s_{tag}"] = time.perf_counter() - t
|
| 291 |
+
t = time.perf_counter()
|
| 292 |
+
Xp, _, _ = H.pcg(B[H.perm], P.HMAT["tol"], P.HMAT["maxit"])
|
| 293 |
+
Q = np.empty_like(Xp)
|
| 294 |
+
Q[H.perm] = Xp
|
| 295 |
+
info[f"solver_{tag}"] = "H-matrix PCG"
|
| 296 |
+
info[f"solve_s_{tag}"] = time.perf_counter() - t
|
| 297 |
+
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
|
| 298 |
+
|
| 299 |
+
Rf = one(h, "f")
|
| 300 |
+
if not rich:
|
| 301 |
+
return Rf, info
|
| 302 |
+
Rc = one(2 * h, "c")
|
| 303 |
+
return 2 * Rf - Rc, info
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def canonical_hash(metals: list, n_core: int, h: float) -> str:
|
| 307 |
+
"""Translation-invariant key of a window (lattice anchored to the signal bbox, coordinates rounded to 0.1 nm)."""
|
| 308 |
+
x0, y0 = shapely.union_all(metals[1:]).bounds[:2]
|
| 309 |
+
tr = [shapely.transform(g, lambda xy: np.round(xy - [x0, y0], 4)) for g in metals]
|
| 310 |
+
hsh = hashlib.sha1(f"{n_core}:{h:.9g}:".encode())
|
| 311 |
+
for g in tr:
|
| 312 |
+
hsh.update(shapely.to_wkb(g))
|
| 313 |
+
return hsh.hexdigest()
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _job(args):
|
| 317 |
+
wi, metals, n_core, h, kw = args
|
| 318 |
+
rows, info = solve_window_rows(metals, n_core, h, **kw)
|
| 319 |
+
return wi, rows, info
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def local_prior(G, conds: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, rich: bool = True, panel_budget: int = 12000,
|
| 323 |
+
halo_gaps: float = 100.0, margin_gaps: float = 100.0, margin_min_um: float = 150.0, fill_um: float = 250.0,
|
| 324 |
+
lmax_mult: float = 16.0, merge_grade: float = 1.0, workers: int = 1, cache: bool = True, dense_max: int = 12000,
|
| 325 |
+
global_budget: int | None = None, level_gaps: tuple = ()) -> tuple:
|
| 326 |
+
"""Local prior of a layout (ground G, conductors conds, never merged): (C (N+1, N+1) fF with NaN for far pairs,
|
| 327 |
+
far_mask, info). Finest panel h = gap / cells_per_gap; with rich=True the Richardson pair is (h, 2 h). Windows
|
| 328 |
+
are solved in parallel on `workers` processes."""
|
| 329 |
+
t_all = time.perf_counter()
|
| 330 |
+
metals_all = [G] + list(conds)
|
| 331 |
+
gap = gap_of(metals_all)
|
| 332 |
+
h = gap / cells_per_gap
|
| 333 |
+
R_g, margin = halo_gaps * gap, max(margin_gaps * gap, margin_min_um)
|
| 334 |
+
t = time.perf_counter()
|
| 335 |
+
wins = plan_windows(G, conds, h, R_g, margin, panel_budget, global_budget, level_rings=tuple(float(g) * gap for g in level_gaps))
|
| 336 |
+
t_plan = time.perf_counter() - t
|
| 337 |
+
t = time.perf_counter()
|
| 338 |
+
mats = [window_metals(G, conds, w, fill_um, keep_um=R_g) for w in wins]
|
| 339 |
+
keys = [canonical_hash(m, w["n_core"], h) if cache else str(i) for i, (m, w) in enumerate(zip(mats, wins))]
|
| 340 |
+
t_build = time.perf_counter() - t
|
| 341 |
+
uniq = {}
|
| 342 |
+
for i, k in enumerate(keys):
|
| 343 |
+
uniq.setdefault(k, i)
|
| 344 |
+
kw = dict(eps_r=eps_r, lmax_mult=lmax_mult, merge_grade=merge_grade, rich=rich, dense_max=dense_max,
|
| 345 |
+
levels=tuple(float(g) * gap for g in level_gaps))
|
| 346 |
+
jobs = [(i, mats[i], wins[i]["n_core"], h, kw) for i in uniq.values()]
|
| 347 |
+
t = time.perf_counter()
|
| 348 |
+
if workers > 1 and len(jobs) > 1:
|
| 349 |
+
with ProcessPoolExecutor(workers, mp_context=get_context("fork")) as ex:
|
| 350 |
+
res = {wi: (rows, info) for wi, rows, info in ex.map(_job, jobs)}
|
| 351 |
+
else:
|
| 352 |
+
res = {wi: (rows, info) for wi, rows, info in map(_job, jobs)}
|
| 353 |
+
t_solve = time.perf_counter() - t
|
| 354 |
+
N = len(conds) + 1
|
| 355 |
+
acc, cnt = np.zeros((N, N)), np.zeros((N, N))
|
| 356 |
+
for i, w in enumerate(wins):
|
| 357 |
+
rows, _ = res[uniq[keys[i]]]
|
| 358 |
+
idx = np.concatenate([[0], w["core"] + 1, w["halo"] + 1]).astype(int)
|
| 359 |
+
for k, ci in enumerate(w["core"] + 1):
|
| 360 |
+
acc[ci, idx] += rows[k]
|
| 361 |
+
cnt[ci, idx] += 1
|
| 362 |
+
C = np.full((N, N), np.nan)
|
| 363 |
+
have = cnt > 0
|
| 364 |
+
C[have] = acc[have] / cnt[have]
|
| 365 |
+
# symmetrise: mean of the two estimates when both exist, the one available otherwise; ground row from the columns
|
| 366 |
+
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))
|
| 367 |
+
S[0, 0] = np.nan
|
| 368 |
+
far = ~(have | have.T)
|
| 369 |
+
np.fill_diagonal(far, False)
|
| 370 |
+
infos = [res[j][1] for j in uniq.values()]
|
| 371 |
+
info = {"n_windows": len(wins), "n_unique": len(uniq), "h_um": h, "min_gap_um": gap, "R_g_um": R_g, "margin_um": margin,
|
| 372 |
+
"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],
|
| 373 |
+
"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],
|
| 374 |
+
"solvers": sorted({i["solver_f"] for i in infos}), "n_far_pairs": int(far[np.triu_indices(N, 1)].sum()),
|
| 375 |
+
"mesh_s": sum(i["mesh_s_f"] + i.get("mesh_s_c", 0.0) for i in infos),
|
| 376 |
+
"assemble_s": sum(i["assemble_s_f"] + i.get("assemble_s_c", 0.0) for i in infos),
|
| 377 |
+
"solve_s": sum(i["solve_s_f"] + i.get("solve_s_c", 0.0) for i in infos),
|
| 378 |
+
"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}
|
| 379 |
+
return S, far, info
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
# ---------------------------------------------------------------- flagship-fast: the cheap prior (PRIOR_SCHEME.md Part III, sections 12 and 16)
|
| 383 |
+
# Hybrid H = micro-MoM (`micro_mom`: the flagship mesh family at a fixed panel budget per window, dense Cholesky) for self,
|
| 384 |
+
# ground and co-windowed pairs + the closed-form edge-coupling prior (`formula_prior`) for pairs never co-windowed.
|
| 385 |
+
# Mirrored verbatim (function sources) in deploy/tlsq_infer/src/tlsq_infer/_vendor/fastprior.py.
|
| 386 |
+
|
| 387 |
+
# formula constants: frozen 2026-10-09, not tuned on labels
|
| 388 |
+
FORMULA_STEP_UM = 0.25 # boundary sample step (as the pair tokens)
|
| 389 |
+
FORMULA_R_GAPS = 150.0 # pairs farther apart than this (in smallest gaps) use the bounding-box form
|
| 390 |
+
FORMULA_SCREEN_UM = 1.0 # the screening factor is evaluated every FORMULA_SCREEN_UM of boundary and held in between
|
| 391 |
+
LITE_REFINE = 3 # rejected window solves: refine h by 2 up to this many times before majority-owned cells
|
| 392 |
+
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
|
| 393 |
+
LITE_WINDOW_BUDGET = 2.0 # windows of large layouts: panel budget = this x the budget of the one-window (component) prior
|
| 394 |
+
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)
|
| 395 |
+
LITE_MAX_CORE = [None] # windows of large layouts: conductors per core (None = the max_core argument; PRIOR_SCHEME.md 14.4.2)
|
| 396 |
+
LITE_GROWTH = 2.0 # merged panels per halving of h (measured 1.6-2.2 on the training families)
|
| 397 |
+
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)
|
| 398 |
+
DIPOLE_K = 8 # nearest boundary samples searched for the nearest other conductor (gbar)
|
| 399 |
+
ROW_SUM_EPS = 0.0143 # training median of 1 - sum_j |C_ij| / C_ii (self = row sum / (1 - eps))
|
| 400 |
+
EPS0_FF_UM = 8.8541878128e-3
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def plan_cores(sites: np.ndarray, max_core: int = 8) -> list:
|
| 404 |
+
"""Cores (index arrays) by recursive bisection of the conductor sites (n, 2) along the longer extent until each core
|
| 405 |
+
has <= max_core conductors; each split is snapped to the widest coordinate gap between sites in the central half
|
| 406 |
+
of the sorted order (ties broken by the other coordinate, so the cores do not depend on the conductor order)."""
|
| 407 |
+
out = []
|
| 408 |
+
|
| 409 |
+
def rec(idx):
|
| 410 |
+
if len(idx) <= max_core:
|
| 411 |
+
out.append(idx)
|
| 412 |
+
return
|
| 413 |
+
s = sites[idx]
|
| 414 |
+
ax = int(np.argmax(s.max(0) - s.min(0)))
|
| 415 |
+
order = idx[np.lexsort((s[:, 1 - ax], s[:, ax]))]
|
| 416 |
+
x = sites[order, ax]
|
| 417 |
+
lo = max(1, len(order) // 4)
|
| 418 |
+
hi = max(lo + 1, min(len(order), (3 * len(order)) // 4 + 1))
|
| 419 |
+
m = lo + int(np.argmax(x[lo:hi] - x[lo - 1:hi - 1]))
|
| 420 |
+
rec(order[:m]), rec(order[m:])
|
| 421 |
+
|
| 422 |
+
rec(np.arange(len(sites)))
|
| 423 |
+
return out
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def _rot90(k: int):
|
| 427 |
+
"""Exact rotation of coordinates by k x 90 degrees (swaps and sign flips only)."""
|
| 428 |
+
def f(xy):
|
| 429 |
+
x, y = xy[:, 0], xy[:, 1]
|
| 430 |
+
return np.stack([(x, y), (-y, x), (-x, -y), (y, -x)][k % 4], 1)
|
| 431 |
+
return f
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def canonical_frames(G, conds: list) -> list:
|
| 435 |
+
"""The layout in canonical frames, so that the lattice-anchored mesh (and hence the prior) does not depend on the
|
| 436 |
+
position, the 90-degree orientation or the conductor order of the input: rotations by k x 90 degrees whose
|
| 437 |
+
rotation-invariant key (signal bounding box, sorted conductor centroids and convex-hull vertices about the box
|
| 438 |
+
centre, ground bounds, rounded to 1 nm) is smallest (several when the layout is symmetric), translation of the signal
|
| 439 |
+
bounding box corner to the origin, coordinates rounded to 1e-6 um, collinear vertices removed (`shapely.simplify(0)`),
|
| 440 |
+
rings in normal form (`shapely.normalize`), conductors sorted by (centroid, area). Returns [(G, conds, order)]:
|
| 441 |
+
conds[k] of a frame is input conductor order[k]."""
|
| 442 |
+
keys = []
|
| 443 |
+
for k in range(4):
|
| 444 |
+
f = _rot90(k)
|
| 445 |
+
sig = [shapely.transform(c, f) for c in conds]
|
| 446 |
+
b = shapely.bounds(np.array(sig, dtype=object))
|
| 447 |
+
x0, y0, x1, y1 = b[:, 0].min(), b[:, 1].min(), b[:, 2].max(), b[:, 3].max()
|
| 448 |
+
cen = shapely.get_coordinates(shapely.centroid(np.array(sig, dtype=object))) - [(x0 + x1) / 2, (y0 + y1) / 2]
|
| 449 |
+
hull = shapely.get_coordinates(shapely.convex_hull(shapely.union_all(sig)))[:-1] - [(x0 + x1) / 2, (y0 + y1) / 2]
|
| 450 |
+
gb = np.round(np.array(shapely.transform(G, f).bounds) - [(x0 + x1) / 2, (y0 + y1) / 2] * 2, 3)
|
| 451 |
+
key = ((round(x1 - x0, 3), round(y1 - y0, 3)) + tuple(sorted(map(tuple, np.round(cen, 3).tolist())))
|
| 452 |
+
+ tuple(sorted(map(tuple, np.round(hull, 3).tolist()))) + tuple(gb.tolist()))
|
| 453 |
+
keys.append((key, k, x0, y0))
|
| 454 |
+
best = min(kk[0] for kk in keys)
|
| 455 |
+
out = []
|
| 456 |
+
for key, k, x0, y0 in keys:
|
| 457 |
+
if key != best:
|
| 458 |
+
continue
|
| 459 |
+
f = _rot90(k)
|
| 460 |
+
|
| 461 |
+
def to(g, f=f, x0=x0, y0=y0):
|
| 462 |
+
return shapely.normalize(shapely.simplify(shapely.transform(g, lambda xy: np.round(f(xy) - [x0, y0], 6)), 0.0))
|
| 463 |
+
|
| 464 |
+
cs = [to(c) for c in conds]
|
| 465 |
+
cen = shapely.get_coordinates(shapely.centroid(np.array(cs, dtype=object)))
|
| 466 |
+
order = np.lexsort((np.round([c.area for c in cs], 6), np.round(cen[:, 1], 6), np.round(cen[:, 0], 6)))
|
| 467 |
+
out.append((to(G), [cs[i] for i in order], order))
|
| 468 |
+
return out
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def _gap_size(metals: list) -> tuple:
|
| 472 |
+
"""(smallest gap, layout size) exactly as mom_capacitance_gds_flagship computes them (all pairs; small layouts)."""
|
| 473 |
+
bbox = shapely.union_all(metals).bounds
|
| 474 |
+
size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 475 |
+
gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
|
| 476 |
+
return gap, size
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
def _graded_mesh(metals: list, n_core: int, h: float, levels: tuple, majority: bool = False) -> tuple:
|
| 480 |
+
"""Core-graded flagship-family mesh (`anchored_cells_graded` + `strip_merge`): finest panel h within levels[0] of the
|
| 481 |
+
core conductors (metals[1:1 + n_core]), doubling beyond each level. Returns (centres, sizes, owners, h, raw count)."""
|
| 482 |
+
raw = anchored_cells_graded(metals, h, shapely.union_all(metals[1:1 + n_core]), levels, majority=majority)
|
| 483 |
+
c, wh, o = strip_merge(*raw, metals, h)
|
| 484 |
+
return c, wh, o, h, len(raw[0])
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _lite_mesh(metals: list, h: float, budget: float, n_core: int = 0, levels: tuple = ()) -> tuple:
|
| 488 |
+
"""Flagship-family mesh at the finest lattice level h 2^k predicted to fit the budget: a probe mesh at the level
|
| 489 |
+
estimated (2 merged panels per h of metal edge) to hold ~budget / 4 panels, then the level LITE_GROWTH^j finer
|
| 490 |
+
predicted to hold <= budget panels (each halving of h multiplies the panels by ~LITE_GROWTH), doubled while it does
|
| 491 |
+
not fit. levels (um from the n_core core conductors): core-graded mesh (`_graded_mesh`); () = uniform
|
| 492 |
+
(`proxy.mesh_flagship`). With an unbounded budget: the mesh at h. Returns (centres, sizes, owners, h, raw count)."""
|
| 493 |
+
def mesh(hh):
|
| 494 |
+
if not levels:
|
| 495 |
+
return P.mesh_flagship(metals, hh, budget)
|
| 496 |
+
while True:
|
| 497 |
+
r = _graded_mesh(metals, n_core, hh, levels)
|
| 498 |
+
if len(r[0]) <= budget:
|
| 499 |
+
return r
|
| 500 |
+
hh *= 2.0
|
| 501 |
+
|
| 502 |
+
if not np.isfinite(budget):
|
| 503 |
+
return mesh(h)
|
| 504 |
+
L = sum(g.length for g in metals)
|
| 505 |
+
k = max(0, int(np.ceil(np.log2(max(2.0 * L / (h * budget / 4), 1.0)))))
|
| 506 |
+
probe = mesh(h * 2.0**k)
|
| 507 |
+
j = min(int(np.floor(np.log(budget / len(probe[0])) / np.log(LITE_GROWTH))), int(round(np.log2(probe[3] / h))))
|
| 508 |
+
return probe if j <= 0 else mesh(probe[3] / 2.0**j)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _sym_solve(A, B):
|
| 512 |
+
"""Solve with the lower triangle of the Fortran-ordered A from `proxy._assemble`: Cholesky, or the symmetric
|
| 513 |
+
indefinite (Bunch-Kaufman) factorisation when A is not positive definite."""
|
| 514 |
+
try:
|
| 515 |
+
return P._chol_solve(A.copy(order="F"), B)
|
| 516 |
+
except np.linalg.LinAlgError:
|
| 517 |
+
from scipy.linalg import solve
|
| 518 |
+
return solve(A, B, lower=True, assume_a="sym", overwrite_a=True, check_finite=False)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def _window_solve(metals: list, n_core: int, h: float, budget: float, eps_r: float, all_rhs: bool, levels: tuple = ()) -> tuple:
|
| 522 |
+
"""Flagship-family mesh of one window at the lattice level of h that fits the budget (`_lite_mesh`), exact near
|
| 523 |
+
field, dense Cholesky (H-matrix PCG above DENSE_MAX panels); right-hand sides: every metal (all_rhs, as
|
| 524 |
+
`proxy._cap_flagship`) or the n_core core conductors; levels: core-graded mesh (`_lite_mesh`). A solve is rejected
|
| 525 |
+
when the system is not positive definite, a metal has no panel or (all_rhs) a mutual entry is not negative (cut
|
| 526 |
+
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
|
| 527 |
+
meshed with majority-owned finest cells (as the flagship). Returns (R (n_rhs, n_metals) charges per metal, info)."""
|
| 528 |
+
cols = np.arange(len(metals)) if all_rhs else np.arange(1, 1 + n_core)
|
| 529 |
+
t_mesh = t_asm = t_sol = 0.0
|
| 530 |
+
hh, cap, refined, majority = h, budget, 0, False
|
| 531 |
+
while True:
|
| 532 |
+
t = time.perf_counter()
|
| 533 |
+
if not refined:
|
| 534 |
+
c, wh, o, hh, n_raw = _lite_mesh(metals, hh, cap, n_core, levels)
|
| 535 |
+
elif levels:
|
| 536 |
+
c, wh, o, hh, n_raw = _graded_mesh(metals, n_core, hh, levels, majority)
|
| 537 |
+
else:
|
| 538 |
+
c, wh, o, hh, n_raw = P.mesh_flagship(metals, hh, cap, majority=majority)
|
| 539 |
+
t_mesh += time.perf_counter() - t
|
| 540 |
+
t = time.perf_counter()
|
| 541 |
+
try:
|
| 542 |
+
if len(c) <= P.DENSE_MAX:
|
| 543 |
+
A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential)
|
| 544 |
+
t_asm += time.perf_counter() - t
|
| 545 |
+
t = time.perf_counter()
|
| 546 |
+
Bm = (o[:, None] == cols[None, :]).astype(float)
|
| 547 |
+
if all_rhs:
|
| 548 |
+
Q = P._chol_solve(A, Bm)
|
| 549 |
+
else: # windows: an indefinite system (overlapping cut panels on the coarse graded levels) is solved by LDL^T
|
| 550 |
+
Q = _sym_solve(A, Bm)
|
| 551 |
+
else:
|
| 552 |
+
Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)[:, cols]
|
| 553 |
+
R = np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1)
|
| 554 |
+
off = np.ones(R.shape, bool)
|
| 555 |
+
off[np.arange(len(cols)), cols] = False
|
| 556 |
+
ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and (not all_rhs or np.all(R[off] < 0)))
|
| 557 |
+
except np.linalg.LinAlgError:
|
| 558 |
+
ok = False
|
| 559 |
+
t_sol += time.perf_counter() - t
|
| 560 |
+
if ok or majority:
|
| 561 |
+
break
|
| 562 |
+
if refined < LITE_REFINE:
|
| 563 |
+
hh, cap, refined = hh / 2, np.inf, refined + 1
|
| 564 |
+
else:
|
| 565 |
+
majority = True
|
| 566 |
+
return R, {"h_um": hh, "panels": len(c), "raw": n_raw, "refined": refined, "majority": majority, "mesh_s": t_mesh,
|
| 567 |
+
"assemble_s": t_asm, "solve_s": t_sol}
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def _lite_window(G, conds: list, core, R_g: float, margin: float, fill_um: float, tree, etched) -> tuple:
|
| 571 |
+
"""Window of a core: ([ground, core..., halo...], halo). Halo = conductors within R_g of a core conductor (separate
|
| 572 |
+
nets at 0 V); ground = chip ground clipped to the core + halo box widened by margin, plus every farther conductor in
|
| 573 |
+
the box as ground metal with its etched surroundings within fill_um filled where farther than R_g from a member."""
|
| 574 |
+
hit = tree.query([conds[i] for i in core], predicate="dwithin", distance=R_g)[1]
|
| 575 |
+
halo = np.setdiff1d(np.unique(hit), core)
|
| 576 |
+
members = np.concatenate([core, halo]).astype(int)
|
| 577 |
+
b = shapely.bounds(np.array([conds[i] for i in members], dtype=object))
|
| 578 |
+
box = (b[:, 0].min() - margin, b[:, 1].min() - margin, b[:, 2].max() + margin, b[:, 3].max() + margin)
|
| 579 |
+
far = np.setdiff1d(tree.query(shapely.box(*box), predicate="intersects"), members)
|
| 580 |
+
Gw = shapely.clip_by_rect(G, *box)
|
| 581 |
+
if len(far):
|
| 582 |
+
farg = shapely.clip_by_rect(shapely.union_all([conds[i] for i in far]), *box)
|
| 583 |
+
fill = shapely.intersection(shapely.clip_by_rect(etched, *box), farg.buffer(fill_um, quad_segs=4))
|
| 584 |
+
fill = fill.difference(shapely.union_all([conds[i] for i in members]).buffer(R_g, quad_segs=4))
|
| 585 |
+
Gw = shapely.union_all([Gw, farg, fill])
|
| 586 |
+
return [_valid(Gw)] + [conds[i] for i in members], halo
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
_LITE_BUDGET_USED: list = [0.0]
|
| 590 |
+
_LITE: dict = {} # layout of the running micro_mom call, inherited by forked window workers
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _lite_job(k: int) -> tuple:
|
| 594 |
+
L = _LITE
|
| 595 |
+
t = time.perf_counter()
|
| 596 |
+
metals, halo = _lite_window(L["G"], L["conds"], L["cores"][k], L["R_g"], L["margin"], L["fill_um"], L["tree"], L["etched"])
|
| 597 |
+
t_build = time.perf_counter() - t
|
| 598 |
+
bx = shapely.bounds(metals[0])
|
| 599 |
+
h = max(L["h"], max(bx[2] - bx[0], bx[3] - bx[1]) / 4096)
|
| 600 |
+
budget = L["budget"]
|
| 601 |
+
if LITE_WINDOW_PPG[0]: # resolution-controlled windows (PRIOR_SCHEME.md 14.4): finest panel gap / ppg, no budget
|
| 602 |
+
h, budget = L["gap"] / LITE_WINDOW_PPG[0], np.inf
|
| 603 |
+
R, info = _window_solve(metals, len(L["cores"][k]), h, budget, L["eps_r"], False, L["levels"])
|
| 604 |
+
info.update(build_s=t_build, n_halo=len(halo), n_core=len(L["cores"][k]))
|
| 605 |
+
return k, halo, R, info
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def micro_mom(G, conds: list, eps_r: float = 11.45, budget: float = 1500, cells_per_gap: float = 3.0, max_core: int = 8,
|
| 609 |
+
halo_gaps: float = 100.0, margin_gaps: float = 100.0, margin_min_um: float = 150.0, fill_um: float = 250.0,
|
| 610 |
+
workers: int = 1, level_gaps: tuple = LITE_LEVEL_GAPS, window_budget: float | None = None, canonical: bool = True) -> tuple:
|
| 611 |
+
"""Cheap micro-MoM prior (PRIOR_SCHEME.md section 12, M / hybrid H): (C (N+1, N+1) fF Maxwell, far_mask, info).
|
| 612 |
+
<= max_core conductors: one global window = the layout as given, h = max(gap / cells_per_gap, size / 4096) doubled
|
| 613 |
+
on the flagship lattice until the merged mesh has <= budget panels, every metal excited (with budget = inf this is
|
| 614 |
+
`proxy.mom_capacitance_gds_flagship(rich=False)` bit for bit; `_lite_mesh` picks the level). More conductors: cores of <= max_core by bisection,
|
| 615 |
+
one window per core (halo within halo_gaps, ground clipped at margin_gaps), entry (i, j) = mean of the two window
|
| 616 |
+
estimates when both exist (a non-negative window estimate is not used), ground row from the columns, C_00 = row sum /
|
| 617 |
+
(1 - ROW_SUM_EPS); pairs never co-windowed (far_mask, > halo_gaps apart) in different ground pockets take the screened
|
| 618 |
+
dipole value (`dipole_far`), in the same pocket the closed form (`formula_prior`, quadrature step one smallest gap). level_gaps: core-graded window
|
| 619 |
+
meshes (finest panel within level_gaps[0] smallest gaps of the core, doubling beyond each level); window systems that
|
| 620 |
+
are not positive definite are solved by LDL^T; window budget = window_budget or LITE_WINDOW_BUDGET x budget. Windows
|
| 621 |
+
run on `workers` forked processes. canonical: solved in the `canonical_frames` (mean over them when the layout is
|
| 622 |
+
symmetric; invariant to translation, 90-degree rotation and conductor order), returned in the input order."""
|
| 623 |
+
t_all = time.perf_counter()
|
| 624 |
+
if canonical: # mean over the canonical frames (one unless the layout is symmetric), in the input order
|
| 625 |
+
runs = []
|
| 626 |
+
for Gc, cc, order in canonical_frames(G, conds):
|
| 627 |
+
C, far, info = micro_mom(Gc, cc, eps_r, budget, cells_per_gap, max_core, halo_gaps, margin_gaps, margin_min_um, fill_um,
|
| 628 |
+
workers, level_gaps, window_budget, canonical=False)
|
| 629 |
+
inv = np.r_[0, np.argsort(order) + 1]
|
| 630 |
+
runs.append((C[np.ix_(inv, inv)], far[np.ix_(inv, inv)], info))
|
| 631 |
+
C = runs[0][0] if len(runs) == 1 else sum(r[0] for r in runs) / len(runs)
|
| 632 |
+
far = np.logical_or.reduce([r[1] for r in runs])
|
| 633 |
+
info = runs[0][2]
|
| 634 |
+
for k in ("mesh_s", "assemble_s", "solve_s", "build_s", "formula_s"):
|
| 635 |
+
info[k] = sum(r[2][k] for r in runs)
|
| 636 |
+
info["n_frames"] = len(runs)
|
| 637 |
+
info["total_s"] = time.perf_counter() - t_all
|
| 638 |
+
return C, far, info
|
| 639 |
+
metals = [G] + list(conds)
|
| 640 |
+
N = len(metals)
|
| 641 |
+
far = np.zeros((N, N), bool)
|
| 642 |
+
if len(conds) <= max_core:
|
| 643 |
+
gap, size = _gap_size(metals)
|
| 644 |
+
h = max(gap / cells_per_gap, size / 4096)
|
| 645 |
+
R, wi = _window_solve(metals, len(conds), h, budget, eps_r, True)
|
| 646 |
+
C = 0.5 * (R + R.T)
|
| 647 |
+
info = {"n_windows": 1, "min_gap_um": gap, "h_um": [wi["h_um"]], "panels": [wi["panels"]], "panels_per_gap": [gap / wi["h_um"]],
|
| 648 |
+
"majority": [wi["majority"]], "refined": [wi["refined"]], "mesh_s": wi["mesh_s"], "assemble_s": wi["assemble_s"], "solve_s": wi["solve_s"],
|
| 649 |
+
"build_s": 0.0, "plan_s": 0.0, "formula_s": 0.0, "n_far_pairs": 0, "budget": budget}
|
| 650 |
+
info["total_s"] = time.perf_counter() - t_all
|
| 651 |
+
return C, far, info
|
| 652 |
+
t = time.perf_counter()
|
| 653 |
+
gap = gap_of(metals)
|
| 654 |
+
R_g, margin = halo_gaps * gap, max(margin_gaps * gap, margin_min_um)
|
| 655 |
+
b = shapely.bounds(np.array(conds, dtype=object))
|
| 656 |
+
cores = plan_cores(np.stack([(b[:, 0] + b[:, 2]) / 2, (b[:, 1] + b[:, 3]) / 2], 1), LITE_MAX_CORE[0] or max_core)
|
| 657 |
+
tree = shapely.STRtree(conds)
|
| 658 |
+
etched = shapely.box(*G.bounds).difference(G)
|
| 659 |
+
_LITE.clear()
|
| 660 |
+
_LITE.update(G=G, conds=conds, cores=cores, R_g=R_g, margin=margin, fill_um=fill_um, tree=tree, etched=etched,
|
| 661 |
+
h=gap / cells_per_gap, gap=gap, budget=LITE_WINDOW_BUDGET * budget if window_budget is None else window_budget, eps_r=eps_r,
|
| 662 |
+
levels=tuple(float(x) * gap for x in level_gaps))
|
| 663 |
+
_LITE_BUDGET_USED[:] = [_LITE["budget"]]
|
| 664 |
+
t_plan = time.perf_counter() - t
|
| 665 |
+
t = time.perf_counter()
|
| 666 |
+
if workers > 1 and len(cores) > 1:
|
| 667 |
+
with ProcessPoolExecutor(min(workers, len(cores)), mp_context=get_context("fork")) as ex:
|
| 668 |
+
res = list(ex.map(_lite_job, range(len(cores))))
|
| 669 |
+
else:
|
| 670 |
+
res = [_lite_job(k) for k in range(len(cores))]
|
| 671 |
+
t_win = time.perf_counter() - t
|
| 672 |
+
_LITE.clear()
|
| 673 |
+
acc, cnt = np.zeros((N, N)), np.zeros((N, N))
|
| 674 |
+
for k, halo, R, _ in res:
|
| 675 |
+
idx = np.concatenate([[0], cores[k] + 1, halo + 1]).astype(int)
|
| 676 |
+
for r, ci in enumerate(cores[k] + 1):
|
| 677 |
+
use = (R[r] < 0) | (idx == ci) # a non-negative mutual estimate of a window (tiny far entries) is not used
|
| 678 |
+
acc[ci, idx[use]] += R[r][use]
|
| 679 |
+
cnt[ci, idx[use]] += 1
|
| 680 |
+
have = cnt > 0
|
| 681 |
+
Cw = np.where(have, acc / np.where(have, cnt, 1), 0.0)
|
| 682 |
+
C = np.where(have & have.T, 0.5 * (Cw + Cw.T), np.where(have, Cw, Cw.T))
|
| 683 |
+
far = ~(have | have.T)
|
| 684 |
+
np.fill_diagonal(far, False)
|
| 685 |
+
t = time.perf_counter()
|
| 686 |
+
iu = np.nonzero(np.triu(far, 1))
|
| 687 |
+
t_dip, n_dip = 0.0, 0
|
| 688 |
+
if len(iu[0]):
|
| 689 |
+
pid = np.r_[-10**9, pocket_ids(G, conds)]
|
| 690 |
+
cross = pid[iu[0]] != pid[iu[1]] # different ground pockets: screened dipole; same pocket: closed form
|
| 691 |
+
if (~cross).any():
|
| 692 |
+
F, _ = formula_prior(G, conds, eps_r, step_um=max(FORMULA_STEP_UM, gap), pairs=np.stack(iu, 1)[~cross], gap=gap, workers=workers)
|
| 693 |
+
C[iu[0][~cross], iu[1][~cross]] = F[iu[0][~cross], iu[1][~cross]]
|
| 694 |
+
if cross.any():
|
| 695 |
+
t_dip = time.perf_counter()
|
| 696 |
+
C[iu[0][cross], iu[1][cross]] = dipole_far(G, conds, np.stack(iu, 1)[cross], eps_r, gap)
|
| 697 |
+
t_dip, n_dip = time.perf_counter() - t_dip, int(cross.sum())
|
| 698 |
+
C[iu[1], iu[0]] = C[iu]
|
| 699 |
+
t_form = time.perf_counter() - t
|
| 700 |
+
C[0, 0] = np.abs(C[0, 1:]).sum() / (1 - ROW_SUM_EPS)
|
| 701 |
+
infos = [r[3] for r in res]
|
| 702 |
+
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],
|
| 703 |
+
"panels": [i["panels"] for i in infos], "panels_per_gap": [gap / i["h_um"] for i in infos],
|
| 704 |
+
"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],
|
| 705 |
+
"mesh_s": sum(i["mesh_s"] for i in infos), "assemble_s": sum(i["assemble_s"] for i in infos),
|
| 706 |
+
"solve_s": sum(i["solve_s"] for i in infos), "build_s": sum(i["build_s"] for i in infos), "plan_s": t_plan,
|
| 707 |
+
"windows_wall_s": t_win, "formula_s": t_form, "n_far_pairs": int(len(iu[0])), "dipole_s": t_dip,
|
| 708 |
+
"n_dipole_pairs": n_dip, "budget": _LITE_BUDGET_USED[0],
|
| 709 |
+
"workers": workers, "level_gaps": list(level_gaps)}
|
| 710 |
+
info["total_s"] = time.perf_counter() - t_all
|
| 711 |
+
return C, far, info
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def pocket_ids(G, conds: list) -> np.ndarray:
|
| 715 |
+
"""Ground pocket of every conductor: index of the interior ring of the ground metal that contains it (STRtree of the
|
| 716 |
+
rings' polygons, `within`); a conductor in no ring gets its own id (-1 - k)."""
|
| 717 |
+
rings = [shapely.Polygon(r) for p in getattr(G, "geoms", [G]) for r in p.interiors]
|
| 718 |
+
out = -1 - np.arange(len(conds))
|
| 719 |
+
if rings:
|
| 720 |
+
c, r = shapely.STRtree(rings).query(list(conds), predicate="within")
|
| 721 |
+
out[c] = r
|
| 722 |
+
return out
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def _edge_samples(geoms: list, step: float) -> tuple:
|
| 726 |
+
"""Points every <= step along every polygon edge of geoms (vertices included), with the index of their geometry:
|
| 727 |
+
(points (n, 2), owner (n,)). Vectorised over all edges (no per-ring interpolation)."""
|
| 728 |
+
segs, sown = [], []
|
| 729 |
+
for k, g in enumerate(geoms):
|
| 730 |
+
for p in getattr(g, "geoms", [g]):
|
| 731 |
+
for ring in [p.exterior, *p.interiors]:
|
| 732 |
+
xy = np.asarray(ring.coords)
|
| 733 |
+
segs.append(np.stack([xy[:-1], xy[1:]], 1))
|
| 734 |
+
sown.append(np.full(len(xy) - 1, k))
|
| 735 |
+
S, sown = np.concatenate(segs), np.concatenate(sown)
|
| 736 |
+
L = np.sqrt(((S[:, 1] - S[:, 0]) ** 2).sum(1))
|
| 737 |
+
n = np.maximum(1, np.ceil(L / step).astype(int))
|
| 738 |
+
seg = np.repeat(np.arange(len(S)), n)
|
| 739 |
+
t = (np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)) / np.repeat(n, n)
|
| 740 |
+
return S[seg, 0] + t[:, None] * (S[seg, 1] - S[seg, 0]), sown[seg]
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def dipole_far(G, conds: list, pairs, eps_r: float = 11.45, gap: float | None = None) -> np.ndarray:
|
| 744 |
+
"""Screened-dipole far couplings (PRIOR_SCHEME.md 14.2): for metal-index pairs (k, 2) (1 = first conductor),
|
| 745 |
+
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
|
| 746 |
+
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
|
| 747 |
+
nearest other metal: ground edge samples (step gap / 4) by one k-d tree, other conductors by one k-d tree of all
|
| 748 |
+
conductor samples with owner labels (DIPOLE_K neighbours). Returns the values (k,)."""
|
| 749 |
+
metals = [G] + list(conds)
|
| 750 |
+
gap = gap_of(metals) if gap is None else gap
|
| 751 |
+
pairs = np.asarray(pairs, int).reshape(-1, 2)
|
| 752 |
+
pts, own = _edge_samples(list(conds), gap)
|
| 753 |
+
own = own + 1
|
| 754 |
+
sel = np.isin(own, np.unique(pairs))
|
| 755 |
+
q = pts[sel]
|
| 756 |
+
dg, _ = cKDTree(_edge_samples([G], gap / 4)[0]).query(q)
|
| 757 |
+
d, idx = cKDTree(pts).query(q, k=min(DIPOLE_K, len(own)))
|
| 758 |
+
if d.ndim == 1:
|
| 759 |
+
d, idx = d[:, None], idx[:, None]
|
| 760 |
+
d = np.where(own[np.minimum(idx, len(own) - 1)] != own[sel][:, None], d, np.inf).min(1)
|
| 761 |
+
gbar = np.bincount(own[sel], np.minimum(dg, d), len(metals)) / np.maximum(np.bincount(own[sel], minlength=len(metals)), 1)
|
| 762 |
+
area = np.array([g.area for g in metals])
|
| 763 |
+
perim = np.array([g.length for g in metals])
|
| 764 |
+
At = area + ALPHA_GAP_SHARE * perim * gbar
|
| 765 |
+
cen = shapely.get_coordinates(shapely.centroid(np.array(metals, dtype=object)))
|
| 766 |
+
a, b = pairs[:, 0], pairs[:, 1]
|
| 767 |
+
d2 = ((cen[a] - cen[b]) ** 2).sum(1) + (At[a] + At[b]) / np.pi
|
| 768 |
+
return -(1 + eps_r) * EPS0_FF_UM * At[a] * At[b] / (2 * np.pi * d2 ** 1.5)
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def _ground_segments(G):
|
| 772 |
+
"""Edge segments (m, 2, 2) of the ground metal and an STRtree over them."""
|
| 773 |
+
_, S, _ = P._segments([G])
|
| 774 |
+
return S, shapely.STRtree(shapely.linestrings(S))
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def _metal_length(A: np.ndarray, B: np.ndarray, S: np.ndarray, tree) -> np.ndarray:
|
| 778 |
+
"""Length of ground metal crossed by each segment A[k] -> B[k] (endpoints off the metal): crossings with the ground
|
| 779 |
+
edges (STRtree) sorted along the segment, alternate inside / outside intervals summed."""
|
| 780 |
+
out = np.zeros(len(A))
|
| 781 |
+
if not len(A):
|
| 782 |
+
return out
|
| 783 |
+
li, gi = tree.query(shapely.linestrings(np.stack([A, B], 1)), predicate="intersects")
|
| 784 |
+
if not len(li):
|
| 785 |
+
return out
|
| 786 |
+
p, r = A[li], B[li] - A[li]
|
| 787 |
+
q, s = S[gi, 0], S[gi, 1] - S[gi, 0]
|
| 788 |
+
den = r[:, 0] * s[:, 1] - r[:, 1] * s[:, 0]
|
| 789 |
+
ok = np.abs(den) > 1e-12
|
| 790 |
+
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)
|
| 791 |
+
order = np.lexsort((t, li))
|
| 792 |
+
li, t = li[order], t[order]
|
| 793 |
+
start = np.r_[0, np.nonzero(np.diff(li))[0] + 1]
|
| 794 |
+
n = np.diff(np.r_[start, len(li)])
|
| 795 |
+
rank = np.arange(len(li)) - np.repeat(start, n)
|
| 796 |
+
keep = rank < np.repeat(n // 2 * 2, n)
|
| 797 |
+
sgn = np.where(rank % 2 == 1, 1.0, -1.0)
|
| 798 |
+
out += np.bincount(li[keep], weights=(sgn * t)[keep], minlength=len(A))
|
| 799 |
+
return out * np.sqrt(((B - A) ** 2).sum(1))
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
def _cps_m(d, w1, w2):
|
| 803 |
+
"""Coplanar-strip modulus (as `blocks.edge_features`; w = inf for the ground)."""
|
| 804 |
+
if np.isinf(w1) or np.isinf(w2):
|
| 805 |
+
wf = w2 if np.isinf(w1) else w1
|
| 806 |
+
return d / (d + wf)
|
| 807 |
+
return d * (d + w1 + w2) / ((d + w1) * (d + w2))
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
_FORM: dict = {} # samples and trees of the running formula_prior call, inherited by forked row workers
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def _formula_row(i: int) -> tuple:
|
| 814 |
+
"""Row i of the directed sums I[i, j] of `formula_prior` (j = the near metals of i; ground last term included)."""
|
| 815 |
+
F = _FORM
|
| 816 |
+
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"]
|
| 817 |
+
I = np.zeros(near.shape[0])
|
| 818 |
+
dmin_other, dG = np.full(len(pts[i]), np.inf), None
|
| 819 |
+
for j in np.nonzero(near[i])[0]:
|
| 820 |
+
d, idx = kd[j].query(pts[i], distance_upper_bound=R if j > 0 else np.inf)
|
| 821 |
+
ok = np.isfinite(d)
|
| 822 |
+
if j > 0:
|
| 823 |
+
dmin_other = np.minimum(dmin_other, d)
|
| 824 |
+
else:
|
| 825 |
+
dG = d
|
| 826 |
+
if not ok.any():
|
| 827 |
+
continue
|
| 828 |
+
dd = np.maximum(d[ok], 0.05)
|
| 829 |
+
if j == 0:
|
| 830 |
+
S = np.ones(ok.sum())
|
| 831 |
+
else:
|
| 832 |
+
sel = np.arange(0, ok.sum(), every)
|
| 833 |
+
A = pts[i][ok][sel]
|
| 834 |
+
lg = _metal_length(A, pts[j][idx[ok][sel]], F["SG"], F["gtree"])
|
| 835 |
+
S = np.exp(-lg / (dd[sel] + min(width[i], width[j])))[np.arange(ok.sum()) // every]
|
| 836 |
+
I[j] = k * np.sum(step_um * _kratio(_cps_m(dd, width[i], width[j])) * S)
|
| 837 |
+
if dG is not None:
|
| 838 |
+
share = float(np.mean(dG <= dmin_other))
|
| 839 |
+
I[0] += 8 * EPS0_FF_UM * (1 + F["eps_r"]) / 2 * np.sqrt(F["area"][i] / np.pi) * share
|
| 840 |
+
return i, I
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
def formula_prior(G, conds: list, eps_r: float = 11.45, step_um: float = FORMULA_STEP_UM, R_gaps: float = FORMULA_R_GAPS,
|
| 844 |
+
pairs=None, gap: float | None = None, screen_um: float = FORMULA_SCREEN_UM, workers: int = 1,
|
| 845 |
+
max_core: int = 8) -> tuple:
|
| 846 |
+
"""Closed-form edge-coupling prior (PRIOR_SCHEME.md section 12, F): (C (N+1, N+1) fF Maxwell, info). No mesh, no solve.
|
| 847 |
+
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
|
| 848 |
+
samples p of i (modulus of the local widths 2 A / P and the distance to the nearest sample of j, within R_gaps
|
| 849 |
+
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
|
| 850 |
+
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
|
| 851 |
+
ground). Pairs farther than R_gaps: the same form on the bounding boxes (facing length (P_i + P_j) / 2, distance of
|
| 852 |
+
the boxes, l_G = ground area fraction x distance). Self terms: row sums / (1 - ROW_SUM_EPS). pairs (k, 2) of metal
|
| 853 |
+
indices (0 = ground): only those mutual entries (the rest 0, no self terms). More than max_core conductors: the
|
| 854 |
+
quadrature step is at least gap / 4 and the screening spacing at least one gap (numerically equivalent: median
|
| 855 |
+
0.02 %, max 1.2 % on the grids vs 0.25 um), rows on `workers` forked processes."""
|
| 856 |
+
t0 = time.perf_counter()
|
| 857 |
+
metals = [G] + list(conds)
|
| 858 |
+
N = len(metals)
|
| 859 |
+
gap = gap_of(metals) if gap is None else gap
|
| 860 |
+
if len(conds) > max_core:
|
| 861 |
+
step_um, screen_um = max(step_um, gap / 4), max(screen_um, gap)
|
| 862 |
+
R = R_gaps * gap
|
| 863 |
+
k = EPS0_FF_UM * (1 + eps_r) / 2
|
| 864 |
+
want = np.zeros((N, N), bool)
|
| 865 |
+
if pairs is None:
|
| 866 |
+
want[np.triu_indices(N, 1)] = True
|
| 867 |
+
else:
|
| 868 |
+
pairs = np.sort(np.asarray(pairs, int).reshape(-1, 2), 1)
|
| 869 |
+
want[pairs[:, 0], pairs[:, 1]] = True
|
| 870 |
+
area = np.array([g.area for g in metals])
|
| 871 |
+
perim = np.array([g.length for g in metals])
|
| 872 |
+
width = np.r_[np.inf, 2 * area[1:] / perim[1:]]
|
| 873 |
+
tree = shapely.STRtree(list(conds))
|
| 874 |
+
near = np.zeros((N, N), bool)
|
| 875 |
+
a, b = tree.query(list(conds), predicate="dwithin", distance=R)
|
| 876 |
+
near[a + 1, b + 1] = True
|
| 877 |
+
near[0, 1:] = near[1:, 0] = True
|
| 878 |
+
np.fill_diagonal(near, False)
|
| 879 |
+
near &= want | want.T
|
| 880 |
+
gx0, gy0, gx1, gy1 = G.bounds
|
| 881 |
+
need = np.unique(np.nonzero(near)[0])
|
| 882 |
+
pts, kd = {}, {}
|
| 883 |
+
for i in np.unique(np.r_[need, np.nonzero(near.any(0))[0]]):
|
| 884 |
+
p = sample_boundary(metals[i], step_um)
|
| 885 |
+
if i == 0: # ground edge = boundary of the etched region (not the chip outline)
|
| 886 |
+
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)
|
| 887 |
+
p = p[~on]
|
| 888 |
+
pts[i] = p
|
| 889 |
+
kd[i] = cKDTree(p)
|
| 890 |
+
SG, gtree = _ground_segments(G)
|
| 891 |
+
_FORM.clear()
|
| 892 |
+
_FORM.update(pts=pts, kd=kd, near=near, width=width, area=area, R=R, k=k, step=step_um, eps_r=eps_r,
|
| 893 |
+
every=max(1, int(round(screen_um / step_um))), SG=SG, gtree=gtree)
|
| 894 |
+
rows = [i for i in need if i > 0]
|
| 895 |
+
if workers > 1 and len(rows) > 1:
|
| 896 |
+
with ProcessPoolExecutor(min(workers, len(rows)), mp_context=get_context("fork")) as ex:
|
| 897 |
+
res = list(ex.map(_formula_row, rows, chunksize=max(1, len(rows) // (4 * workers))))
|
| 898 |
+
else:
|
| 899 |
+
res = [_formula_row(i) for i in rows]
|
| 900 |
+
_FORM.clear()
|
| 901 |
+
I = np.zeros((N, N))
|
| 902 |
+
for i, row in res:
|
| 903 |
+
I[i] = row
|
| 904 |
+
C = np.zeros((N, N))
|
| 905 |
+
iu = np.nonzero(np.triu(near, 1))
|
| 906 |
+
gnd = iu[0] == 0
|
| 907 |
+
C[iu] = np.where(gnd, I[iu[1], iu[0]], 0.5 * (I[iu] + I[iu[1], iu[0]]))
|
| 908 |
+
fa, fb = np.nonzero(np.triu(want & ~near & ~near.T, 1))
|
| 909 |
+
if len(fa):
|
| 910 |
+
bb = shapely.bounds(np.array(metals, dtype=object))
|
| 911 |
+
dx = np.maximum(0.0, np.maximum(bb[fa, 0] - bb[fb, 2], bb[fb, 0] - bb[fa, 2]))
|
| 912 |
+
dy = np.maximum(0.0, np.maximum(bb[fa, 1] - bb[fb, 3], bb[fb, 1] - bb[fa, 3]))
|
| 913 |
+
dd = np.maximum(np.hypot(dx, dy), 0.05)
|
| 914 |
+
fG = G.area / max(shapely.box(*G.bounds).area, 1e-12)
|
| 915 |
+
w1, w2 = width[fa], width[fb]
|
| 916 |
+
m = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
|
| 917 |
+
S = np.exp(-fG * dd / (dd + np.minimum(w1, w2)))
|
| 918 |
+
C[fa, fb] = k * 0.5 * (perim[fa] + perim[fb]) * _kratio(m) * S
|
| 919 |
+
C = -(C + C.T)
|
| 920 |
+
info = {"n_sampled_pairs": int(len(iu[0])), "n_bbox_pairs": int(len(fa)), "min_gap_um": gap, "step_um": step_um,
|
| 921 |
+
"samples": int(sum(len(p) for p in pts.values()))}
|
| 922 |
+
if pairs is None:
|
| 923 |
+
np.fill_diagonal(C, np.abs(C).sum(1) / (1 - ROW_SUM_EPS))
|
| 924 |
+
info["total_s"] = time.perf_counter() - t0
|
| 925 |
+
return C, info
|
src/squadds/ml/capacitance/_core/_tlsq/embed/fastprior_loc.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local-gap (graded) lite micro-MoM prior: PRIOR_SCHEME.md Amendment MESH (2026-10-11).
|
| 2 |
+
|
| 3 |
+
The lite prior meshes every metal edge at h = gap / ppg with gap the layout's global smallest conductor gap. A sliver
|
| 4 |
+
(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
|
| 5 |
+
floor at every ppg (the resolution knob is dead). Here the panel size is set by the LOCAL gap of each quadtree cell:
|
| 6 |
+
|
| 7 |
+
h(cell) = clamp(local_gap(cell) / ppg, h_floor, H), H = G_ref / ppg, h_floor = size / FLOOR_DIV
|
| 8 |
+
|
| 9 |
+
local_gap(cell) = min over the metals k the cell touches and the other metals j of distance(cell & metal_k, metal_j)
|
| 10 |
+
(the gap of the edge stretch inside the cell, never smaller than the global smallest gap); G_ref = the smallest pair
|
| 11 |
+
gap among conductor pairs whose gap is >= SLIVER_UM ("sliver" pairs only refine their own neighbourhood). Same lattice
|
| 12 |
+
(H 2^-k, anchored to the signal bounding box), exact cut panels, strip merge bounded by each panel's own size, slab
|
| 13 |
+
kernel and exact near field as `fastprior.micro_mom`. A layout without a sliver pair is passed to `fastprior.micro_mom`
|
| 14 |
+
unchanged (bit-identical prior). Resolution descriptor: proxy_min_gap_um = G_ref, proxy_h_min_um = H (log ppg).
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import time
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import shapely
|
| 23 |
+
|
| 24 |
+
from . import fastprior as F
|
| 25 |
+
from . import proxy as P
|
| 26 |
+
|
| 27 |
+
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)
|
| 28 |
+
FLOOR_DIV = 4096 # h_floor = layout size / FLOOR_DIV (the existing floor)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def ref_gap(metals: list, sliver: float = SLIVER_UM) -> tuple:
|
| 32 |
+
"""(G_ref, smallest gap, layout size, number of sliver pairs). G_ref = smallest pair gap >= sliver; when every pair
|
| 33 |
+
is a sliver, the edge-length-weighted 5th percentile of the local gap of the boundary (0.25 um samples)."""
|
| 34 |
+
gmin, size = F._gap_size(metals)
|
| 35 |
+
n = len(metals)
|
| 36 |
+
d = np.array([shapely.distance(metals[i], metals[j]) for i in range(n) for j in range(i + 1, n)])
|
| 37 |
+
ok = d >= sliver
|
| 38 |
+
if ok.any():
|
| 39 |
+
return float(d[ok].min()), float(gmin), float(size), int((~ok).sum())
|
| 40 |
+
lg = []
|
| 41 |
+
for i, g in enumerate(metals):
|
| 42 |
+
others = shapely.union_all([metals[k] for k in range(n) if k != i])
|
| 43 |
+
for ln in getattr(g.boundary, "geoms", [g.boundary]):
|
| 44 |
+
pts = shapely.line_interpolate_point(ln, np.arange(0, ln.length, 0.25))
|
| 45 |
+
lg.append(shapely.distance(pts, others))
|
| 46 |
+
return float(max(np.percentile(np.concatenate(lg), 5), gmin)), float(gmin), float(size), int((~ok).sum())
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _local_gap(metals: list, boxes, hit, inn, pcs, sel) -> np.ndarray:
|
| 50 |
+
"""local_gap of the cells sel (indices): min over touched metals k and other metals j of distance(cell & k, j)."""
|
| 51 |
+
lg = np.full(len(sel), np.inf)
|
| 52 |
+
m = len(metals)
|
| 53 |
+
for k in range(m):
|
| 54 |
+
t = hit[k, sel]
|
| 55 |
+
if not t.any():
|
| 56 |
+
continue
|
| 57 |
+
ix = sel[t]
|
| 58 |
+
geo = np.where(inn[k, ix], boxes[ix], pcs[k][ix])
|
| 59 |
+
bad = np.array([g is None for g in geo])
|
| 60 |
+
geo[bad] = boxes[ix][bad]
|
| 61 |
+
dk = np.full(len(ix), np.inf)
|
| 62 |
+
for j in range(m):
|
| 63 |
+
if j != k:
|
| 64 |
+
dk = np.minimum(dk, shapely.distance(geo, metals[j]))
|
| 65 |
+
lg[t] = np.minimum(lg[t], dk)
|
| 66 |
+
return lg
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def anchored_cells_local(metals: list, H: float, h_floor: float, ppg: float, grade: float = 2.0, majority: bool = False):
|
| 70 |
+
"""`proxy.anchored_cells` on the lattice of H (anchored to the signal bounding box) with the finest level of every
|
| 71 |
+
cell set by its local gap: a cell (cut or whole) is final once h <= clamp(local_gap / ppg, h_floor, H). Returns
|
| 72 |
+
centres (n, 2), sizes (n, 2), owner (n,)."""
|
| 73 |
+
edges = shapely.union_all([g.boundary for g in metals])
|
| 74 |
+
sig = metals[1:] if len(metals) > 1 else metals
|
| 75 |
+
ax, ay = shapely.union_all(sig).bounds[:2]
|
| 76 |
+
X0, Y0, X1, Y1 = shapely.union_all(metals).bounds
|
| 77 |
+
span = max(X1 - X0, Y1 - Y0)
|
| 78 |
+
K = max(0, int(np.ceil(np.log2(max(span / 16, H) / H))))
|
| 79 |
+
h0 = H * 2**K
|
| 80 |
+
ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0))
|
| 81 |
+
ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0))
|
| 82 |
+
gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1))
|
| 83 |
+
xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0)
|
| 84 |
+
gq = P._Geoms(list(metals) + [edges])
|
| 85 |
+
tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool)
|
| 86 |
+
out_c, out_h, out_o = [], [], []
|
| 87 |
+
while len(xs):
|
| 88 |
+
boxes = shapely.box(xs, ys, xs + h, ys + h)
|
| 89 |
+
cov, hit, inn, pcs = P._cover(gq, boxes, h, tst, inn)
|
| 90 |
+
keep = cov.sum(0) > 1e-3
|
| 91 |
+
xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep]
|
| 92 |
+
pcs = [p[keep] for p in pcs]
|
| 93 |
+
cx, cy = xs + h / 2, ys + h / 2
|
| 94 |
+
full = cov.max(0) > 0.999
|
| 95 |
+
cand = h <= H * 1.0001
|
| 96 |
+
last = cand & (h <= h_floor * 1.0001)
|
| 97 |
+
need = np.nonzero(cand & ~last)[0]
|
| 98 |
+
if len(need):
|
| 99 |
+
tgt = np.clip(_local_gap(metals, boxes, hit, inn, pcs, need) / ppg, h_floor, H)
|
| 100 |
+
last[need] = h[need] <= tgt * 1.0001
|
| 101 |
+
d = np.full(len(xs), np.inf)
|
| 102 |
+
far = full & ~last
|
| 103 |
+
d[far] = P._distance(gq, len(metals), boxes[far])
|
| 104 |
+
leaf = full & (last | (h <= grade * d + 1e-12))
|
| 105 |
+
out_c.append(np.stack([cx[leaf], cy[leaf]], 1))
|
| 106 |
+
out_h.append(np.stack([h[leaf], h[leaf]], 1))
|
| 107 |
+
out_o.append(cov[:, leaf].argmax(0))
|
| 108 |
+
cut = last & ~leaf
|
| 109 |
+
if majority and cut.any():
|
| 110 |
+
take = cut & (cov.max(0) >= 0.5)
|
| 111 |
+
out_c.append(np.stack([cx[take], cy[take]], 1))
|
| 112 |
+
out_h.append(np.stack([h[take], h[take]], 1))
|
| 113 |
+
out_o.append(cov[:, take].argmax(0))
|
| 114 |
+
cut = cut & False
|
| 115 |
+
if cut.any():
|
| 116 |
+
gs = gq.get()
|
| 117 |
+
for k, g in enumerate(gs[:len(metals)]):
|
| 118 |
+
shapely.prepare(g)
|
| 119 |
+
sel = np.nonzero(cut & (cov[k] > 1e-3))[0]
|
| 120 |
+
if not len(sel):
|
| 121 |
+
continue
|
| 122 |
+
pcs_k = pcs[k][sel]
|
| 123 |
+
bb = shapely.bounds(pcs_k)
|
| 124 |
+
cen = shapely.get_coordinates(shapely.centroid(pcs_k))
|
| 125 |
+
inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1])
|
| 126 |
+
if not inside.all():
|
| 127 |
+
cen[~inside] = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside]))
|
| 128 |
+
out_c.append(cen)
|
| 129 |
+
out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6))
|
| 130 |
+
out_o.append(np.full(len(sel), k))
|
| 131 |
+
gq.put(gs)
|
| 132 |
+
split = ~leaf & ~last
|
| 133 |
+
hs = h[split] / 2
|
| 134 |
+
xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs])
|
| 135 |
+
ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs])
|
| 136 |
+
h = np.concatenate([hs] * 4)
|
| 137 |
+
tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4)
|
| 138 |
+
return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def mesh_local(metals: list, H: float, h_floor: float, ppg: float, majority: bool = False) -> tuple:
|
| 142 |
+
"""Strip-merged local mesh (strip length <= 16 x the panel's own size and <= the distance to the nearest vertex).
|
| 143 |
+
Returns (centres, sizes, owners, raw count)."""
|
| 144 |
+
raw = anchored_cells_local(metals, H, h_floor, ppg, majority=majority)
|
| 145 |
+
c, wh, o = F.strip_merge(*raw, metals, h_floor)
|
| 146 |
+
return c, wh, o, len(raw[0])
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _solve(metals: list, H: float, h_floor: float, ppg: float, eps_r: float) -> tuple:
|
| 150 |
+
"""`fastprior._window_solve(all_rhs=True)` on the local mesh: rejected solves (not PD, a metal without a panel, a
|
| 151 |
+
non-negative mutual entry) refine (H, h_floor) / 2 up to LITE_REFINE times, then majority-owned cut cells."""
|
| 152 |
+
t_mesh = t_sol = 0.0
|
| 153 |
+
cols = np.arange(len(metals))
|
| 154 |
+
refined, majority = 0, False
|
| 155 |
+
while True:
|
| 156 |
+
t = time.perf_counter()
|
| 157 |
+
c, wh, o, n_raw = mesh_local(metals, H, h_floor, ppg, majority)
|
| 158 |
+
t_mesh += time.perf_counter() - t
|
| 159 |
+
t = time.perf_counter()
|
| 160 |
+
try:
|
| 161 |
+
if len(c) <= P.DENSE_MAX:
|
| 162 |
+
A = P._assemble(c, wh, P.rect_self(wh[:, 0], wh[:, 1]), eps_r, P.rect_potential)
|
| 163 |
+
Q = P._chol_solve(A, (o[:, None] == cols[None, :]).astype(float))
|
| 164 |
+
del A
|
| 165 |
+
else:
|
| 166 |
+
Q = P.mom_solve_fast(c, wh, o, len(metals), eps_r)
|
| 167 |
+
R = np.stack([Q[o == a].sum(0) for a in range(len(metals))], 1)
|
| 168 |
+
off = ~np.eye(len(metals), dtype=bool)
|
| 169 |
+
ok = bool(np.all(np.bincount(o, minlength=len(metals)) > 0) and np.all(R[off] < 0))
|
| 170 |
+
except np.linalg.LinAlgError:
|
| 171 |
+
ok = False
|
| 172 |
+
t_sol += time.perf_counter() - t
|
| 173 |
+
if ok or majority:
|
| 174 |
+
break
|
| 175 |
+
if refined < F.LITE_REFINE:
|
| 176 |
+
H, h_floor, refined = H / 2, h_floor / 2, refined + 1
|
| 177 |
+
else:
|
| 178 |
+
majority = True
|
| 179 |
+
return R, {"H_um": H, "h_floor_um": h_floor, "h_min_um": float(wh.min()), "panels": len(c), "raw": n_raw,
|
| 180 |
+
"refined": refined, "majority": majority, "mesh_s": t_mesh, "solve_s": t_sol}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def micro_mom_loc(G, conds: list, eps_r: float = 11.45, ppg: float = 3.0, sliver: float = SLIVER_UM,
|
| 184 |
+
floor_div: float = FLOOR_DIV, canonical: bool = True) -> tuple:
|
| 185 |
+
"""Local-gap lite prior of a <= 8-conductor layout: (C (N+1, N+1) fF, far_mask (all False), info). Layouts without a
|
| 186 |
+
sliver pair: `fastprior.micro_mom(budget=inf, cells_per_gap=ppg)` (the existing liteppg prior, bit-identical).
|
| 187 |
+
Mean over the canonical frames of symmetric layouts, returned in the input order (as micro_mom)."""
|
| 188 |
+
t_all = time.perf_counter()
|
| 189 |
+
metals = [G] + list(conds)
|
| 190 |
+
gref, gmin, size, n_sl = ref_gap(metals, sliver)
|
| 191 |
+
if n_sl == 0 or len(conds) > 8: # no sliver (or windows: out of scope) -> the existing prior
|
| 192 |
+
C, far, info = F.micro_mom(G, conds, eps_r, budget=np.inf, cells_per_gap=ppg)
|
| 193 |
+
info.update(local=False, G_ref_um=float(info["min_gap_um"]), H_um=float(min(info["h_um"])), n_sliver_pairs=n_sl)
|
| 194 |
+
return C, far, info
|
| 195 |
+
runs = []
|
| 196 |
+
frames = F.canonical_frames(G, conds) if canonical else [(G, list(conds), np.arange(len(conds)))]
|
| 197 |
+
for Gc, cc, order in frames:
|
| 198 |
+
R, wi = _solve([Gc] + list(cc), gref / ppg, size / floor_div, ppg, eps_r)
|
| 199 |
+
C = 0.5 * (R + R.T)
|
| 200 |
+
inv = np.r_[0, np.argsort(order) + 1]
|
| 201 |
+
runs.append((C[np.ix_(inv, inv)], wi))
|
| 202 |
+
C = sum(r[0] for r in runs) / len(runs)
|
| 203 |
+
wi = runs[0][1]
|
| 204 |
+
info = {"local": True, "n_windows": 1, "n_frames": len(runs), "min_gap_um": gref, "G_ref_um": gref, "gmin_um": gmin,
|
| 205 |
+
"n_sliver_pairs": n_sl, "H_um": wi["H_um"], "h_floor_um": wi["h_floor_um"], "h_um": [wi["H_um"]],
|
| 206 |
+
"h_min_um": wi["h_min_um"], "panels": [wi["panels"]], "panels_per_gap": [gref / wi["H_um"]],
|
| 207 |
+
"majority": [wi["majority"]], "refined": [wi["refined"]],
|
| 208 |
+
"mesh_s": sum(r[1]["mesh_s"] for r in runs), "solve_s": sum(r[1]["solve_s"] for r in runs)}
|
| 209 |
+
info["total_s"] = time.perf_counter() - t_all
|
| 210 |
+
return C, np.zeros(C.shape, bool), info
|
src/squadds/ml/capacitance/_core/_tlsq/embed/proxy.py
ADDED
|
@@ -0,0 +1,944 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cheap physics proxy: thin-film method-of-moments capacitance on the metal masks.
|
| 2 |
+
|
| 3 |
+
Planar conductors of negligible thickness on a dielectric half-space: the quasi-static Green's function is
|
| 4 |
+
1 / (4 pi eps0 eps_eff r) with eps_eff = (eps_r + 1) / 2. The metal is discretised into square cells (pulse basis,
|
| 5 |
+
point matching); a uniformly charged square of side a has self-potential q / (4 pi eps0 eps_eff) * 4 ln(1 + sqrt 2) / a.
|
| 6 |
+
Solving P q = v for each conductor at 1 V (others at 0 V) gives the full Maxwell capacitance matrix, including
|
| 7 |
+
shielding and other non-local effects that local descriptors cannot represent. Truncation: the ground plane is
|
| 8 |
+
represented only inside the design window (a proxy, not a replacement for Q3D).
|
| 9 |
+
|
| 10 |
+
v2 (`mom_capacitance_gds`) works on the exact GDS polygons with the whole ground plane and an adaptive quadtree mesh
|
| 11 |
+
(cells no larger than `grade` x their distance to a metal edge, edge cells down to ~1/3 of the smallest gap). On the
|
| 12 |
+
gallery designs it reaches 5-6 % (NCAP, star) and 12 % (concentric) median error with no training, vs 14-32 % for v1.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import queue
|
| 19 |
+
import threading
|
| 20 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 21 |
+
from functools import partial
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import shapely
|
| 25 |
+
from scipy.linalg import cho_factor, cho_solve
|
| 26 |
+
from scipy.spatial import cKDTree
|
| 27 |
+
|
| 28 |
+
EPS0_FF_PER_UM = 8.8541878128e-3
|
| 29 |
+
SELF = 4 * np.log(1 + np.sqrt(2))
|
| 30 |
+
NUM_THREADS = 0 # threads of the mesh / assembly pool and of the concurrent v3-rich solves; 0 = torch.get_num_threads()
|
| 31 |
+
_LOCK = threading.Lock()
|
| 32 |
+
_POOL: list = [] # [(threads, executor)]
|
| 33 |
+
if hasattr(os, "register_at_fork"):
|
| 34 |
+
os.register_at_fork(after_in_child=_POOL.clear) # a forked worker must not reuse the parent's pool threads
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _nthreads() -> int:
|
| 38 |
+
if NUM_THREADS:
|
| 39 |
+
return NUM_THREADS
|
| 40 |
+
try:
|
| 41 |
+
import torch
|
| 42 |
+
except ImportError:
|
| 43 |
+
return 1
|
| 44 |
+
return torch.get_num_threads()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _run(tasks: list) -> list:
|
| 48 |
+
"""Results of the zero-argument callables in order, on the thread pool when more than one thread is allowed (numpy
|
| 49 |
+
ufuncs and shapely's vectorised functions release the GIL). Tasks never wait on other pool tasks."""
|
| 50 |
+
n = _nthreads()
|
| 51 |
+
if n < 2 or len(tasks) < 2:
|
| 52 |
+
return [t() for t in tasks]
|
| 53 |
+
with _LOCK:
|
| 54 |
+
if not _POOL or _POOL[0][0] != n:
|
| 55 |
+
_POOL[:] = [(n, ThreadPoolExecutor(n, thread_name_prefix="tlsq-mom"))]
|
| 56 |
+
pool = _POOL[0][1]
|
| 57 |
+
return list(pool.map(lambda t: t(), tasks))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _spans(n: int, size: int) -> list:
|
| 61 |
+
return [(a, min(a + size, n)) for a in range(0, n, size)]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class _Geoms:
|
| 65 |
+
"""Private copies of geometries (exact WKB round trip) handed out to one pool task at a time and made on demand: GEOS
|
| 66 |
+
prepared geometries keep mutable search state and must not be shared between threads (nor with a concurrent solve)."""
|
| 67 |
+
|
| 68 |
+
def __init__(self, geoms: list):
|
| 69 |
+
self.wkb, self.free = shapely.to_wkb(geoms), queue.SimpleQueue()
|
| 70 |
+
|
| 71 |
+
def get(self) -> list:
|
| 72 |
+
try:
|
| 73 |
+
return self.free.get_nowait()
|
| 74 |
+
except queue.Empty:
|
| 75 |
+
return list(shapely.from_wkb(self.wkb))
|
| 76 |
+
|
| 77 |
+
def put(self, gs: list) -> None:
|
| 78 |
+
self.free.put(gs)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _cover(gq, boxes, h, tst, inn):
|
| 82 |
+
"""Coverage area(box & metal) / h^2 of every box by every metal (m, n), evaluated exactly only where a box straddles a
|
| 83 |
+
metal: a box properly inside a metal covers 1 and a box disjoint from it 0 (same decisions as the exact areas). tst
|
| 84 |
+
(m, n): metals the box can touch (its parent did); inn (m, n): metals the box lies properly inside (from its parent).
|
| 85 |
+
Returns cov, hit (box intersects the metal), inn, and per metal the pieces box & metal where they were computed."""
|
| 86 |
+
m, n = tst.shape
|
| 87 |
+
cov, hit, inn = inn.astype(float), inn.copy(), inn.copy()
|
| 88 |
+
pcs = [np.empty(n, dtype=object) for _ in range(m)]
|
| 89 |
+
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)]
|
| 90 |
+
|
| 91 |
+
def task(k, ix):
|
| 92 |
+
gs = gq.get()
|
| 93 |
+
try:
|
| 94 |
+
g = gs[k]
|
| 95 |
+
shapely.prepare(g)
|
| 96 |
+
b = boxes[ix]
|
| 97 |
+
ht = shapely.intersects(g, b)
|
| 98 |
+
it = shapely.contains_properly(g, b)
|
| 99 |
+
p = shapely.intersection(b[ht & ~it], g)
|
| 100 |
+
return ht, it, p, shapely.area(p)
|
| 101 |
+
finally:
|
| 102 |
+
gq.put(gs)
|
| 103 |
+
|
| 104 |
+
for (k, ix), (ht, it, p, a) in zip(work, _run([partial(task, k, ix) for k, ix in work])):
|
| 105 |
+
hit[k, ix], inn[k, ix] = ht, it
|
| 106 |
+
cov[k, ix[it]] = 1.0
|
| 107 |
+
s = ix[ht & ~it]
|
| 108 |
+
cov[k, s] = a / h[s] ** 2
|
| 109 |
+
pcs[k][s] = p
|
| 110 |
+
return cov, hit, inn, pcs
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _distance(gq, j: int, geoms) -> np.ndarray:
|
| 114 |
+
"""shapely.distance(geoms, geometry j of the queue), in chunks on the pool."""
|
| 115 |
+
def task(a, b):
|
| 116 |
+
gs = gq.get()
|
| 117 |
+
try:
|
| 118 |
+
return shapely.distance(geoms[a:b], gs[j])
|
| 119 |
+
finally:
|
| 120 |
+
gq.put(gs)
|
| 121 |
+
return np.concatenate([np.zeros(0)] + _run([partial(task, a, b) for a, b in _spans(len(geoms), 256)]))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def mom_capacitance(masks: np.ndarray, window_um: float, eps_r: float = 11.45, cells: int = 64) -> np.ndarray:
|
| 127 |
+
"""masks: (n_cond, R, R) coverage in [0, 1] (channel 0 = ground). Returns the (n_cond, n_cond) Maxwell C in fF."""
|
| 128 |
+
nc, R, _ = masks.shape
|
| 129 |
+
f = R // cells
|
| 130 |
+
cov = masks.reshape(nc, cells, f, cells, f).mean((2, 4)) # coverage per coarse cell
|
| 131 |
+
owner = np.where(cov.max(0) >= 0.5, cov.argmax(0), -1)
|
| 132 |
+
ii, jj = np.nonzero(owner >= 0)
|
| 133 |
+
lab = owner[ii, jj]
|
| 134 |
+
a = window_um / cells
|
| 135 |
+
xy = np.stack([(jj + 0.5) * a, (ii + 0.5) * a], 1)
|
| 136 |
+
d = np.sqrt(((xy[:, None, :] - xy[None, :, :]) ** 2).sum(-1))
|
| 137 |
+
np.fill_diagonal(d, 1.0)
|
| 138 |
+
P = 1.0 / d
|
| 139 |
+
np.fill_diagonal(P, SELF / a)
|
| 140 |
+
P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2
|
| 141 |
+
B = (lab[:, None] == np.arange(nc)[None, :]).astype(float) # conductor b at 1 V
|
| 142 |
+
Q = cho_solve(cho_factor(P, lower=True), B)
|
| 143 |
+
C = np.stack([Q[lab == a_].sum(0) for a_ in range(nc)]) # C[a, b] = charge on a with b at 1 V
|
| 144 |
+
return 0.5 * (C + C.T)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def quadtree_cells(metals: list, bbox, h0: float, h_min: float, grade: float = 2.0, limit: int | None = None):
|
| 148 |
+
"""Square cells covering the metal polygons: a cell is kept whole when it lies inside one conductor and is no larger
|
| 149 |
+
than `grade` x its distance to the nearest metal edge; edge cells are split down to h_min, where they go to the
|
| 150 |
+
conductor covering >= 50 % of them. Returns centres (n, 2), sides (n,), owner (n,); None once more than `limit` cells."""
|
| 151 |
+
edges = shapely.union_all([g.boundary for g in metals])
|
| 152 |
+
x0, y0, x1, y1 = bbox
|
| 153 |
+
nx, ny = int(np.ceil((x1 - x0) / h0)), int(np.ceil((y1 - y0) / h0))
|
| 154 |
+
gx, gy = np.meshgrid(x0 + h0 * np.arange(nx), y0 + h0 * np.arange(ny))
|
| 155 |
+
xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0)
|
| 156 |
+
gq = _Geoms(list(metals) + [edges])
|
| 157 |
+
tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool)
|
| 158 |
+
out_c, out_h, out_o, count = [], [], [], 0
|
| 159 |
+
while len(xs):
|
| 160 |
+
boxes = shapely.box(xs, ys, xs + h, ys + h)
|
| 161 |
+
cov, hit, inn, _ = _cover(gq, boxes, h, tst, inn)
|
| 162 |
+
keep = cov.sum(0) > 1e-3
|
| 163 |
+
xs, ys, h, cov, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], hit[:, keep], inn[:, keep]
|
| 164 |
+
cx, cy = xs + h / 2, ys + h / 2
|
| 165 |
+
full = cov.max(0) > 0.999
|
| 166 |
+
d = np.full(len(xs), np.inf) # the edge distance only decides for cells inside one conductor
|
| 167 |
+
d[full] = _distance(gq, len(metals), shapely.points(cx[full], cy[full]))
|
| 168 |
+
leaf = full & (h <= grade * d + 1e-12)
|
| 169 |
+
last = h <= h_min * 1.0001
|
| 170 |
+
take_last = last & ~leaf & (cov.max(0) >= 0.5)
|
| 171 |
+
acc = leaf | take_last
|
| 172 |
+
out_c.append(np.stack([cx[acc], cy[acc]], 1))
|
| 173 |
+
out_h.append(h[acc])
|
| 174 |
+
out_o.append(cov[:, acc].argmax(0))
|
| 175 |
+
count += int(acc.sum())
|
| 176 |
+
if limit is not None and count > limit:
|
| 177 |
+
return None
|
| 178 |
+
split = ~acc & ~last
|
| 179 |
+
hs = h[split] / 2
|
| 180 |
+
xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs])
|
| 181 |
+
ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs])
|
| 182 |
+
h = np.concatenate([hs] * 4)
|
| 183 |
+
tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4)
|
| 184 |
+
return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def anchored_cells(metals: list, h_f: float, grade: float = 2.0, majority: bool = False, limit: int | None = None):
|
| 188 |
+
"""v3 mesh: quadtree on a lattice anchored to the signal conductors, independent of the chip size and position.
|
| 189 |
+
|
| 190 |
+
Finest cells have side h_f; coarse cells are h_f * 2^k on the same lattice (origin = lower-left corner of the
|
| 191 |
+
signal conductors' bounding box), so the cells near the conductors do not change when the ground plane grows,
|
| 192 |
+
shrinks or the layout is translated. A cell is kept whole when it lies inside one conductor and is no larger than
|
| 193 |
+
`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
|
| 194 |
+
polygon boundaries into one panel per metal (no rounding of gaps to the grid).
|
| 195 |
+
Returns centres (n, 2), sizes (n, 2) = (width, height) of each panel, owner (n,); None once the mesh has more
|
| 196 |
+
than `limit` cells."""
|
| 197 |
+
edges = shapely.union_all([g.boundary for g in metals])
|
| 198 |
+
sig = metals[1:] if len(metals) > 1 else metals
|
| 199 |
+
ax, ay = shapely.union_all(sig).bounds[:2]
|
| 200 |
+
X0, Y0, X1, Y1 = shapely.union_all(metals).bounds
|
| 201 |
+
span = max(X1 - X0, Y1 - Y0)
|
| 202 |
+
K = max(0, int(np.ceil(np.log2(max(span / 16, h_f) / h_f))))
|
| 203 |
+
h0 = h_f * 2**K
|
| 204 |
+
ix0, iy0 = int(np.floor((X0 - ax) / h0)), int(np.floor((Y0 - ay) / h0))
|
| 205 |
+
ix1, iy1 = int(np.ceil((X1 - ax) / h0)), int(np.ceil((Y1 - ay) / h0))
|
| 206 |
+
gx, gy = np.meshgrid(ax + h0 * np.arange(ix0, ix1), ay + h0 * np.arange(iy0, iy1))
|
| 207 |
+
xs, ys, h = gx.ravel(), gy.ravel(), np.full(gx.size, h0)
|
| 208 |
+
gq = _Geoms(list(metals) + [edges])
|
| 209 |
+
tst, inn = np.ones((len(metals), len(xs)), bool), np.zeros((len(metals), len(xs)), bool)
|
| 210 |
+
out_c, out_h, out_o, count = [], [], [], 0
|
| 211 |
+
while len(xs):
|
| 212 |
+
boxes = shapely.box(xs, ys, xs + h, ys + h)
|
| 213 |
+
cov, hit, inn, pcs = _cover(gq, boxes, h, tst, inn)
|
| 214 |
+
keep = cov.sum(0) > 1e-3
|
| 215 |
+
xs, ys, h, cov, boxes, hit, inn = xs[keep], ys[keep], h[keep], cov[:, keep], boxes[keep], hit[:, keep], inn[:, keep]
|
| 216 |
+
pcs = [p[keep] for p in pcs]
|
| 217 |
+
cx, cy = xs + h / 2, ys + h / 2
|
| 218 |
+
full = cov.max(0) > 0.999
|
| 219 |
+
last = h <= h_f * 1.0001
|
| 220 |
+
d = np.full(len(xs), np.inf) # the edge distance only decides for whole cells above the finest level
|
| 221 |
+
far = full & ~last
|
| 222 |
+
d[far] = _distance(gq, len(metals), boxes[far])
|
| 223 |
+
leaf = full & (last | (h <= grade * d + 1e-12))
|
| 224 |
+
out_c.append(np.stack([cx[leaf], cy[leaf]], 1))
|
| 225 |
+
out_h.append(np.stack([h[leaf], h[leaf]], 1))
|
| 226 |
+
out_o.append(cov[:, leaf].argmax(0))
|
| 227 |
+
count += int(leaf.sum())
|
| 228 |
+
cut = last & ~leaf
|
| 229 |
+
if majority and cut.any():
|
| 230 |
+
take = cut & (cov.max(0) >= 0.5)
|
| 231 |
+
out_c.append(np.stack([cx[take], cy[take]], 1))
|
| 232 |
+
out_h.append(np.stack([h[take], h[take]], 1))
|
| 233 |
+
out_o.append(cov[:, take].argmax(0))
|
| 234 |
+
count += int(take.sum())
|
| 235 |
+
cut = cut & False
|
| 236 |
+
if cut.any():
|
| 237 |
+
gs = gq.get()
|
| 238 |
+
for k, g in enumerate(gs[:-1]):
|
| 239 |
+
shapely.prepare(g)
|
| 240 |
+
sel = np.nonzero(cut & (cov[k] > 1e-3))[0]
|
| 241 |
+
if not len(sel):
|
| 242 |
+
continue
|
| 243 |
+
pcs_k = pcs[k][sel] # box & metal, computed by _cover (straddling cells only reach this level uncut)
|
| 244 |
+
bb = shapely.bounds(pcs_k)
|
| 245 |
+
cen = shapely.get_coordinates(shapely.centroid(pcs_k))
|
| 246 |
+
inside = shapely.contains_xy(g, cen[:, 0], cen[:, 1])
|
| 247 |
+
if not inside.all():
|
| 248 |
+
rp = shapely.get_coordinates(shapely.point_on_surface(pcs_k[~inside]))
|
| 249 |
+
cen[~inside] = rp
|
| 250 |
+
out_c.append(cen)
|
| 251 |
+
out_h.append(np.maximum(np.stack([bb[:, 2] - bb[:, 0], bb[:, 3] - bb[:, 1]], 1), 1e-6))
|
| 252 |
+
out_o.append(np.full(len(sel), k))
|
| 253 |
+
count += len(sel)
|
| 254 |
+
gq.put(gs)
|
| 255 |
+
if limit is not None and count > limit:
|
| 256 |
+
return None
|
| 257 |
+
split = ~leaf & ~last
|
| 258 |
+
hs = h[split] / 2
|
| 259 |
+
xs = np.concatenate([xs[split], xs[split] + hs, xs[split], xs[split] + hs])
|
| 260 |
+
ys = np.concatenate([ys[split], ys[split], ys[split] + hs, ys[split] + hs])
|
| 261 |
+
h = np.concatenate([hs] * 4)
|
| 262 |
+
tst, inn = np.tile((hit & ~inn)[:, split], 4), np.tile(inn[:, split], 4)
|
| 263 |
+
return np.concatenate(out_c), np.concatenate(out_h), np.concatenate(out_o)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def mom_mesh(metals: list, max_cells: int = 8000, h_min: float | None = None, grade: float = 2.0, cells_per_gap: float = 3.0,
|
| 267 |
+
mesh: str = "v2", offset: tuple = (0.0, 0.0)):
|
| 268 |
+
"""Mesh for the thin-film MoM. mesh="v3": conductor-anchored lattice with exact edge panels
|
| 269 |
+
(`anchored_cells`); mesh="v2" (default, published priors): the original chip-anchored quadtree (reproduces the published v2 priors).
|
| 270 |
+
Returns (centres, sides, owner, h_min)."""
|
| 271 |
+
bbox = shapely.union_all(metals).bounds
|
| 272 |
+
size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 273 |
+
if h_min is None:
|
| 274 |
+
gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
|
| 275 |
+
h_min = max(gap / cells_per_gap, size / 4096)
|
| 276 |
+
if mesh == "v2" and any(offset):
|
| 277 |
+
h0 = size / 16
|
| 278 |
+
bbox = (bbox[0] - offset[0] * h0, bbox[1] - offset[1] * h0, bbox[2] + h0, bbox[3] + h0)
|
| 279 |
+
while True:
|
| 280 |
+
if mesh == "v3":
|
| 281 |
+
r = anchored_cells(metals, h_min, grade, limit=max_cells)
|
| 282 |
+
else:
|
| 283 |
+
r = quadtree_cells(metals, bbox, size / 16, h_min, grade, limit=max_cells)
|
| 284 |
+
if r is not None:
|
| 285 |
+
return (*r, h_min)
|
| 286 |
+
h_min *= 1.5 if mesh == "v2" else 2.0 # v3: stay on the same lattice
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def rect_self(a, b):
|
| 290 |
+
"""Potential at the centre of a uniformly charged a x b rectangle per unit charge, times 4 pi eps (= SELF / a for a
|
| 291 |
+
square)."""
|
| 292 |
+
r = np.sqrt(a**2 + b**2)
|
| 293 |
+
return (2 * a * np.log((b + r) / a) + 2 * b * np.log((a + r) / b)) / (a * b)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _mom_solve_torch(c, h, o, n_metals, eps_r, dev):
|
| 297 |
+
"""Same assembly and Cholesky solve as `mom_solve`, in float64 torch on `dev` (opt-in via TLSQ_MOM_DEVICE)."""
|
| 298 |
+
import torch
|
| 299 |
+
|
| 300 |
+
t = lambda x: torch.as_tensor(np.ascontiguousarray(x), dtype=torch.float64, device=dev) # noqa: E731
|
| 301 |
+
wh = np.stack([h, h], 1) if h.ndim == 1 else h
|
| 302 |
+
C, WH = t(c), t(wh)
|
| 303 |
+
hm = WH.max(1).values
|
| 304 |
+
d = torch.cdist(C, C)
|
| 305 |
+
d.fill_diagonal_(1.0)
|
| 306 |
+
P = 1.0 / d
|
| 307 |
+
near = d < 1.5 * torch.maximum(hm[:, None], hm[None, :])
|
| 308 |
+
near.fill_diagonal_(False)
|
| 309 |
+
del d
|
| 310 |
+
ii, jj = torch.nonzero(near, as_tuple=True)
|
| 311 |
+
del near
|
| 312 |
+
if len(ii):
|
| 313 |
+
off = (torch.arange(3, dtype=torch.float64, device=dev) - 1) / 3
|
| 314 |
+
ox, oy = torch.meshgrid(off, off, indexing="xy")
|
| 315 |
+
sx = C[jj, 0, None] + ox.reshape(-1)[None] * WH[jj, 0, None]
|
| 316 |
+
sy = C[jj, 1, None] + oy.reshape(-1)[None] * WH[jj, 1, None]
|
| 317 |
+
r = torch.sqrt((C[ii, 0, None] - sx) ** 2 + (C[ii, 1, None] - sy) ** 2)
|
| 318 |
+
P[ii, jj] = (1.0 / torch.clamp(r, min=1e-9)).mean(1)
|
| 319 |
+
P = 0.5 * (P + P.T)
|
| 320 |
+
diag = t(rect_self(wh[:, 0], wh[:, 1]) if h.ndim == 2 else SELF / h)
|
| 321 |
+
P.diagonal().copy_(diag)
|
| 322 |
+
P /= 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2
|
| 323 |
+
B = t((o[:, None] == np.arange(n_metals)[None, :]).astype(float))
|
| 324 |
+
L, info = torch.linalg.cholesky_ex(P)
|
| 325 |
+
del P
|
| 326 |
+
if int(info):
|
| 327 |
+
raise np.linalg.LinAlgError(f"{int(info)}-th leading minor not positive definite")
|
| 328 |
+
return torch.cholesky_solve(B, L).cpu().numpy()
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _mom_solve_gpu_slot(c, h, o, n_metals, eps_r):
|
| 332 |
+
"""GPU solve if one of TLSQ_MOM_GPU_SLOTS slots (file locks shared by the worker processes) is free and the solve
|
| 333 |
+
fits; None means: solve on the CPU instead."""
|
| 334 |
+
import fcntl
|
| 335 |
+
import os
|
| 336 |
+
import tempfile
|
| 337 |
+
|
| 338 |
+
import torch
|
| 339 |
+
|
| 340 |
+
slots = int(os.environ.get("TLSQ_MOM_GPU_SLOTS", "3"))
|
| 341 |
+
tag = os.environ.get("SLURM_JOB_ID", "local")
|
| 342 |
+
for k in range(slots):
|
| 343 |
+
f = open(os.path.join(tempfile.gettempdir(), f"tlsq_gpu_{tag}_{k}.lock"), "w")
|
| 344 |
+
try:
|
| 345 |
+
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 346 |
+
except OSError:
|
| 347 |
+
f.close()
|
| 348 |
+
continue
|
| 349 |
+
try:
|
| 350 |
+
return _mom_solve_torch(c, h, o, n_metals, eps_r, os.environ["TLSQ_MOM_DEVICE"])
|
| 351 |
+
except RuntimeError as e: # includes torch.OutOfMemoryError
|
| 352 |
+
if "out of memory" not in str(e).lower():
|
| 353 |
+
raise
|
| 354 |
+
return None
|
| 355 |
+
finally:
|
| 356 |
+
torch.cuda.empty_cache()
|
| 357 |
+
fcntl.flock(f, fcntl.LOCK_UN)
|
| 358 |
+
f.close()
|
| 359 |
+
return None
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def _G(x, y):
|
| 363 |
+
"""Antiderivative of 1 / sqrt(x^2 + y^2) over x and y: x asinh(y / |x|) + y asinh(x / |y|) (0 on the axes)."""
|
| 364 |
+
ax, ay = np.abs(x), np.abs(y)
|
| 365 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 366 |
+
g1 = np.where(ax > 0, x * np.arcsinh(y / np.where(ax > 0, ax, 1.0)), 0.0)
|
| 367 |
+
g2 = np.where(ay > 0, y * np.arcsinh(x / np.where(ay > 0, ay, 1.0)), 0.0)
|
| 368 |
+
return g1 + g2
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def rect_potential(p, cq, wh):
|
| 372 |
+
"""Exact potential (x 4 pi eps) at points p (n, 2) of uniformly charged rectangles (unit total charge) centred at cq
|
| 373 |
+
with sizes wh (n, 2): (1 / (w h)) * integral of 1 / r over the rectangle. Equals rect_self at the centre."""
|
| 374 |
+
x1, x2 = cq[:, 0] - wh[:, 0] / 2 - p[:, 0], cq[:, 0] + wh[:, 0] / 2 - p[:, 0]
|
| 375 |
+
y1, y2 = cq[:, 1] - wh[:, 1] / 2 - p[:, 1], cq[:, 1] + wh[:, 1] / 2 - p[:, 1]
|
| 376 |
+
return (_G(x2, y2) - _G(x1, y2) - _G(x2, y1) + _G(x1, y1)) / (wh[:, 0] * wh[:, 1])
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _mom_solve_exact_near(c, wh, o, n_metals, eps_r):
|
| 380 |
+
"""v3 panels: exact rectangle potential for near pairs (d < 1.5 max side) instead of the 3x3 point average. Used only
|
| 381 |
+
when the 3x3 system is not positive definite (sliver edge panels on long fine combs), so priors that solved before
|
| 382 |
+
are unchanged."""
|
| 383 |
+
P = _assemble(c, wh, rect_self(wh[:, 0], wh[:, 1]), eps_r, rect_potential)
|
| 384 |
+
B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float)
|
| 385 |
+
return _chol_solve(P, B)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def mom_solve(c, h, o, n_metals: int, eps_r: float = 11.45):
|
| 389 |
+
"""mom_solve_quad; for v3 panels (h of shape (n, 2)) a non-positive-definite system is re-solved with the exact
|
| 390 |
+
near field (`_mom_solve_exact_near`)."""
|
| 391 |
+
try:
|
| 392 |
+
return mom_solve_quad(c, h, o, n_metals, eps_r)
|
| 393 |
+
except np.linalg.LinAlgError:
|
| 394 |
+
if h.ndim != 2:
|
| 395 |
+
raise
|
| 396 |
+
print("v3: 3x3 near-field system not positive definite, exact near field", flush=True)
|
| 397 |
+
return _mom_solve_exact_near(c, h, o, n_metals, eps_r)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def mom_solve_quad(c, h, o, n_metals: int, eps_r: float = 11.45):
|
| 401 |
+
"""Point-matching solve on a mesh from `mom_mesh`: cell charges Q (n_cells, n_metals) for each conductor at 1 V.
|
| 402 |
+
h: square sides (n,) or panel (width, height) (n, 2). Set TLSQ_MOM_DEVICE=cuda to assemble and solve on a GPU."""
|
| 403 |
+
import os
|
| 404 |
+
|
| 405 |
+
if os.environ.get("TLSQ_MOM_DEVICE") and SUBSTRATE["model"] == "halfspace": # the torch path has no image correction
|
| 406 |
+
Q = _mom_solve_gpu_slot(c, h, o, n_metals, eps_r)
|
| 407 |
+
if Q is not None:
|
| 408 |
+
return Q
|
| 409 |
+
wh = np.stack([h, h], 1) if h.ndim == 1 else h
|
| 410 |
+
P = _assemble(c, wh, rect_self(wh[:, 0], wh[:, 1]) if h.ndim == 2 else SELF / h, eps_r, _near_quad)
|
| 411 |
+
B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float)
|
| 412 |
+
return _chol_solve(P, B)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def _near_quad(p, cq, wh):
|
| 416 |
+
"""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
|
| 417 |
+
panel (point matching is poor for close, unequal cells)."""
|
| 418 |
+
off = (np.arange(3) - 1) / 3
|
| 419 |
+
ox, oy = np.meshgrid(off, off)
|
| 420 |
+
sx = cq[:, 0, None] + ox.ravel()[None] * wh[:, 0, None]
|
| 421 |
+
sy = cq[:, 1, None] + oy.ravel()[None] * wh[:, 1, None]
|
| 422 |
+
r = np.sqrt((p[:, 0, None] - sx) ** 2 + (p[:, 1, None] - sy) ** 2)
|
| 423 |
+
return (1.0 / np.maximum(r, 1e-9)).mean(1)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def _near_pairs(c, hm):
|
| 427 |
+
"""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
|
| 428 |
+
floating-point test as the dense mask."""
|
| 429 |
+
n = len(c)
|
| 430 |
+
tree, lev, key = cKDTree(c), np.floor(np.log2(hm)), [np.zeros(0, np.int64)]
|
| 431 |
+
for L in np.unique(lev):
|
| 432 |
+
sel = np.nonzero(lev == L)[0]
|
| 433 |
+
pr = cKDTree(c[sel]).sparse_distance_matrix(tree, 1.5 * hm[sel].max() * (1 + 1e-9), output_type="ndarray")
|
| 434 |
+
a, b = sel[pr["i"]], pr["j"]
|
| 435 |
+
key.append(np.minimum(a, b) * n + np.maximum(a, b))
|
| 436 |
+
key = np.unique(np.concatenate(key))
|
| 437 |
+
ii, jj = key // n, key % n
|
| 438 |
+
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]))
|
| 439 |
+
return ii[ok], jj[ok]
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
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"
|
| 443 |
+
_IMG_CACHE: dict = {}
|
| 444 |
+
_IMG_GRID: dict = {}
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class substrate:
|
| 448 |
+
"""Context manager: the MoM Green's function inside the block (`SUBSTRATE`): model "slab_open" (default since
|
| 449 |
+
2026-10-10, PRIOR_SCHEME.md 14.6), "halfspace" (the kernel of the priors the released models were trained on) or
|
| 450 |
+
"slab_pec"; t_um the substrate thickness (None: unchanged)."""
|
| 451 |
+
|
| 452 |
+
def __init__(self, model: str | None, t_um: float | None = None):
|
| 453 |
+
self.new = {k: v for k, v in (("model", model), ("t_um", t_um)) if v is not None}
|
| 454 |
+
|
| 455 |
+
def __enter__(self):
|
| 456 |
+
self.old = dict(SUBSTRATE)
|
| 457 |
+
SUBSTRATE.update(self.new)
|
| 458 |
+
return self
|
| 459 |
+
|
| 460 |
+
def __exit__(self, *exc):
|
| 461 |
+
SUBSTRATE.clear()
|
| 462 |
+
SUBSTRATE.update(self.old)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def _image_correction(d, eps_r: float, exact: bool = False):
|
| 466 |
+
"""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
|
| 467 |
+
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,
|
| 468 |
+
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),
|
| 469 |
+
"slab_pec" = metal backside (w_n = -(1 + K) (-K)^(n-1); weights sum to -1). Images up to K^2n < 1e-4, the remaining
|
| 470 |
+
weight as one more image; tabulated on a uniform grid of t / 1000 up to 100 mm and interpolated linearly (dense
|
| 471 |
+
assembly), or summed exactly (exact=True: the H-matrix kernel, whose ACA blocks need a smooth kernel). None for the
|
| 472 |
+
half-space (the published kernel)."""
|
| 473 |
+
m = SUBSTRATE["model"]
|
| 474 |
+
if m == "halfspace":
|
| 475 |
+
return None
|
| 476 |
+
key = (m, float(SUBSTRATE["t_um"]), float(eps_r))
|
| 477 |
+
if key not in _IMG_CACHE:
|
| 478 |
+
K, t = (eps_r - 1) / (eps_r + 1), float(SUBSTRATE["t_um"])
|
| 479 |
+
n = np.arange(1, 400)
|
| 480 |
+
nmax = int(np.argmax(K ** (2 * n) < 1e-4)) + 1
|
| 481 |
+
n = n[:nmax]
|
| 482 |
+
if m == "slab_open":
|
| 483 |
+
w, total = K ** (2 * n) + K ** (2 * n - 1), K / (1 - K)
|
| 484 |
+
else:
|
| 485 |
+
w, total = -(1 + K) * (-K) ** (n - 1), -1.0
|
| 486 |
+
w, D = np.r_[w, total - w.sum()], np.r_[2 * n * t, 2 * (nmax + 1) * t]
|
| 487 |
+
du = t / 1000
|
| 488 |
+
u = np.arange(0.0, 1e5 + 2 * du, du)
|
| 489 |
+
T = (w[None, :] / np.sqrt(u[:, None] ** 2 + D[None, :] ** 2)).sum(1)
|
| 490 |
+
_IMG_CACHE[key] = (du, T, w, D)
|
| 491 |
+
du, T = _IMG_CACHE[key][:2]
|
| 492 |
+
if exact:
|
| 493 |
+
w, D = _IMG_CACHE[key][2:]
|
| 494 |
+
d2 = np.asarray(d, float) ** 2
|
| 495 |
+
return sum(wn / np.sqrt(d2 + Dn * Dn) for wn, Dn in zip(w, D))
|
| 496 |
+
if key not in _IMG_GRID:
|
| 497 |
+
_IMG_GRID[key] = du * np.arange(len(T))
|
| 498 |
+
return np.interp(d, _IMG_GRID[key], T)
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def _assemble(c, wh, diag, eps_r: float, near):
|
| 502 |
+
"""Interaction matrix / (4 pi eps0 eps_eff) for the lower Cholesky factorisation: far pairs 1 / d, near pairs (d < 1.5
|
| 503 |
+
max side) the symmetrised near(p, cq, wh) potential, diagonal `diag`; the same numbers as the dense construction.
|
| 504 |
+
Built in row blocks on the pool threads without n x n temporaries, and only the half the factorisation reads: returns
|
| 505 |
+
a Fortran-ordered matrix whose lower triangle holds the entries (its upper triangle is not initialised)."""
|
| 506 |
+
n = len(c)
|
| 507 |
+
k = 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2
|
| 508 |
+
A = np.empty((n, n))
|
| 509 |
+
x, y = c[:, 0], c[:, 1]
|
| 510 |
+
|
| 511 |
+
def rows(r0, r1):
|
| 512 |
+
d = x[r0:r1, None] - x[None, r0:]
|
| 513 |
+
np.multiply(d, d, out=d)
|
| 514 |
+
t = y[r0:r1, None] - y[None, r0:]
|
| 515 |
+
np.multiply(t, t, out=t)
|
| 516 |
+
d += t
|
| 517 |
+
np.sqrt(d, out=d)
|
| 518 |
+
corr = _image_correction(d, eps_r)
|
| 519 |
+
d[np.arange(r1 - r0), np.arange(r1 - r0)] = 1.0
|
| 520 |
+
out = A[r0:r1, r0:]
|
| 521 |
+
np.divide(1.0, d, out=out)
|
| 522 |
+
if corr is not None:
|
| 523 |
+
out += corr
|
| 524 |
+
out /= k
|
| 525 |
+
|
| 526 |
+
_run([partial(rows, a, b) for a, b in _spans(n, 64)])
|
| 527 |
+
ii, jj = _near_pairs(c, wh.max(1))
|
| 528 |
+
img = _image_correction(np.zeros(1), eps_r)
|
| 529 |
+
if len(ii):
|
| 530 |
+
A[ii, jj] = 0.5 * (near(c[ii], c[jj], wh[jj]) + near(c[jj], c[ii], wh[ii])) / k
|
| 531 |
+
if img is not None:
|
| 532 |
+
A[ii, jj] += _image_correction(np.sqrt(((c[ii] - c[jj]) ** 2).sum(1)), eps_r) / k
|
| 533 |
+
A[np.arange(n), np.arange(n)] = diag / k if img is None else (diag + img[0]) / k
|
| 534 |
+
return A.T
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _chol_solve(P, B):
|
| 538 |
+
"""Cholesky solve with the lower triangle of the Fortran-ordered P from `_assemble`, factorised in place (no copy)."""
|
| 539 |
+
return cho_solve(cho_factor(P, lower=True, overwrite_a=True, check_finite=False), B, check_finite=False)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def mom_capacitance_gds(metals: list, eps_r: float = 11.45, max_cells: int = 8000, h_min: float | None = None, grade: float = 2.0,
|
| 543 |
+
cells_per_gap: float = 3.0, offset: tuple = (0.0, 0.0), mesh: str = "v2"):
|
| 544 |
+
"""Thin-film MoM on the exact GDS polygons (ground to the chip edge), adaptive quadtree mesh (see `mom_mesh`).
|
| 545 |
+
|
| 546 |
+
metals: shapely geometries, one per conductor (index 0 = ground). `offset` (v2 mesh only) shifts the quadtree origin
|
| 547 |
+
by that fraction of the coarsest cell. Returns (C fF in the same order, n_cells, h_min)."""
|
| 548 |
+
c, h, o, h_min = mom_mesh(metals, max_cells, h_min, grade, cells_per_gap, mesh, offset)
|
| 549 |
+
try:
|
| 550 |
+
Q = mom_solve(c, h, o, len(metals), eps_r) # v3: exact near field if the 3x3 system is not positive definite
|
| 551 |
+
except np.linalg.LinAlgError:
|
| 552 |
+
if mesh != "v3":
|
| 553 |
+
raise
|
| 554 |
+
# cell cap coarser than the finger pitch: cut-panel boxes of different conductors overlap; finest cells as whole
|
| 555 |
+
# squares owned by the metal covering >= 50 % (as the v2 mesh), exact near field
|
| 556 |
+
print("v3: still not positive definite, majority finest cells", flush=True)
|
| 557 |
+
c, h, o = anchored_cells(metals, h_min, grade, majority=True)
|
| 558 |
+
Q = _mom_solve_exact_near(c, h, o, len(metals), eps_r)
|
| 559 |
+
C = np.stack([Q[o == a].sum(0) for a in range(len(metals))])
|
| 560 |
+
return 0.5 * (C + C.T), len(c), h_min
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def mom_capacitance_gds_avg(metals: list, n_offsets: int = 4, **kw):
|
| 564 |
+
"""MoM averaged over quadtree origins (offsets on a diagonal grid of the coarsest cell): removes the part of the
|
| 565 |
+
discretisation error that jumps with mesh alignment as the geometry is swept."""
|
| 566 |
+
offs = [(i / n_offsets, ((i * 3) % n_offsets) / n_offsets) for i in range(n_offsets)]
|
| 567 |
+
runs = [mom_capacitance_gds(metals, offset=o, mesh="v2", **kw) for o in offs]
|
| 568 |
+
return np.mean([r[0] for r in runs], 0), int(np.mean([r[1] for r in runs])), runs[0][2]
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def _both(f, g):
|
| 572 |
+
"""(f(), g()), a LinAlgError in place of a result; concurrently (g on a helper thread) when more than one thread is
|
| 573 |
+
allowed: the gap/6 and gap/3 solves of v3-rich are independent."""
|
| 574 |
+
def call(fn):
|
| 575 |
+
try:
|
| 576 |
+
return fn()
|
| 577 |
+
except np.linalg.LinAlgError as e:
|
| 578 |
+
return e
|
| 579 |
+
if _nthreads() < 2:
|
| 580 |
+
return call(f), call(g)
|
| 581 |
+
with ThreadPoolExecutor(1, thread_name_prefix="tlsq-rich") as ex:
|
| 582 |
+
fut = ex.submit(call, g)
|
| 583 |
+
a = call(f)
|
| 584 |
+
return a, fut.result()
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def mom_capacitance_gds_rich(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 8000,
|
| 588 |
+
max_cells_fine: int = 16000, grade: float = 2.0):
|
| 589 |
+
"""v3 MoM with Richardson extrapolation: solves at gap/cells_per_gap and at half that cell size on the same
|
| 590 |
+
conductor-anchored lattice and extrapolates the first-order discretisation error to zero cell size. If the cell
|
| 591 |
+
cap forces both meshes to the same resolution, returns the finer solve. If the coarse system is not positive
|
| 592 |
+
definite (sliver edge panels badly resolved by the 3x3 near-field rule; ~0.2 % of designs), returns the other
|
| 593 |
+
solve alone (fine if the coarse one fails, coarse if the fine one fails). The two solves run concurrently when more
|
| 594 |
+
than one thread is allowed. Returns (C, total cells, h of the fine mesh)."""
|
| 595 |
+
rf, rc = _both(partial(mom_capacitance_gds, metals, eps_r, max_cells_fine, None, grade, 2 * cells_per_gap, mesh="v3"),
|
| 596 |
+
partial(mom_capacitance_gds, metals, eps_r, max_cells, None, grade, cells_per_gap, mesh="v3"))
|
| 597 |
+
if isinstance(rf, np.linalg.LinAlgError):
|
| 598 |
+
print("v3-rich: fine mesh not positive definite, coarse solve only", flush=True)
|
| 599 |
+
if isinstance(rc, np.linalg.LinAlgError):
|
| 600 |
+
raise rc
|
| 601 |
+
return rc
|
| 602 |
+
Cf, nf, hf = rf
|
| 603 |
+
if isinstance(rc, np.linalg.LinAlgError):
|
| 604 |
+
print("v3-rich: coarse mesh not positive definite, fine solve only", flush=True)
|
| 605 |
+
return Cf, nf, hf
|
| 606 |
+
Cc, nc, hc = rc
|
| 607 |
+
r = hc / hf
|
| 608 |
+
C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1)
|
| 609 |
+
return C, nc + nf, hf
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
# ---------------------------------------------------------------- flagship prior: strip-merged mesh, H-matrix solve, Richardson
|
| 613 |
+
# Resolution-controlled (panels per gap, no small cap), the same conductor-anchored panels as v3 merged along straight
|
| 614 |
+
# edges, the exact rectangle potential for near pairs, and for large systems an H-matrix (ACA far field) with
|
| 615 |
+
# preconditioned CG instead of the dense Cholesky: O(n log n) time and memory.
|
| 616 |
+
|
| 617 |
+
DENSE_MAX = int(os.environ.get("TLSQ_MOM_DENSE_MAX", 12000)) # panels up to which the dense Cholesky is used (faster below this size)
|
| 618 |
+
HMAT = dict(leaf=128, eta=2.0, eps=1e-9, tol=1e-12, maxit=1000) # ACA block tolerance (relative Frobenius) and PCG residual
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def _segments(metals):
|
| 622 |
+
segs, verts = [], []
|
| 623 |
+
for g in metals:
|
| 624 |
+
for p in getattr(g, "geoms", [g]):
|
| 625 |
+
for ring in [p.exterior, *p.interiors]:
|
| 626 |
+
xy = np.asarray(ring.coords)
|
| 627 |
+
verts.append(xy[:-1])
|
| 628 |
+
segs.append(np.stack([xy[:-1], xy[1:]], 1))
|
| 629 |
+
S = np.concatenate(segs)
|
| 630 |
+
return shapely.linestrings(S), S, np.concatenate(verts)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def strip_merge(c, wh, o, metals, h_f, lmax_mult: float = 16.0, grade: float = 1.0):
|
| 634 |
+
"""Merge runs of equal-width panels along the direction of their nearest polygon edge (where the charge density is
|
| 635 |
+
translation-invariant) into panels of length <= lmax_mult * h_f and <= grade * distance to the nearest vertex;
|
| 636 |
+
the size across the edge is kept. Returns merged (centres, sizes, owners)."""
|
| 637 |
+
lines, S, verts = _segments(metals)
|
| 638 |
+
near = shapely.STRtree(lines).nearest(shapely.points(c))
|
| 639 |
+
d = S[near, 1] - S[near, 0]
|
| 640 |
+
horiz = np.abs(d[:, 0]) >= np.abs(d[:, 1])
|
| 641 |
+
dv, _ = cKDTree(verts).query(c, workers=-1)
|
| 642 |
+
allow = np.minimum(lmax_mult * h_f, grade * dv)
|
| 643 |
+
out_c, out_wh, out_o = [], [], []
|
| 644 |
+
for axis, mask in ((0, horiz), (1, ~horiz)):
|
| 645 |
+
if not mask.any():
|
| 646 |
+
continue
|
| 647 |
+
idx = np.nonzero(mask)[0]
|
| 648 |
+
other = 1 - axis
|
| 649 |
+
key = np.stack([o[idx], np.round(c[idx, other], 4), np.round(wh[idx, other], 4)], 1)
|
| 650 |
+
order = np.lexsort([c[idx, axis], key[:, 2], key[:, 1], key[:, 0]])
|
| 651 |
+
idx, key = idx[order], key[order]
|
| 652 |
+
same = np.all(key[1:] == key[:-1], 1)
|
| 653 |
+
lo, hi = c[idx, axis] - wh[idx, axis] / 2, c[idx, axis] + wh[idx, axis] / 2
|
| 654 |
+
adjacent = same & (np.abs(hi[:-1] - lo[1:]) < 1e-6)
|
| 655 |
+
start = 0
|
| 656 |
+
while start < len(idx):
|
| 657 |
+
end, length, cap = start, wh[idx[start], axis], allow[idx[start]]
|
| 658 |
+
while end + 1 < len(idx) and adjacent[end] and length + wh[idx[end + 1], axis] <= min(cap, allow[idx[end + 1]]):
|
| 659 |
+
end += 1
|
| 660 |
+
length += wh[idx[end], axis]
|
| 661 |
+
cap = min(cap, allow[idx[end]])
|
| 662 |
+
cc, ww = np.zeros(2), np.zeros(2)
|
| 663 |
+
cc[axis], cc[other] = 0.5 * (lo[start] + hi[end]), c[idx[start], other]
|
| 664 |
+
ww[axis], ww[other] = hi[end] - lo[start], wh[idx[start], other]
|
| 665 |
+
out_c.append(cc)
|
| 666 |
+
out_wh.append(ww)
|
| 667 |
+
out_o.append(o[idx[start]])
|
| 668 |
+
start = end + 1
|
| 669 |
+
return np.array(out_c), np.array(out_wh), np.array(out_o)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def mesh_flagship(metals: list, h: float, max_cells: int, grade: float = 2.0, lmax_mult: float = 16.0, merge_grade: float = 1.0,
|
| 673 |
+
majority: bool = False):
|
| 674 |
+
"""Strip-merged v3 mesh at finest panel h, doubled (same lattice) until the merged mesh has at most max_cells panels.
|
| 675 |
+
Returns (centres, sizes, owners, h, raw panel count)."""
|
| 676 |
+
while True:
|
| 677 |
+
raw = anchored_cells(metals, h, grade, majority=majority, limit=8 * max_cells)
|
| 678 |
+
if raw is not None:
|
| 679 |
+
c, wh, o = strip_merge(*raw, metals, h, lmax_mult, merge_grade)
|
| 680 |
+
if len(c) <= max_cells:
|
| 681 |
+
return c, wh, o, h, len(raw[0])
|
| 682 |
+
h *= 2.0
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
class _Kernel:
|
| 686 |
+
"""Entries of P / (4 pi eps0 eps_eff) in a permuted panel order: 1 / d for far pairs, the exact rectangle potential
|
| 687 |
+
for near pairs (d < 1.5 max side) and rect_self on the diagonal; near and diagonal corrections to 1 / d are held in
|
| 688 |
+
a CSR matrix so that any block is 1 / d + N[I, J] (the same numbers as `_assemble` with `rect_potential`)."""
|
| 689 |
+
|
| 690 |
+
def __init__(self, c, wh, eps_r, perm):
|
| 691 |
+
from scipy.sparse import csr_matrix
|
| 692 |
+
|
| 693 |
+
self.x, self.y = c[perm, 0].copy(), c[perm, 1].copy()
|
| 694 |
+
self.k = 4 * np.pi * EPS0_FF_PER_UM * (eps_r + 1) / 2
|
| 695 |
+
self.eps_r = eps_r
|
| 696 |
+
self.img = _image_correction(np.zeros(1), eps_r) is not None # finite-substrate image term (exact series in blocks / rows)
|
| 697 |
+
n = len(c)
|
| 698 |
+
ii, jj = _near_pairs(c, wh.max(1))
|
| 699 |
+
d = np.sqrt(((c[ii] - c[jj]) ** 2).sum(1))
|
| 700 |
+
near = 0.5 * (rect_potential(c[ii], c[jj], wh[jj]) + rect_potential(c[jj], c[ii], wh[ii])) - 1.0 / d
|
| 701 |
+
inv = np.empty(n, np.int64)
|
| 702 |
+
inv[perm] = np.arange(n)
|
| 703 |
+
rows = inv[np.concatenate([ii, jj, np.arange(n)])]
|
| 704 |
+
cols = inv[np.concatenate([jj, ii, np.arange(n)])]
|
| 705 |
+
vals = np.concatenate([near, near, rect_self(wh[:, 0], wh[:, 1]) - 1.0])
|
| 706 |
+
self.N = csr_matrix((vals, (rows, cols)), shape=(n, n))
|
| 707 |
+
|
| 708 |
+
def block(self, a0, a1, b0, b1):
|
| 709 |
+
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)
|
| 710 |
+
corr = _image_correction(d, self.eps_r, exact=True)
|
| 711 |
+
if a0 == b0:
|
| 712 |
+
d[np.arange(a1 - a0), np.arange(a1 - a0)] = 1.0
|
| 713 |
+
A = 1.0 / d
|
| 714 |
+
if corr is not None:
|
| 715 |
+
A += corr
|
| 716 |
+
Nb = self.N[a0:a1, b0:b1]
|
| 717 |
+
if Nb.nnz:
|
| 718 |
+
A += Nb.toarray()
|
| 719 |
+
return A / self.k
|
| 720 |
+
|
| 721 |
+
def row(self, i, b0, b1):
|
| 722 |
+
d = np.sqrt((self.x[i] - self.x[b0:b1]) ** 2 + (self.y[i] - self.y[b0:b1]) ** 2)
|
| 723 |
+
r = 1.0 / d
|
| 724 |
+
if self.img:
|
| 725 |
+
r += _image_correction(d, self.eps_r, exact=True)
|
| 726 |
+
Nr = self.N[i, b0:b1]
|
| 727 |
+
if Nr.nnz:
|
| 728 |
+
r += Nr.toarray()[0]
|
| 729 |
+
return r / self.k
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def _cluster_tree(c, leaf: int):
|
| 733 |
+
"""Recursive bisection of the panel centres along the longer side of their bounding box at the median: a permutation
|
| 734 |
+
making every cluster a contiguous range, and nodes (a, b, lo, hi, left, right)."""
|
| 735 |
+
perm, nodes = np.arange(len(c)), []
|
| 736 |
+
|
| 737 |
+
def rec(a, b):
|
| 738 |
+
idx = perm[a:b]
|
| 739 |
+
lo, hi = c[idx].min(0), c[idx].max(0)
|
| 740 |
+
k = len(nodes)
|
| 741 |
+
nodes.append([a, b, lo, hi, -1, -1])
|
| 742 |
+
if b - a > leaf:
|
| 743 |
+
ax = int(np.argmax(hi - lo))
|
| 744 |
+
perm[a:b] = idx[np.argsort(c[idx, ax], kind="stable")]
|
| 745 |
+
m = a + (b - a) // 2
|
| 746 |
+
nodes[k][4], nodes[k][5] = rec(a, m), rec(m, b)
|
| 747 |
+
return k
|
| 748 |
+
|
| 749 |
+
rec(0, len(c))
|
| 750 |
+
return perm, nodes
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
def _aca(K, a0, a1, b0, b1, eps, max_rank):
|
| 754 |
+
"""Partial-pivoting adaptive cross approximation of the block (a0:a1, b0:b1) to relative Frobenius accuracy eps:
|
| 755 |
+
(U, V) with block ~ U V^T, or None when the rank would exceed max_rank."""
|
| 756 |
+
m, n = a1 - a0, b1 - b0
|
| 757 |
+
U, V, used_r, used_c = [], [], np.zeros(m, bool), np.zeros(n, bool)
|
| 758 |
+
i, norm2 = 0, 0.0
|
| 759 |
+
for _ in range(min(m, n, max_rank)):
|
| 760 |
+
r = K.row(a0 + i, b0, b1)
|
| 761 |
+
for u, v in zip(U, V):
|
| 762 |
+
r -= u[i] * v
|
| 763 |
+
rm = np.where(used_c, 0.0, np.abs(r))
|
| 764 |
+
j = int(np.argmax(rm))
|
| 765 |
+
if rm[j] == 0.0:
|
| 766 |
+
break
|
| 767 |
+
v = r / r[j]
|
| 768 |
+
u = K.row(b0 + j, a0, a1) # column j of the block = row j of the symmetric kernel
|
| 769 |
+
for uu, vv in zip(U, V):
|
| 770 |
+
u -= vv[j] * uu
|
| 771 |
+
used_r[i], used_c[j] = True, True
|
| 772 |
+
nu, nv = float(u @ u), float(v @ v)
|
| 773 |
+
norm2 += nu * nv + 2 * sum(float(u @ uu) * float(v @ vv) for uu, vv in zip(U, V))
|
| 774 |
+
U.append(u)
|
| 775 |
+
V.append(v)
|
| 776 |
+
if nu * nv <= eps**2 * norm2:
|
| 777 |
+
break
|
| 778 |
+
um = np.where(used_r, 0.0, np.abs(u))
|
| 779 |
+
i = int(np.argmax(um))
|
| 780 |
+
if um[i] == 0.0:
|
| 781 |
+
break
|
| 782 |
+
else:
|
| 783 |
+
return None
|
| 784 |
+
return np.stack(U, 1), np.stack(V, 1)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
class _HMatrix:
|
| 788 |
+
"""Hierarchical matrix of the panel system: dense blocks for leaf pairs that are not well separated, ACA low-rank
|
| 789 |
+
blocks for admissible pairs (min diameter <= eta x distance); only the upper block triangle is stored (symmetric)."""
|
| 790 |
+
|
| 791 |
+
def __init__(self, c, wh, eps_r, leaf=128, eta=2.0, eps=1e-9):
|
| 792 |
+
self.n = len(c)
|
| 793 |
+
self.perm, nodes = _cluster_tree(c, leaf)
|
| 794 |
+
self.K = _Kernel(c, wh, eps_r, self.perm)
|
| 795 |
+
self.eps = eps
|
| 796 |
+
plan = []
|
| 797 |
+
|
| 798 |
+
def leafq(k):
|
| 799 |
+
return nodes[k][4] < 0
|
| 800 |
+
|
| 801 |
+
def rec(s, t):
|
| 802 |
+
a0, a1, lo_s, hi_s, sl, sr = nodes[s]
|
| 803 |
+
b0, b1, lo_t, hi_t, tl, tr = nodes[t]
|
| 804 |
+
if s == t:
|
| 805 |
+
if leafq(s):
|
| 806 |
+
plan.append(("d", a0, a1, a0, a1))
|
| 807 |
+
else:
|
| 808 |
+
rec(sl, sl), rec(sr, sr), rec(sl, sr)
|
| 809 |
+
return
|
| 810 |
+
gap = np.maximum(0.0, np.maximum(lo_s - hi_t, lo_t - hi_s))
|
| 811 |
+
diam = min(np.sqrt(((hi_s - lo_s) ** 2).sum()), np.sqrt(((hi_t - lo_t) ** 2).sum()))
|
| 812 |
+
if diam <= eta * np.sqrt((gap**2).sum()):
|
| 813 |
+
plan.append(("l", a0, a1, b0, b1))
|
| 814 |
+
elif leafq(s) and leafq(t):
|
| 815 |
+
plan.append(("d", a0, a1, b0, b1))
|
| 816 |
+
elif leafq(s):
|
| 817 |
+
rec(s, tl), rec(s, tr)
|
| 818 |
+
elif leafq(t):
|
| 819 |
+
rec(sl, t), rec(sr, t)
|
| 820 |
+
else:
|
| 821 |
+
for u in (sl, sr):
|
| 822 |
+
for v in (tl, tr):
|
| 823 |
+
rec(u, v)
|
| 824 |
+
|
| 825 |
+
rec(0, 0)
|
| 826 |
+
self.dense, self.low = [], []
|
| 827 |
+
|
| 828 |
+
def build(chunk):
|
| 829 |
+
out = []
|
| 830 |
+
for kind, a0, a1, b0, b1 in chunk:
|
| 831 |
+
if kind == "l":
|
| 832 |
+
r = _aca(self.K, a0, a1, b0, b1, eps, max(2, min(a1 - a0, b1 - b0) // 2))
|
| 833 |
+
if r is not None:
|
| 834 |
+
out.append(("l", a0, a1, b0, b1, r))
|
| 835 |
+
continue
|
| 836 |
+
out.append(("d", a0, a1, b0, b1, self.K.block(a0, a1, b0, b1)))
|
| 837 |
+
return out
|
| 838 |
+
|
| 839 |
+
for res in _run([partial(build, plan[a:b]) for a, b in _spans(len(plan), 64)]):
|
| 840 |
+
for kind, a0, a1, b0, b1, M in res:
|
| 841 |
+
(self.low if kind == "l" else self.dense).append((a0, a1, b0, b1, M))
|
| 842 |
+
self.pre = [(a0, a1, cho_factor(D, lower=True)) for a0, a1, b0, _, D in self.dense if a0 == b0] # block Jacobi
|
| 843 |
+
self.n_threads = max(1, _nthreads())
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
def nbytes(self):
|
| 847 |
+
return sum(D.nbytes for *_, D in self.dense) + sum(U.nbytes + V.nbytes for *_, (U, V) in self.low)
|
| 848 |
+
|
| 849 |
+
def matvec(self, X):
|
| 850 |
+
def part(dense, low):
|
| 851 |
+
Y = np.zeros_like(X)
|
| 852 |
+
for a0, a1, b0, b1, D in dense:
|
| 853 |
+
Y[a0:a1] += D @ X[b0:b1]
|
| 854 |
+
if a0 != b0:
|
| 855 |
+
Y[b0:b1] += D.T @ X[a0:a1]
|
| 856 |
+
for a0, a1, b0, b1, (U, V) in low:
|
| 857 |
+
Y[a0:a1] += U @ (V.T @ X[b0:b1])
|
| 858 |
+
Y[b0:b1] += V @ (U.T @ X[a0:a1])
|
| 859 |
+
return Y
|
| 860 |
+
|
| 861 |
+
T = self.n_threads
|
| 862 |
+
if T < 2:
|
| 863 |
+
return part(self.dense, self.low)
|
| 864 |
+
return sum(_run([partial(part, self.dense[k::T], self.low[k::T]) for k in range(T)]))
|
| 865 |
+
|
| 866 |
+
def precondition(self, R):
|
| 867 |
+
Z = np.empty_like(R)
|
| 868 |
+
for a0, a1, cf in self.pre:
|
| 869 |
+
Z[a0:a1] = cho_solve(cf, R[a0:a1], check_finite=False)
|
| 870 |
+
return Z
|
| 871 |
+
|
| 872 |
+
def pcg(self, B, tol, maxit):
|
| 873 |
+
"""Conjugate gradients on every right-hand side column at once (independent columns), block-Jacobi preconditioned,
|
| 874 |
+
until every column's relative residual is below tol. B and the result are in the permuted order."""
|
| 875 |
+
X, R = np.zeros_like(B), B.copy()
|
| 876 |
+
Z = self.precondition(R)
|
| 877 |
+
P, rz = Z.copy(), (R * Z).sum(0)
|
| 878 |
+
bn = np.sqrt((B * B).sum(0))
|
| 879 |
+
for it in range(maxit):
|
| 880 |
+
AP = self.matvec(P)
|
| 881 |
+
alpha = rz / (P * AP).sum(0)
|
| 882 |
+
X += alpha * P
|
| 883 |
+
R -= alpha * AP
|
| 884 |
+
res = (np.sqrt((R * R).sum(0)) / bn).max()
|
| 885 |
+
if res < tol:
|
| 886 |
+
return X, it + 1, res
|
| 887 |
+
Z = self.precondition(R)
|
| 888 |
+
rz_new = (R * Z).sum(0)
|
| 889 |
+
P = Z + (rz_new / rz) * P
|
| 890 |
+
rz = rz_new
|
| 891 |
+
raise np.linalg.LinAlgError(f"H-matrix PCG did not converge in {maxit} iterations (residual {res:.1e})")
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def mom_solve_fast(c, wh, o, n_metals: int, eps_r: float = 11.45, dense_max: int | None = None):
|
| 895 |
+
"""Panel charges Q (n, n_metals) for unit excitation of every conductor, exact near field: dense Cholesky for
|
| 896 |
+
n <= dense_max panels (`_mom_solve_exact_near`), otherwise the H-matrix / PCG solve of the same system."""
|
| 897 |
+
n = len(c)
|
| 898 |
+
if n <= (DENSE_MAX if dense_max is None else dense_max):
|
| 899 |
+
return _mom_solve_exact_near(c, wh, o, n_metals, eps_r)
|
| 900 |
+
H = _HMatrix(c, wh, eps_r, HMAT["leaf"], HMAT["eta"], HMAT["eps"])
|
| 901 |
+
B = (o[:, None] == np.arange(n_metals)[None, :]).astype(float)[H.perm]
|
| 902 |
+
Xp, _, _ = H.pcg(B, HMAT["tol"], HMAT["maxit"])
|
| 903 |
+
Q = np.empty_like(Xp)
|
| 904 |
+
Q[H.perm] = Xp
|
| 905 |
+
return Q
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
def _cap_flagship(metals, eps_r, h, max_cells, grade, lmax_mult, merge_grade):
|
| 909 |
+
c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade)
|
| 910 |
+
try:
|
| 911 |
+
Q = mom_solve_fast(c, wh, o, len(metals), eps_r)
|
| 912 |
+
except np.linalg.LinAlgError: # cut panels of different conductors overlap (lattice coarser than the finger pitch)
|
| 913 |
+
print("flagship: system not positive definite, majority finest cells", flush=True)
|
| 914 |
+
c, wh, o, h, n_raw = mesh_flagship(metals, h, max_cells, grade, lmax_mult, merge_grade, majority=True)
|
| 915 |
+
Q = mom_solve_fast(c, wh, o, len(metals), eps_r)
|
| 916 |
+
C = np.stack([Q[o == a].sum(0) for a in range(len(metals))])
|
| 917 |
+
return 0.5 * (C + C.T), len(c), h, n_raw
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def mom_capacitance_gds_flagship(metals: list, eps_r: float = 11.45, cells_per_gap: float = 3.0, max_cells: int = 250000,
|
| 921 |
+
grade: float = 2.0, rich: bool = True, lmax_mult: float = 16.0, merge_grade: float = 1.0):
|
| 922 |
+
"""Flagship prior: strip-merged conductor-anchored mesh at h_f = max(gap / (2 cells_per_gap), size / 8192) and, with
|
| 923 |
+
rich=True, Richardson extrapolation with the mesh at 2 h_f (same lattice), both solved with `mom_solve_fast`. The
|
| 924 |
+
resolution is set by cells_per_gap (the fine mesh has 2 cells_per_gap panels across the smallest gap; the coarse
|
| 925 |
+
one cells_per_gap); max_cells is only a safety cap on the merged panel count (h doubles until it fits). The two solves
|
| 926 |
+
run concurrently when more than one thread is allowed. Returns (C, total panels, h of the fine mesh, info dict)."""
|
| 927 |
+
bbox = shapely.union_all(metals).bounds
|
| 928 |
+
size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 929 |
+
gap = min(shapely.distance(metals[i], metals[j]) for i in range(len(metals)) for j in range(i + 1, len(metals)))
|
| 930 |
+
hf = max(gap / (2 * cells_per_gap), size / 8192)
|
| 931 |
+
if not rich:
|
| 932 |
+
C, n, h, n_raw = _cap_flagship(metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade)
|
| 933 |
+
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}
|
| 934 |
+
rf, rc = _both(partial(_cap_flagship, metals, eps_r, hf, max_cells, grade, lmax_mult, merge_grade),
|
| 935 |
+
partial(_cap_flagship, metals, eps_r, 2 * hf, max_cells, grade, lmax_mult, merge_grade))
|
| 936 |
+
for r in (rf, rc):
|
| 937 |
+
if isinstance(r, np.linalg.LinAlgError):
|
| 938 |
+
raise r
|
| 939 |
+
(Cf, nf, h_f, raw_f), (Cc, nc, h_c, raw_c) = rf, rc
|
| 940 |
+
r = h_c / h_f
|
| 941 |
+
C = Cf if r < 1.01 else Cf + (Cf - Cc) / (r - 1)
|
| 942 |
+
info = {"h_target_um": hf, "min_gap_um": gap, "cap_hit": h_f > hf * 1.0001, "raw_cells": raw_f, "coarse_cells": nc,
|
| 943 |
+
"extrapolated": bool(r >= 1.01)}
|
| 944 |
+
return C, nf + nc, h_f, info
|
src/squadds/ml/capacitance/_core/_tlsq/geometry.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GDS conductor geometry: exact polygon metrics, separation spectra and spectral shape descriptors.
|
| 2 |
+
|
| 3 |
+
Only metal layers are used: (1,0) ground and (1,10) signal conductors. Port stubs (2,0)/(3,0) are ignored.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
|
| 10 |
+
import gdstk
|
| 11 |
+
import numpy as np
|
| 12 |
+
import shapely
|
| 13 |
+
from scipy import sparse
|
| 14 |
+
from scipy.sparse.linalg import eigsh
|
| 15 |
+
from scipy.spatial import cKDTree
|
| 16 |
+
from shapely.geometry import MultiPolygon, Polygon
|
| 17 |
+
|
| 18 |
+
GROUND_LAYER = (1, 0)
|
| 19 |
+
SIGNAL_LAYER = (1, 10)
|
| 20 |
+
BOUNDARY_STEP_UM = 0.25
|
| 21 |
+
SEP_BINS_UM = np.geomspace(0.5, 2000.0, 41)
|
| 22 |
+
N_FOURIER = 16
|
| 23 |
+
MIC_TOL = [0.01] # inscribed-circle tolerance (um); 0.1 for the approximate token variants (PRIOR_SCHEME.md 14.3.1)
|
| 24 |
+
RASTER_PX = 512
|
| 25 |
+
N_EIG = 16
|
| 26 |
+
K_BINS = 48
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class Conductors:
|
| 31 |
+
N: Polygon
|
| 32 |
+
S: Polygon
|
| 33 |
+
G: Polygon | MultiPolygon
|
| 34 |
+
pocket: Polygon | MultiPolygon # etched region inside the chip (contains N and S)
|
| 35 |
+
gap: Polygon | MultiPolygon # pocket minus signal metal (dielectric surface)
|
| 36 |
+
chip: Polygon
|
| 37 |
+
pads: list = field(default_factory=list) # extra 0 V bodies (merged into G)
|
| 38 |
+
|
| 39 |
+
def metals(self) -> dict:
|
| 40 |
+
return {"N": self.N, "S": self.S, "G": self.G}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _valid(geom):
|
| 44 |
+
g = shapely.make_valid(geom)
|
| 45 |
+
polys = [p for p in getattr(g, "geoms", [g]) if isinstance(p, (Polygon, MultiPolygon))]
|
| 46 |
+
return shapely.union_all(polys)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def load_conductors(gds_path) -> Conductors:
|
| 50 |
+
lib = gdstk.read_gds(str(gds_path))
|
| 51 |
+
cell = lib.top_level()[0]
|
| 52 |
+
to_um = lib.unit / 1e-6
|
| 53 |
+
sig = [p for p in cell.polygons if (p.layer, p.datatype) == SIGNAL_LAYER]
|
| 54 |
+
gnd = [p for p in cell.polygons if (p.layer, p.datatype) == GROUND_LAYER]
|
| 55 |
+
if len(sig) < 2 or len(gnd) != 1:
|
| 56 |
+
raise ValueError(f"expected >=2 signal + 1 ground polygons, got {len(sig)} + {len(gnd)}")
|
| 57 |
+
polys = [_valid(Polygon(p.points * to_um)) for p in sig]
|
| 58 |
+
if len(polys) == 2:
|
| 59 |
+
N, S = polys
|
| 60 |
+
pads = []
|
| 61 |
+
else:
|
| 62 |
+
# multi-terminal (exp12): GDS order is not the net order. S = star at the origin; N = body fed by the
|
| 63 |
+
# single port stub; the remaining pads are held at 0 V in the solve and are merged into ground.
|
| 64 |
+
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]])
|
| 65 |
+
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])))
|
| 66 |
+
n = min((i for i in range(len(polys)) if i != s), key=lambda i: polys[i].distance(port))
|
| 67 |
+
N, S = polys[n], polys[s]
|
| 68 |
+
pads = [g for i, g in enumerate(polys) if i not in (n, s)]
|
| 69 |
+
G0 = _valid(Polygon(gnd[0].points * to_um))
|
| 70 |
+
if abs(G0.area - gnd[0].area() * to_um**2) > 1e-6 * G0.area:
|
| 71 |
+
raise ValueError("ground polygon area changed during repair")
|
| 72 |
+
chip = shapely.box(*G0.bounds)
|
| 73 |
+
pocket = chip.difference(G0)
|
| 74 |
+
G = shapely.union_all([G0, *pads]) if pads else G0
|
| 75 |
+
gap = pocket.difference(N).difference(S)
|
| 76 |
+
for g in pads:
|
| 77 |
+
gap = gap.difference(g)
|
| 78 |
+
return Conductors(N, S, G, pocket, gap, chip, pads)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def sample_boundary(geom, step: float = BOUNDARY_STEP_UM) -> np.ndarray:
|
| 82 |
+
rings = []
|
| 83 |
+
for poly in getattr(geom, "geoms", [geom]):
|
| 84 |
+
rings += [poly.exterior, *poly.interiors]
|
| 85 |
+
pts = []
|
| 86 |
+
for r in rings:
|
| 87 |
+
n = max(int(np.ceil(r.length / step)), 4)
|
| 88 |
+
pts.append(shapely.get_coordinates(shapely.line_interpolate_point(r, np.linspace(0, r.length, n, endpoint=False))))
|
| 89 |
+
return np.concatenate(pts)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def boundaries(c: Conductors) -> dict[str, np.ndarray]:
|
| 93 |
+
# ground edge = boundary of the etched pocket
|
| 94 |
+
g = [sample_boundary(c.pocket)] + [sample_boundary(p) for p in c.pads]
|
| 95 |
+
return {"N": sample_boundary(c.N), "S": sample_boundary(c.S), "G": np.concatenate(g)}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def shape_metrics(poly) -> dict:
|
| 99 |
+
hull = poly.convex_hull
|
| 100 |
+
x0, y0, x1, y1 = poly.bounds
|
| 101 |
+
cx, cy = poly.centroid.x, poly.centroid.y
|
| 102 |
+
ixx, iyy, ixy = _second_moments(poly, cx, cy)
|
| 103 |
+
evals = np.linalg.eigvalsh([[ixx, ixy], [ixy, iyy]])
|
| 104 |
+
return {
|
| 105 |
+
"area": poly.area,
|
| 106 |
+
"perimeter": poly.length,
|
| 107 |
+
"convex_area": hull.area,
|
| 108 |
+
"solidity": poly.area / hull.area,
|
| 109 |
+
"compactness": 4 * np.pi * poly.area / poly.length**2,
|
| 110 |
+
"bbox_w": x1 - x0,
|
| 111 |
+
"bbox_h": y1 - y0,
|
| 112 |
+
"cx": cx,
|
| 113 |
+
"cy": cy,
|
| 114 |
+
"I_major": evals[1],
|
| 115 |
+
"I_minor": evals[0],
|
| 116 |
+
"elongation": np.sqrt(evals[1] / max(evals[0], 1e-30)),
|
| 117 |
+
"inscribed_radius": shapely.maximum_inscribed_circle(poly, MIC_TOL[0]).length if isinstance(poly, Polygon) else np.nan,
|
| 118 |
+
"n_vertices": int(shapely.get_num_coordinates(poly)),
|
| 119 |
+
"n_holes": int(sum(len(p.interiors) for p in getattr(poly, "geoms", [poly]))),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _second_moments(geom, cx, cy) -> tuple[float, float, float]:
|
| 124 |
+
ixx = iyy = ixy = 0.0
|
| 125 |
+
for poly in getattr(geom, "geoms", [geom]):
|
| 126 |
+
for k, ring in enumerate([poly.exterior, *poly.interiors]):
|
| 127 |
+
xy = np.asarray(ring.coords) - (cx, cy)
|
| 128 |
+
x, y = xy[:-1, 0], xy[:-1, 1]
|
| 129 |
+
xn, yn = xy[1:, 0], xy[1:, 1]
|
| 130 |
+
a = x * yn - xn * y
|
| 131 |
+
sgn = 1.0 if ring.is_ccw == (k == 0) else -1.0
|
| 132 |
+
ixx += sgn * np.sum(a * (y**2 + y * yn + yn**2)) / 12
|
| 133 |
+
iyy += sgn * np.sum(a * (x**2 + x * xn + xn**2)) / 12
|
| 134 |
+
ixy += sgn * np.sum(a * (x * yn + 2 * x * y + 2 * xn * yn + xn * y)) / 24
|
| 135 |
+
return abs(ixx), abs(iyy), ixy
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def fourier_descriptors(poly, n_samples: int = 512) -> np.ndarray:
|
| 139 |
+
"""|c_k|/|c_1| for k=-N..N of the outer contour (translation/rotation/scale invariant)."""
|
| 140 |
+
ring = max(getattr(poly, "geoms", [poly]), key=lambda p: p.area).exterior
|
| 141 |
+
if not ring.is_ccw:
|
| 142 |
+
ring = shapely.reverse(ring)
|
| 143 |
+
pts = shapely.get_coordinates(shapely.line_interpolate_point(ring, np.linspace(0, 1, n_samples, endpoint=False), normalized=True))
|
| 144 |
+
c = np.fft.fft(pts[:, 0] + 1j * pts[:, 1]) / n_samples
|
| 145 |
+
k = np.r_[np.arange(-N_FOURIER, 0), np.arange(0, N_FOURIER + 1)]
|
| 146 |
+
mags = np.abs(c[k])
|
| 147 |
+
mags[k == 0] = 0.0
|
| 148 |
+
return mags / mags[k == 1][0]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def separation_spectrum(a_pts: np.ndarray, b_pts: np.ndarray) -> tuple[np.ndarray, dict]:
|
| 152 |
+
d, _ = cKDTree(b_pts).query(a_pts)
|
| 153 |
+
hist, _ = np.histogram(d, bins=SEP_BINS_UM, weights=np.full(len(d), BOUNDARY_STEP_UM))
|
| 154 |
+
dmin = float(d.min())
|
| 155 |
+
s = {"dmin": dmin, "P_inv": float(np.sum(BOUNDARY_STEP_UM / np.maximum(d, 0.05)))}
|
| 156 |
+
for f in (1.05, 1.5, 2.0, 3.0):
|
| 157 |
+
s[f"L_{f:g}dmin"] = float(np.sum(d <= f * dmin) * BOUNDARY_STEP_UM)
|
| 158 |
+
for d0 in (5.0, 10.0, 20.0):
|
| 159 |
+
s[f"L_le{d0:g}um"] = float(np.sum(d <= d0) * BOUNDARY_STEP_UM)
|
| 160 |
+
return hist, s
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def window(c: Conductors) -> tuple[float, float, float]:
|
| 164 |
+
"""Square raster window around the pocket and signal metal: (x0, y0, side) in µm."""
|
| 165 |
+
x0, y0, x1, y1 = shapely.union(c.N, c.S).buffer(0).bounds
|
| 166 |
+
gx0, gy0, gx1, gy1 = c.pocket.bounds
|
| 167 |
+
cx, cy = (gx0 + gx1) / 2, (gy0 + gy1) / 2
|
| 168 |
+
side = 1.05 * max(gx1 - gx0, gy1 - gy0, x1 - x0, y1 - y0)
|
| 169 |
+
return cx - side / 2, cy - side / 2, side
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def raster(c: Conductors, npx: int = RASTER_PX) -> tuple[dict[str, np.ndarray], float, tuple[float, float]]:
|
| 173 |
+
wx0, wy0, side = window(c)
|
| 174 |
+
cx, cy = wx0 + side / 2, wy0 + side / 2
|
| 175 |
+
px = side / npx
|
| 176 |
+
xs = cx - side / 2 + (np.arange(npx) + 0.5) * px
|
| 177 |
+
ys = cy - side / 2 + (np.arange(npx) + 0.5) * px
|
| 178 |
+
X, Y = np.meshgrid(xs, ys)
|
| 179 |
+
masks = {}
|
| 180 |
+
for k, g in c.metals().items():
|
| 181 |
+
shapely.prepare(g)
|
| 182 |
+
masks[k] = shapely.contains_xy(g, X, Y)
|
| 183 |
+
return masks, px, (cx - side / 2, cy - side / 2)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def radial_power_spectrum(img: np.ndarray, px: float) -> tuple[np.ndarray, np.ndarray]:
|
| 187 |
+
n = img.shape[0]
|
| 188 |
+
F = np.fft.fftshift(np.fft.fft2(img - img.mean()))
|
| 189 |
+
P = np.abs(F) ** 2 / img.size
|
| 190 |
+
k = np.fft.fftshift(np.fft.fftfreq(n, d=px))
|
| 191 |
+
KX, KY = np.meshgrid(k, k)
|
| 192 |
+
kr = np.hypot(KX, KY).ravel()
|
| 193 |
+
edges = np.geomspace(1.0 / (n * px), 0.5 / px, K_BINS + 1)
|
| 194 |
+
idx = np.digitize(kr, edges) - 1
|
| 195 |
+
ok = (idx >= 0) & (idx < K_BINS)
|
| 196 |
+
s = np.bincount(idx[ok], weights=P.ravel()[ok], minlength=K_BINS)
|
| 197 |
+
cnt = np.bincount(idx[ok], minlength=K_BINS)
|
| 198 |
+
return np.sqrt(edges[1:] * edges[:-1]), np.where(cnt > 0, s / np.maximum(cnt, 1), np.nan)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def dirichlet_eigenvalues(mask: np.ndarray, px: float, k: int = N_EIG) -> np.ndarray:
|
| 202 |
+
"""Lowest Dirichlet Laplacian eigenvalues of a pixel mask (Shape-DNA), in um^-2."""
|
| 203 |
+
idx = -np.ones(mask.shape, dtype=np.int64)
|
| 204 |
+
ii, jj = np.nonzero(mask)
|
| 205 |
+
n = len(ii)
|
| 206 |
+
if n < 4 * k:
|
| 207 |
+
return np.full(k, np.nan)
|
| 208 |
+
idx[ii, jj] = np.arange(n)
|
| 209 |
+
rows, cols = [np.arange(n)], [np.arange(n)]
|
| 210 |
+
vals = [np.full(n, 4.0)]
|
| 211 |
+
for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
| 212 |
+
ni, nj = ii + di, jj + dj
|
| 213 |
+
inside = (ni >= 0) & (ni < mask.shape[0]) & (nj >= 0) & (nj < mask.shape[1])
|
| 214 |
+
nb = np.full(n, -1)
|
| 215 |
+
nb[inside] = idx[ni[inside], nj[inside]]
|
| 216 |
+
ok = nb >= 0
|
| 217 |
+
rows.append(np.arange(n)[ok])
|
| 218 |
+
cols.append(nb[ok])
|
| 219 |
+
vals.append(-np.ones(ok.sum()))
|
| 220 |
+
L = sparse.csc_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n))
|
| 221 |
+
ev = eigsh(L, k=k, sigma=0, which="LM", return_eigenvectors=False)
|
| 222 |
+
return np.sort(ev) / px**2
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def geometry_record(gds_path) -> tuple[dict, dict]:
|
| 226 |
+
return geometry_record_conductors(load_conductors(gds_path))
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def geometry_record_conductors(c: Conductors) -> tuple[dict, dict]:
|
| 230 |
+
"""Descriptors of a (N, S, G) conductor triple; for multi-conductor queries N/S are the queried pair, G the rest."""
|
| 231 |
+
scalars, arrays = {}, {}
|
| 232 |
+
for name, g in (("N", c.N), ("S", c.S), ("pocket", c.pocket)):
|
| 233 |
+
for k, v in shape_metrics(g).items():
|
| 234 |
+
scalars[f"{name}_{k}"] = float(v)
|
| 235 |
+
arrays[f"fourier_{name}"] = fourier_descriptors(g)
|
| 236 |
+
scalars["gap_area"] = c.gap.area
|
| 237 |
+
scalars["chip_w"], scalars["chip_h"] = c.chip.bounds[2] - c.chip.bounds[0], c.chip.bounds[3] - c.chip.bounds[1]
|
| 238 |
+
scalars["G_area"] = c.G.area
|
| 239 |
+
|
| 240 |
+
b = boundaries(c)
|
| 241 |
+
for a, t in (("N", "S"), ("S", "N"), ("N", "G"), ("G", "N"), ("S", "G"), ("G", "S")):
|
| 242 |
+
hist, s = separation_spectrum(b[a], b[t])
|
| 243 |
+
arrays[f"sep_{a}{t}"] = hist
|
| 244 |
+
scalars.update({f"sep_{a}{t}_{k}": v for k, v in s.items()})
|
| 245 |
+
|
| 246 |
+
masks, px, origin = raster(c)
|
| 247 |
+
scalars["raster_px_um"] = px
|
| 248 |
+
metal = (masks["N"] | masks["S"] | masks["G"]).astype(np.float64)
|
| 249 |
+
k, P = radial_power_spectrum(metal, px)
|
| 250 |
+
arrays["psd_k"], arrays["psd_metal"] = k, P
|
| 251 |
+
arrays["psd_NS"] = radial_power_spectrum(masks["N"].astype(float) - masks["S"].astype(float), px)[1]
|
| 252 |
+
for name in ("N", "S"):
|
| 253 |
+
arrays[f"eig_{name}"] = dirichlet_eigenvalues(masks[name], px)
|
| 254 |
+
scalars[f"{name}_raster_area_err"] = float(masks[name].sum() * px**2 / getattr(c, name).area - 1)
|
| 255 |
+
arrays["sep_bins_um"] = SEP_BINS_UM
|
| 256 |
+
return scalars, arrays
|
src/squadds/ml/capacitance/_core/_tlsq/uge/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Universal GDS Embedding framework: GDS -> scene -> scene graph (+ physics-proxy plugins) -> universal vector / GNN.
|
| 2 |
+
|
| 3 |
+
The recipe is dataset-agnostic; what a user adapts is (1) the layer map / net naming of their GDS, (2) the physics proxy
|
| 4 |
+
plugin that fits their observable (capacitance, resonance frequency, kappa, ...), and (3) the target adapter.
|
| 5 |
+
"""
|
src/squadds/ml/capacitance/_core/_tlsq/uge/blocks.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Physics-agnostic geometry blocks: node (per conductor), edge (per conductor pair) and global features, all in
|
| 2 |
+
physical units (log µm, ratios) so that nothing is fitted to a dataset."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import hashlib
|
| 7 |
+
import os
|
| 8 |
+
import pickle
|
| 9 |
+
from collections.abc import Mapping
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import shapely
|
| 14 |
+
from scipy.special import ellipk
|
| 15 |
+
from scipy.spatial import cKDTree
|
| 16 |
+
|
| 17 |
+
from .. import geometry as _geometry
|
| 18 |
+
from ..embed.proxy import _nthreads
|
| 19 |
+
from ..geometry import fourier_descriptors, sample_boundary, shape_metrics
|
| 20 |
+
from .scene import Scene
|
| 21 |
+
|
| 22 |
+
GRAN_R_UM = np.geomspace(0.25, 100.0, 16)
|
| 23 |
+
SEP_EDGES_UM = np.geomspace(0.5, 2000.0, 11)
|
| 24 |
+
MOMENTS = (0.5, 1.0, 2.0)
|
| 25 |
+
STEP_UM = 0.25
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _log(x):
|
| 29 |
+
return float(np.log(max(float(x), 1e-9)))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def region(scene: Scene, i: int):
|
| 33 |
+
"""The shape that carries conductor i's edge: the etched pocket for the ground net, the metal otherwise."""
|
| 34 |
+
return scene.pocket if scene.conductors[i].role == "ground" else scene.conductors[i].geom
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def granulometry(g) -> np.ndarray:
|
| 38 |
+
a0 = g.area
|
| 39 |
+
return np.array([g.buffer(-r, quad_segs=4).area / a0 if a0 > 0 else 0.0 for r in GRAN_R_UM])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def node_features(scene: Scene, i: int) -> dict:
|
| 43 |
+
g = region(scene, i)
|
| 44 |
+
m = shape_metrics(g)
|
| 45 |
+
f = {"role_ground": float(scene.conductors[i].role == "ground"),
|
| 46 |
+
"log_area": _log(m["area"]), "log_perimeter": _log(m["perimeter"]), "compactness": m["compactness"],
|
| 47 |
+
"solidity": m["solidity"], "log_min_halfwidth": _log(m["inscribed_radius"]),
|
| 48 |
+
"log_aspect": abs(_log(m["bbox_w"]) - _log(m["bbox_h"])), "log_elongation": _log(m["elongation"]),
|
| 49 |
+
"log_Imajor_over_A2": _log(m["I_major"] / max(m["area"], 1e-9) ** 2), "n_holes": float(m["n_holes"]),
|
| 50 |
+
"log_width": _log(2 * m["area"] / m["perimeter"])}
|
| 51 |
+
for j, v in enumerate(fourier_descriptors(g)):
|
| 52 |
+
f[f"fourier_{j:02d}"] = float(np.log1p(50 * v))
|
| 53 |
+
for j, v in enumerate(granulometry(g)):
|
| 54 |
+
f[f"gran_{j:02d}"] = float(v)
|
| 55 |
+
return f
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _kratio(m):
|
| 59 |
+
m = np.clip(m, 1e-12, 1 - 1e-12)
|
| 60 |
+
return ellipk(1 - m) / ellipk(m)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
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)}
|
| 64 |
+
TOKEN_VARIANT: dict = {"name": "exact"} # PRIOR_SCHEME.md 14.3; "exact" = the published tokens
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def set_token_variant(name: str) -> None:
|
| 68 |
+
from ..geometry import MIC_TOL
|
| 69 |
+
|
| 70 |
+
assert name in TOKEN_VARIANTS, name
|
| 71 |
+
TOKEN_VARIANT["name"] = name
|
| 72 |
+
MIC_TOL[0] = 0.01 if name == "exact" else 0.1
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _block_distances(pts: np.ndarray, tree) -> tuple:
|
| 76 |
+
"""Distances from the samples of a to b (k-d tree) for the active token variant, with weights (multiples of the
|
| 77 |
+
sample step): the samples are grouped into consecutive blocks of k; a block whose first sample is farther than d_far
|
| 78 |
+
from b is represented by that sample with weight = block size, the other blocks sample by sample. crop: blocks whose
|
| 79 |
+
first sample is farther than the crop distance are dropped (their representatives kept if every block is dropped)."""
|
| 80 |
+
v = TOKEN_VARIANTS[TOKEN_VARIANT["name"]]
|
| 81 |
+
k = v.get("k", 64)
|
| 82 |
+
r = v.get("crop", v.get("d_far"))
|
| 83 |
+
rep = np.arange(0, len(pts), k)
|
| 84 |
+
d_rep, _ = tree.query(pts[rep], workers=_nthreads())
|
| 85 |
+
size = np.diff(np.r_[rep, len(pts)])
|
| 86 |
+
far = d_rep > r
|
| 87 |
+
near_pts = np.repeat(~far, size)
|
| 88 |
+
d_near, _ = tree.query(pts[near_pts], workers=_nthreads())
|
| 89 |
+
if "crop" in v:
|
| 90 |
+
if not near_pts.any():
|
| 91 |
+
return d_rep, size.astype(float)
|
| 92 |
+
return d_near, np.ones(len(d_near))
|
| 93 |
+
return np.r_[d_rep[far], d_near], np.r_[size[far].astype(float), np.ones(len(d_near))]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def edge_features(scene: Scene, i: int, j: int, bpts: dict, widths: dict) -> dict:
|
| 97 |
+
"""Symmetric pair features: separation spectrum (both directions averaged), minimum gap, coupling moments and the
|
| 98 |
+
coplanar-strip conformal-map coupling (Gevorgian modulus; the ground net is treated as infinitely wide)."""
|
| 99 |
+
f = {"is_ground_pair": float("ground" in (scene.conductors[i].role, scene.conductors[j].role))}
|
| 100 |
+
hist = np.zeros(len(SEP_EDGES_UM) - 1)
|
| 101 |
+
mom = np.zeros(len(MOMENTS))
|
| 102 |
+
cps = 0.0
|
| 103 |
+
dmin = np.inf
|
| 104 |
+
for a, b in ((i, j), (j, i)):
|
| 105 |
+
if TOKEN_VARIANT["name"] != "exact": # approximate tokens (PRIOR_SCHEME.md 14.3)
|
| 106 |
+
d, wq = _block_distances(bpts[a], cKDTree(bpts[b]))
|
| 107 |
+
dmin = min(dmin, d.min())
|
| 108 |
+
hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=STEP_UM * wq)[0]
|
| 109 |
+
dd = np.maximum(d, 0.05)
|
| 110 |
+
mom += 0.5 * np.array([np.sum(STEP_UM * wq * dd ** (-p)) for p in MOMENTS])
|
| 111 |
+
w1, w2 = widths[a], widths[b]
|
| 112 |
+
if np.isinf(w1) or np.isinf(w2):
|
| 113 |
+
wf = w2 if np.isinf(w1) else w1
|
| 114 |
+
mm = dd / (dd + wf)
|
| 115 |
+
else:
|
| 116 |
+
mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
|
| 117 |
+
cps += 0.5 * np.sum(STEP_UM * wq * _kratio(mm))
|
| 118 |
+
continue
|
| 119 |
+
d, _ = cKDTree(bpts[b]).query(bpts[a], workers=_nthreads())
|
| 120 |
+
dmin = min(dmin, d.min())
|
| 121 |
+
hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0]
|
| 122 |
+
dd = np.maximum(d, 0.05)
|
| 123 |
+
mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS])
|
| 124 |
+
w1, w2 = widths[a], widths[b]
|
| 125 |
+
if np.isinf(w1) or np.isinf(w2):
|
| 126 |
+
wf = w2 if np.isinf(w1) else w1
|
| 127 |
+
mm = dd / (dd + wf)
|
| 128 |
+
else:
|
| 129 |
+
mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
|
| 130 |
+
cps += 0.5 * np.sum(STEP_UM * _kratio(mm))
|
| 131 |
+
f["log_dmin"] = _log(dmin)
|
| 132 |
+
for k, v in enumerate(hist):
|
| 133 |
+
f[f"sep_{k:02d}"] = float(np.log1p(v))
|
| 134 |
+
for p, v in zip(MOMENTS, mom):
|
| 135 |
+
f[f"mom_{p:g}"] = _log(v)
|
| 136 |
+
f["log_cps"] = _log(cps)
|
| 137 |
+
f["_cps"] = cps # raw, used for shielding shares
|
| 138 |
+
return f
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
TREE_LEAFSIZE = 32 # nearest distances do not depend on the leaf size (cKDTree's own distance arithmetic); 32 is fastest
|
| 142 |
+
NN_KERNEL: dict = {"on": os.environ.get("TLSQ_NN_KERNEL", "1") == "1"} # numba exact NN (nnk.py), probe-verified
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _tree(P: np.ndarray):
|
| 146 |
+
"""Nearest-sample structure of one conductor: the numba kernel when its probe reproduces cKDTree here, else cKDTree."""
|
| 147 |
+
if NN_KERNEL["on"]:
|
| 148 |
+
try:
|
| 149 |
+
from . import nnk
|
| 150 |
+
except ImportError:
|
| 151 |
+
nnk = None
|
| 152 |
+
if nnk is not None and nnk.available():
|
| 153 |
+
return nnk.Tree(P)
|
| 154 |
+
return cKDTree(P, leafsize=TREE_LEAFSIZE)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _dist(tree, X: np.ndarray) -> np.ndarray:
|
| 158 |
+
return tree.query(X)[0] if isinstance(tree, cKDTree) else tree.dist(X)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
_EDGES_HI = np.r_[SEP_EDGES_UM[:-1], np.nextafter(SEP_EDGES_UM[-1], np.inf)] # np.histogram: last bin closed
|
| 162 |
+
_CHUNK = 1 << 20 # distances per task (rows x samples)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _dir_stats(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple:
|
| 166 |
+
"""edge_features' per-direction statistics of the samples X of one conductor against each conductor in bs (all signal,
|
| 167 |
+
or the ground alone): minimum distance, histogram counts, the three moment sums and the conformal sum. The same
|
| 168 |
+
element-wise operations and pairwise row sums as edge_features (bit-identical)."""
|
| 169 |
+
nb = len(bs)
|
| 170 |
+
D = np.empty((nb, len(X)))
|
| 171 |
+
for r, b in enumerate(bs):
|
| 172 |
+
D[r] = _dist(trees[b], X)
|
| 173 |
+
dmin = D.min(1)
|
| 174 |
+
k = np.searchsorted(_EDGES_HI, D, side="right")
|
| 175 |
+
k += (12 * np.arange(nb))[:, None]
|
| 176 |
+
cnt = np.bincount(k.ravel(), minlength=12 * nb).reshape(nb, 12)[:, 1:11]
|
| 177 |
+
del k
|
| 178 |
+
dd = np.maximum(D, 0.05, out=D)
|
| 179 |
+
mom = np.stack([np.sum(STEP_UM * dd ** (-p), axis=1) for p in MOMENTS], 1)
|
| 180 |
+
w2 = np.array([widths[b] for b in bs])[:, None]
|
| 181 |
+
if np.isinf(w1):
|
| 182 |
+
mm = dd / (dd + w2)
|
| 183 |
+
elif np.isinf(w2).any():
|
| 184 |
+
mm = dd / (dd + w1)
|
| 185 |
+
else:
|
| 186 |
+
mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
|
| 187 |
+
cps = np.sum(STEP_UM * _kratio(mm), axis=1)
|
| 188 |
+
return dmin, cnt, mom, cps
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# "bitwise" (default; training / reproduction): every feature bit-identical to the published code. "numex" (numerically exact;
|
| 192 |
+
# inference): node features and signal-signal directions computed once per class of translated copies (same shape to 1e-6
|
| 193 |
+
# um, same offset) and shared; values differ from bitwise in the last bits only (agents/embedspeed/RESULTS.md).
|
| 194 |
+
EMBED_MODE: dict = {"mode": os.environ.get("TLSQ_EMBED_MODE", "bitwise")}
|
| 195 |
+
FAR_DECIMATION: dict = {"k": 0, "d_far": 100.0}
|
| 196 |
+
# Edge storage: False (default; training) = a dict per pair; True (inference) = EdgeTable, one float64 array per key.
|
| 197 |
+
EDGE_TABLE: dict = {"on": os.environ.get("TLSQ_EDGE_TABLE", "0") == "1"}
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class EdgeTable(Mapping):
|
| 201 |
+
"""Read-only complete-graph edges: pairs i < j in combinations order, one float64 column per key (same values as the
|
| 202 |
+
dict per pair; `npcols` are returned as numpy float64, the others as Python floats). table[(i, j)] builds that pair's
|
| 203 |
+
dict on request; matrix(keys) gives the (P, len(keys)) array without building any dict."""
|
| 204 |
+
|
| 205 |
+
def __init__(self, n: int, cols: dict, npcols=()):
|
| 206 |
+
self.n, self.cols, self.npcols = n, cols, frozenset(npcols)
|
| 207 |
+
|
| 208 |
+
def _r(self, p) -> int:
|
| 209 |
+
i, j = int(p[0]), int(p[1])
|
| 210 |
+
if not 0 <= i < j < self.n:
|
| 211 |
+
raise KeyError(p)
|
| 212 |
+
return i * (2 * self.n - i - 1) // 2 + j - i - 1
|
| 213 |
+
|
| 214 |
+
def __getitem__(self, p) -> dict:
|
| 215 |
+
r = self._r(p)
|
| 216 |
+
return {k: (v[r] if k in self.npcols else float(v[r])) for k, v in self.cols.items()}
|
| 217 |
+
|
| 218 |
+
def __iter__(self):
|
| 219 |
+
return ((i, j) for i in range(self.n) for j in range(i + 1, self.n))
|
| 220 |
+
|
| 221 |
+
def __len__(self) -> int:
|
| 222 |
+
return self.n * (self.n - 1) // 2
|
| 223 |
+
|
| 224 |
+
def matrix(self, keys, dtype=np.float32) -> np.ndarray:
|
| 225 |
+
if not len(self):
|
| 226 |
+
return np.zeros((0, len(keys)), dtype)
|
| 227 |
+
return np.stack([self.cols[k] for k in keys], 1).astype(dtype)
|
| 228 |
+
|
| 229 |
+
def with_cols(self, new: dict, drop=(), npcols=()) -> "EdgeTable":
|
| 230 |
+
cols = {k: v for k, v in self.cols.items() if k not in drop}
|
| 231 |
+
return EdgeTable(self.n, {**cols, **new}, (self.npcols | frozenset(npcols)) - frozenset(drop))
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def edge_matrix(edges, keys, n: int, dtype=np.float32) -> np.ndarray:
|
| 235 |
+
"""(P, len(keys)) array of the edge features (pairs i < j): the table's columns, or the per-pair dicts as before."""
|
| 236 |
+
if isinstance(edges, EdgeTable):
|
| 237 |
+
return edges.matrix(keys, dtype)
|
| 238 |
+
pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
|
| 239 |
+
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
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _dir_stats_far(X: np.ndarray, trees: list, bs: list, w1: float, widths: dict) -> tuple:
|
| 243 |
+
"""Approximate _dir_stats (block decimation of PRIOR_SCHEME.md 14.3.1): blocks of k consecutive samples of a whose first
|
| 244 |
+
sample is farther than d_far from b are represented by that sample with weight k (the last block by its size). Distances
|
| 245 |
+
per row (far representatives, then the near samples), statistics for the whole chunk at once (weighted sums)."""
|
| 246 |
+
k, r = FAR_DECIMATION["k"], FAR_DECIMATION["d_far"]
|
| 247 |
+
rep = np.arange(0, len(X), k)
|
| 248 |
+
size = np.diff(np.r_[rep, len(X)])
|
| 249 |
+
nb = len(bs)
|
| 250 |
+
Xr = X[rep]
|
| 251 |
+
ds, ws, rows = [], [], []
|
| 252 |
+
for row, b in enumerate(bs):
|
| 253 |
+
d_rep = _dist(trees[b], Xr)
|
| 254 |
+
far = d_rep > r
|
| 255 |
+
if far.all():
|
| 256 |
+
d, wq = d_rep, size.astype(float)
|
| 257 |
+
else:
|
| 258 |
+
near = np.repeat(~far, size)
|
| 259 |
+
d = np.r_[d_rep[far], _dist(trees[b], X[near])]
|
| 260 |
+
wq = np.r_[size[far].astype(float), np.ones(int(near.sum()))]
|
| 261 |
+
ds.append(d)
|
| 262 |
+
ws.append(wq)
|
| 263 |
+
rows.append(np.full(len(d), row))
|
| 264 |
+
d, wq, rid = np.concatenate(ds), np.concatenate(ws), np.concatenate(rows)
|
| 265 |
+
starts = np.r_[0, np.cumsum([len(x) for x in ds])[:-1]]
|
| 266 |
+
dmin = np.minimum.reduceat(d, starts)
|
| 267 |
+
kb = np.searchsorted(_EDGES_HI, d, side="right")
|
| 268 |
+
cnt = np.rint(np.bincount(rid * 12 + kb, weights=wq, minlength=12 * nb)).astype(np.int64).reshape(nb, 12)[:, 1:11]
|
| 269 |
+
dd = np.maximum(d, 0.05)
|
| 270 |
+
mom = np.stack([np.bincount(rid, weights=STEP_UM * wq * dd ** (-p), minlength=nb) for p in MOMENTS], 1)
|
| 271 |
+
w2 = np.array([widths[b] for b in bs])[rid]
|
| 272 |
+
if np.isinf(w1):
|
| 273 |
+
mm = dd / (dd + w2)
|
| 274 |
+
elif np.isinf(w2).any():
|
| 275 |
+
mm = dd / (dd + w1)
|
| 276 |
+
else:
|
| 277 |
+
mm = dd * (dd + w1 + w2) / ((dd + w1) * (dd + w2))
|
| 278 |
+
cps = np.bincount(rid, weights=STEP_UM * wq * _kratio(mm), minlength=nb)
|
| 279 |
+
return dmin, cnt, mom, cps
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _pmap(fn, items: list, threads: int) -> list:
|
| 283 |
+
if threads < 2 or len(items) < 2:
|
| 284 |
+
return [fn(x) for x in items]
|
| 285 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 286 |
+
|
| 287 |
+
with ThreadPoolExecutor(threads, thread_name_prefix="tlsq-edges") as ex:
|
| 288 |
+
return list(ex.map(fn, items))
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
# Optional persistent cache (exact): per-body node features and per-direction pair statistics, keyed by the body's region
|
| 292 |
+
# (WKB) and role, under a key of this code, the parameters and the machine / library versions (a value is reused only where
|
| 293 |
+
# this machine would recompute it bit for bit). Off unless TLSQ_EMBED_CACHE (or EMBED_CACHE["dir"]) names a directory.
|
| 294 |
+
EMBED_CACHE: dict = {"dir": os.environ.get("TLSQ_EMBED_CACHE") or None}
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _code_key() -> str:
|
| 298 |
+
import platform
|
| 299 |
+
|
| 300 |
+
import scipy
|
| 301 |
+
|
| 302 |
+
h = hashlib.sha256()
|
| 303 |
+
for f in (__file__, _geometry.__file__):
|
| 304 |
+
h.update(Path(f).read_bytes())
|
| 305 |
+
h.update(repr((platform.machine(), platform.system(), np.__version__, scipy.__version__, shapely.__version__, STEP_UM,
|
| 306 |
+
SEP_EDGES_UM.tolist(), MOMENTS, TREE_LEAFSIZE, TOKEN_VARIANT["name"], EMBED_MODE["mode"],
|
| 307 |
+
NN_KERNEL["on"])).encode())
|
| 308 |
+
return h.hexdigest()[:24]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def body_keys(scene: Scene) -> list:
|
| 312 |
+
return [hashlib.sha256(c.role.encode() + shapely.to_wkb(region(scene, i))).hexdigest()[:32]
|
| 313 |
+
for i, c in enumerate(scene.conductors)]
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class _Cache:
|
| 317 |
+
def __init__(self, root):
|
| 318 |
+
self.d = Path(root) / _code_key()
|
| 319 |
+
for sub in ("dir", "node"):
|
| 320 |
+
(self.d / sub).mkdir(parents=True, exist_ok=True)
|
| 321 |
+
|
| 322 |
+
def _put(self, path: Path, write):
|
| 323 |
+
tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
| 324 |
+
with open(tmp, "wb") as fh:
|
| 325 |
+
write(fh)
|
| 326 |
+
os.replace(tmp, path)
|
| 327 |
+
|
| 328 |
+
def nodes(self, keys: list) -> dict:
|
| 329 |
+
out = {}
|
| 330 |
+
for i, k in enumerate(keys):
|
| 331 |
+
p = self.d / "node" / f"{k}.pkl"
|
| 332 |
+
if p.exists():
|
| 333 |
+
out[i] = pickle.loads(p.read_bytes())
|
| 334 |
+
return out
|
| 335 |
+
|
| 336 |
+
def put_node(self, key: str, f: dict):
|
| 337 |
+
self._put(self.d / "node" / f"{key}.pkl", lambda fh: pickle.dump(f, fh, protocol=5))
|
| 338 |
+
|
| 339 |
+
def rows(self, ka: str):
|
| 340 |
+
p = self.d / "dir" / f"{ka}.npz"
|
| 341 |
+
if not p.exists():
|
| 342 |
+
return None
|
| 343 |
+
z = np.load(p)
|
| 344 |
+
return {str(k): r for r, k in enumerate(z["keys"])}, z["dmin"], z["cnt"], z["mom"], z["cps"]
|
| 345 |
+
|
| 346 |
+
def put_rows(self, ka: str, keys: list, dmin, cnt, mom, cps):
|
| 347 |
+
old = self.rows(ka)
|
| 348 |
+
if old is not None:
|
| 349 |
+
idx, *arr = old
|
| 350 |
+
ks = set(keys)
|
| 351 |
+
extra = [r for k, r in idx.items() if k not in ks]
|
| 352 |
+
keys = list(keys) + [k for k, r in idx.items() if k not in ks]
|
| 353 |
+
dmin, cnt, mom, cps = (np.concatenate([x, y[extra]]) for x, y in zip((dmin, cnt, mom, cps), arr))
|
| 354 |
+
self._put(self.d / "dir" / f"{ka}.npz",
|
| 355 |
+
lambda fh: np.savez(fh, keys=np.array(keys), dmin=dmin, cnt=cnt, mom=mom, cps=cps))
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def trim(self):
|
| 359 |
+
"""Size bound (TLSQ_EMBED_CACHE_MB): the least recently written entries are removed down to 80 % of the bound."""
|
| 360 |
+
mb = os.environ.get("TLSQ_EMBED_CACHE_MB")
|
| 361 |
+
if not mb:
|
| 362 |
+
return
|
| 363 |
+
lim = float(mb) * 2**20
|
| 364 |
+
files = [e for sub in ("dir", "node") for e in os.scandir(self.d / sub) if e.is_file()]
|
| 365 |
+
tot = sum(e.stat().st_size for e in files)
|
| 366 |
+
if tot <= lim:
|
| 367 |
+
return
|
| 368 |
+
for e in sorted(files, key=lambda e: e.stat().st_mtime):
|
| 369 |
+
if tot <= 0.8 * lim:
|
| 370 |
+
break
|
| 371 |
+
try:
|
| 372 |
+
tot -= e.stat().st_size
|
| 373 |
+
os.remove(e.path)
|
| 374 |
+
except OSError:
|
| 375 |
+
pass
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _cache():
|
| 379 |
+
return _Cache(EMBED_CACHE["dir"]) if EMBED_CACHE["dir"] else None
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def shape_classes(scene: Scene, bpts: dict | None = None) -> tuple:
|
| 383 |
+
"""Translation classes of the signal bodies (numex mode): class id per conductor (-1 = ground, its own class) from the
|
| 384 |
+
coordinates relative to the bounding-box corner rounded to 1e-6 um and the ring structure, and, with bpts, from the
|
| 385 |
+
boundary samples relative to that corner rounded to 1e-9 um (a translated copy can get one sample more or fewer when a
|
| 386 |
+
ring length is a multiple of the step); integer origins (1e-6 um)."""
|
| 387 |
+
ids, cid, org = {}, np.full(scene.n, -1), np.zeros((scene.n, 2), np.int64)
|
| 388 |
+
for i, c in enumerate(scene.conductors):
|
| 389 |
+
if c.role == "ground":
|
| 390 |
+
continue
|
| 391 |
+
g = region(scene, i)
|
| 392 |
+
o = np.array(g.bounds[:2])
|
| 393 |
+
rings = [len(r.coords) for q in getattr(g, "geoms", [g]) for r in (q.exterior, *q.interiors)]
|
| 394 |
+
h = hashlib.sha1(repr((c.role, g.geom_type, rings)).encode() + (np.round(shapely.get_coordinates(g) - o, 6) + 0.0).tobytes())
|
| 395 |
+
if bpts is not None:
|
| 396 |
+
h.update((np.round(bpts[i] - o, 9) + 0.0).tobytes())
|
| 397 |
+
cid[i] = ids.setdefault(h.hexdigest(), len(ids))
|
| 398 |
+
org[i] = np.rint(o * 1e6).astype(np.int64)
|
| 399 |
+
return cid, org
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def node_features_all(scene: Scene, keys: list | None = None) -> list:
|
| 403 |
+
"""[node_features(scene, i) for every conductor], threads over the conductors, reusing the persistent cache (numex:
|
| 404 |
+
once per translation class)."""
|
| 405 |
+
c = _cache()
|
| 406 |
+
keys = keys if keys is not None or c is None else body_keys(scene)
|
| 407 |
+
hit = c.nodes(keys) if c else {}
|
| 408 |
+
miss = [i for i in range(scene.n) if i not in hit]
|
| 409 |
+
rep = {}
|
| 410 |
+
if EMBED_MODE["mode"] == "numex":
|
| 411 |
+
cid = shape_classes(scene)[0]
|
| 412 |
+
first = {}
|
| 413 |
+
rep = {i: first.setdefault(cid[i], i) for i in miss if cid[i] >= 0}
|
| 414 |
+
rep = {i: r for i, r in rep.items() if r != i}
|
| 415 |
+
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())))
|
| 416 |
+
new.update({i: dict(new[r]) for i, r in rep.items()})
|
| 417 |
+
if c:
|
| 418 |
+
for i, f in new.items():
|
| 419 |
+
c.put_node(keys[i], f)
|
| 420 |
+
c.trim()
|
| 421 |
+
return [hit[i] if i in hit else new[i] for i in range(scene.n)]
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def edge_features_all(scene: Scene, bpts: dict, widths: dict, keys: list | None = None) -> dict:
|
| 425 |
+
"""{(i, j): edge_features(scene, i, j, bpts, widths)} for every pair i < j, bit-identical, batched: one k-d tree per
|
| 426 |
+
conductor, every direction a -> b as rows of one distance array per (a, chunk of b), threads over the chunks (the
|
| 427 |
+
queries and ufuncs release the GIL); directions found in the persistent cache are not recomputed."""
|
| 428 |
+
n = scene.n
|
| 429 |
+
pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
|
| 430 |
+
if TOKEN_VARIANT["name"] != "exact" or n < 2:
|
| 431 |
+
return {(i, j): edge_features(scene, i, j, bpts, widths) for i, j in pairs}
|
| 432 |
+
th = _nthreads()
|
| 433 |
+
DM, CP = np.empty((n, n)), np.empty((n, n))
|
| 434 |
+
CN, MO = np.empty((n, n, 10), np.int64), np.empty((n, n, len(MOMENTS)))
|
| 435 |
+
c = _cache() if not FAR_DECIMATION["k"] else None
|
| 436 |
+
if c and keys is None:
|
| 437 |
+
keys = body_keys(scene)
|
| 438 |
+
todo = {a: [b for b in range(n) if b != a] for a in range(n)}
|
| 439 |
+
if c:
|
| 440 |
+
for a in range(n):
|
| 441 |
+
got = c.rows(keys[a])
|
| 442 |
+
if got is None:
|
| 443 |
+
continue
|
| 444 |
+
idx, dm, cn, mo, cp = got
|
| 445 |
+
have = [b for b in todo[a] if keys[b] in idx]
|
| 446 |
+
r = [idx[keys[b]] for b in have]
|
| 447 |
+
DM[a, have], CN[a, have], MO[a, have], CP[a, have] = dm[r], cn[r], mo[r], cp[r]
|
| 448 |
+
todo[a] = [b for b in todo[a] if keys[b] not in idx]
|
| 449 |
+
share = None
|
| 450 |
+
if EMBED_MODE["mode"] == "numex":
|
| 451 |
+
cid, org = shape_classes(scene, bpts)
|
| 452 |
+
A, B = np.nonzero((cid[:, None] >= 0) & (cid[None, :] >= 0) & ~np.eye(n, dtype=bool))
|
| 453 |
+
K = np.c_[cid[A], cid[B], org[B] - org[A]]
|
| 454 |
+
_, first, inv = np.unique(K, axis=0, return_index=True, return_inverse=True)
|
| 455 |
+
R = first[inv.ravel()]
|
| 456 |
+
share = (A, B, A[R], B[R])
|
| 457 |
+
drop = np.zeros((n, n), bool)
|
| 458 |
+
drop[A[R != np.arange(len(A))], B[R != np.arange(len(A))]] = True
|
| 459 |
+
todo = {a: [b for b in bs if not drop[a, b]] for a, bs in todo.items()}
|
| 460 |
+
tasks = []
|
| 461 |
+
for a, bs in todo.items():
|
| 462 |
+
sig = [b for b in bs if not np.isinf(widths[b])]
|
| 463 |
+
tasks += [(a, [b]) for b in bs if np.isinf(widths[b])]
|
| 464 |
+
step = max(1, _CHUNK // len(bpts[a]))
|
| 465 |
+
tasks += [(a, sig[k:k + step]) for k in range(0, len(sig), step)]
|
| 466 |
+
tasks.sort(key=lambda t: -len(t[1]) * len(bpts[t[0]]))
|
| 467 |
+
need = sorted({b for _, bs in tasks for b in bs})
|
| 468 |
+
trees = dict(zip(need, _pmap(lambda i: _tree(bpts[i]), need, th)))
|
| 469 |
+
|
| 470 |
+
def run(t):
|
| 471 |
+
a, bs = t
|
| 472 |
+
f = _dir_stats_far if FAR_DECIMATION["k"] else _dir_stats
|
| 473 |
+
DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs] = f(bpts[a], trees, bs, widths[a], widths)
|
| 474 |
+
|
| 475 |
+
_pmap(run, tasks, th)
|
| 476 |
+
if share is not None:
|
| 477 |
+
A, B, RA, RB = share
|
| 478 |
+
DM[A, B], CN[A, B], MO[A, B], CP[A, B] = DM[RA, RB], CN[RA, RB], MO[RA, RB], CP[RA, RB]
|
| 479 |
+
if c:
|
| 480 |
+
for a in {t[0] for t in tasks}:
|
| 481 |
+
bs = [b for b in range(n) if b != a]
|
| 482 |
+
c.put_rows(keys[a], [keys[b] for b in bs], DM[a, bs], CN[a, bs], MO[a, bs], CP[a, bs])
|
| 483 |
+
c.trim()
|
| 484 |
+
return _assemble(scene, DM, CN, MO, CP)
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def _assemble(scene: Scene, DM, CN, MO, CP) -> dict:
|
| 488 |
+
"""Pair dicts from the per-direction statistics, in edge_features' operation order and key order."""
|
| 489 |
+
n = scene.n
|
| 490 |
+
I, J = np.triu_indices(n, 1)
|
| 491 |
+
dmin = np.minimum(DM[I, J], DM[J, I])
|
| 492 |
+
hist = 0.5 * (STEP_UM * CN[I, J]) + 0.5 * (STEP_UM * CN[J, I])
|
| 493 |
+
mom = 0.5 * MO[I, J] + 0.5 * MO[J, I]
|
| 494 |
+
cps = 0.5 * CP[I, J] + 0.5 * CP[J, I]
|
| 495 |
+
gnd = np.array([c.role == "ground" for c in scene.conductors])
|
| 496 |
+
cols = {"is_ground_pair": (gnd[I] | gnd[J]).astype(float), "log_dmin": np.log(np.maximum(dmin, 1e-9))}
|
| 497 |
+
sep = np.log1p(hist)
|
| 498 |
+
for k in range(sep.shape[1]):
|
| 499 |
+
cols[f"sep_{k:02d}"] = sep[:, k]
|
| 500 |
+
lm = np.log(np.maximum(mom, 1e-9))
|
| 501 |
+
for k, p in enumerate(MOMENTS):
|
| 502 |
+
cols[f"mom_{p:g}"] = lm[:, k]
|
| 503 |
+
cols["log_cps"] = np.log(np.maximum(cps, 1e-9))
|
| 504 |
+
if EDGE_TABLE["on"]:
|
| 505 |
+
return EdgeTable(n, {**cols, "_cps": cps}, ("_cps",))
|
| 506 |
+
keys = list(cols)
|
| 507 |
+
rows = zip(*[cols[k].tolist() for k in keys], list(cps))
|
| 508 |
+
return {(i, j): {**dict(zip(keys, r[:-1])), "_cps": r[-1]} for i, j, r in zip(I.tolist(), J.tolist(), rows)}
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def global_features(scene: Scene) -> dict:
|
| 512 |
+
st = scene.stack
|
| 513 |
+
n_sig = sum(c.role == "signal" for c in scene.conductors)
|
| 514 |
+
return {"n_metal_layers": float(st["n_metal_layers"]), "log_metal_t": _log(st["metal_thickness_um"]),
|
| 515 |
+
"log_substrate_t": _log(st["substrate_thickness_um"]), "eps_eff": (st["substrate_eps_r"] + 1) / 2,
|
| 516 |
+
"n_signal": float(n_sig), "log_chip_area": _log(scene.chip.area),
|
| 517 |
+
"log_pocket_area": _log(scene.pocket.area)}
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def boundary_points(scene: Scene) -> tuple[dict, dict]:
|
| 521 |
+
def one(i):
|
| 522 |
+
g = region(scene, i)
|
| 523 |
+
return sample_boundary(g, STEP_UM), np.inf if scene.conductors[i].role == "ground" else 2 * g.area / g.length
|
| 524 |
+
|
| 525 |
+
out = _pmap(one, list(range(scene.n)), _nthreads())
|
| 526 |
+
return {i: p for i, (p, _) in enumerate(out)}, {i: w for i, (_, w) in enumerate(out)}
|
src/squadds/ml/capacitance/_core/_tlsq/uge/graph.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scene graph (nodes = conductors, edges = all conductor pairs) and its permutation-invariant pooled vector."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from .blocks import EdgeTable, _cache, body_keys, boundary_points, edge_features_all, global_features, node_features_all
|
| 8 |
+
from .proxies import Proxy
|
| 9 |
+
from .scene import Scene
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def scene_graph(scene: Scene, proxy: Proxy | None = None) -> dict:
|
| 13 |
+
keys = body_keys(scene) if _cache() else None
|
| 14 |
+
bpts, widths = boundary_points(scene)
|
| 15 |
+
nodes = node_features_all(scene, keys)
|
| 16 |
+
edges = edge_features_all(scene, bpts, widths, keys)
|
| 17 |
+
# shielding: share of each endpoint's total geometric coupling carried by this edge
|
| 18 |
+
table = isinstance(edges, EdgeTable)
|
| 19 |
+
if table:
|
| 20 |
+
edges = _shares_table(scene.n, edges)
|
| 21 |
+
if proxy is not None:
|
| 22 |
+
edges = {p: edges[p] for p in edges}
|
| 23 |
+
tot = None if table else np.zeros(scene.n)
|
| 24 |
+
for (i, j), f in (edges.items() if tot is not None else ()):
|
| 25 |
+
tot[i] += f["_cps"]
|
| 26 |
+
tot[j] += f["_cps"]
|
| 27 |
+
for (i, j), f in (edges.items() if tot is not None else ()):
|
| 28 |
+
si, sj = f["_cps"] / max(tot[i], 1e-12), f["_cps"] / max(tot[j], 1e-12)
|
| 29 |
+
f["share_mean"], f["share_absdiff"] = 0.5 * (si + sj), abs(si - sj)
|
| 30 |
+
g = {"names": scene.names(), "global": global_features(scene), "nodes": nodes, "edges": edges}
|
| 31 |
+
if proxy is not None:
|
| 32 |
+
px = proxy.compute(scene, edges)
|
| 33 |
+
for i, v in px["node"].items():
|
| 34 |
+
nodes[i].update({f"proxy_{k}": x for k, x in v.items()})
|
| 35 |
+
for e, v in px["edge"].items():
|
| 36 |
+
edges[e].update({f"proxy_{k}": x for k, x in v.items()})
|
| 37 |
+
g["global"].update({f"proxy_{k}": x for k, x in px["global"].items()})
|
| 38 |
+
if "matrix" in px:
|
| 39 |
+
g["proxy_matrix"] = px["matrix"]
|
| 40 |
+
for f in (edges.values() if tot is not None else ()):
|
| 41 |
+
f.pop("_cps")
|
| 42 |
+
return g
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _shares_table(n: int, E: EdgeTable) -> EdgeTable:
|
| 46 |
+
"""The shares of scene_graph on an EdgeTable: the same additions in the same order (np.add.at is sequential)."""
|
| 47 |
+
I, J = np.triu_indices(n, 1)
|
| 48 |
+
cps = E.cols["_cps"]
|
| 49 |
+
tot = np.zeros(n)
|
| 50 |
+
np.add.at(tot, np.c_[I, J].ravel(), np.repeat(cps, 2))
|
| 51 |
+
si, sj = cps / np.maximum(tot[I], 1e-12), cps / np.maximum(tot[J], 1e-12)
|
| 52 |
+
return E.with_cols({"share_mean": 0.5 * (si + sj), "share_absdiff": np.abs(si - sj)}, drop=("_cps",),
|
| 53 |
+
npcols=("share_mean", "share_absdiff"))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def pooled_vector(g: dict) -> dict:
|
| 57 |
+
"""Fixed-length universal vector for any number of conductors: global block, the ground node, sum/mean/max over
|
| 58 |
+
signal nodes, and sum/mean/max over signal-signal and signal-ground edges."""
|
| 59 |
+
out = {f"global.{k}": v for k, v in g["global"].items()}
|
| 60 |
+
roles = ["ground" if n["role_ground"] else "signal" for n in g["nodes"]]
|
| 61 |
+
keys = [k for k in g["nodes"][0] if k != "role_ground"]
|
| 62 |
+
gi = roles.index("ground")
|
| 63 |
+
out.update({f"ground.{k}": g["nodes"][gi][k] for k in keys})
|
| 64 |
+
S = np.array([[n[k] for k in keys] for n, r in zip(g["nodes"], roles) if r == "signal"])
|
| 65 |
+
for agg, fn in (("mean", np.mean), ("max", np.max), ("min", np.min)):
|
| 66 |
+
out.update({f"signal.{agg}.{k}": v for k, v in zip(keys, fn(S, 0))})
|
| 67 |
+
ekeys = [k for k in next(iter(g["edges"].values())) if k != "is_ground_pair"]
|
| 68 |
+
for typ, flag in (("ss", 0.0), ("sg", 1.0)):
|
| 69 |
+
E = np.array([[f[k] for k in ekeys] for f in g["edges"].values() if f["is_ground_pair"] == flag])
|
| 70 |
+
if len(E) == 0:
|
| 71 |
+
E = np.full((1, len(ekeys)), np.nan)
|
| 72 |
+
for agg, fn in (("mean", np.nanmean), ("max", np.nanmax), ("min", np.nanmin)):
|
| 73 |
+
out.update({f"edge_{typ}.{agg}.{k}": v for k, v in zip(ekeys, fn(E, 0))})
|
| 74 |
+
return out
|
src/squadds/ml/capacitance/_core/_tlsq/uge/localtok.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local, window-invariant context tokens (PRIOR_SCHEME.md 14.5 E4; replace the chip / pocket areas): for every signal
|
| 2 |
+
conductor and radius R, the fractions of its surrounding annulus (conductor buffered by R, minus the conductor) that are
|
| 3 |
+
ground metal, other-conductor metal and etched chip; the rest of the annulus lies outside the chip (no metal). Pair
|
| 4 |
+
tokens = mean over the pair's signal ends (a ground pair: its signal end). Identical copy: tlsq_infer/localtok.py."""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import shapely
|
| 10 |
+
|
| 11 |
+
from ..geometry import sample_boundary
|
| 12 |
+
from ..embed.proxy import _nthreads
|
| 13 |
+
from .blocks import MOMENTS, SEP_EDGES_UM, STEP_UM, EdgeTable, _dist, _kratio, _pmap, _tree
|
| 14 |
+
|
| 15 |
+
RADII_UM = (50.0, 150.0, 400.0)
|
| 16 |
+
KEYS = [f"lt_{k}{int(r)}" for r in RADII_UM for k in ("g", "o", "e")]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def node_tokens(scene) -> np.ndarray:
|
| 20 |
+
"""(n, len(KEYS)) per conductor (ground row = NaN)."""
|
| 21 |
+
conds = scene.conductors
|
| 22 |
+
n = len(conds)
|
| 23 |
+
G = next(c.geom for c in conds if c.role == "ground")
|
| 24 |
+
sig = [k for k, c in enumerate(conds) if c.role != "ground"]
|
| 25 |
+
tree = shapely.STRtree([conds[k].geom for k in sig])
|
| 26 |
+
out = np.full((n, len(KEYS)), np.nan)
|
| 27 |
+
|
| 28 |
+
def one(k):
|
| 29 |
+
g = conds[k].geom
|
| 30 |
+
vals = []
|
| 31 |
+
for R in RADII_UM:
|
| 32 |
+
ring = g.buffer(R, quad_segs=4).difference(g)
|
| 33 |
+
A = ring.area
|
| 34 |
+
box = ring.bounds
|
| 35 |
+
gm = shapely.intersection(shapely.clip_by_rect(G, *box), ring).area
|
| 36 |
+
near = [sig[i] for i in tree.query(ring, predicate="intersects") if sig[i] != k]
|
| 37 |
+
om = shapely.intersection(shapely.union_all([conds[i].geom for i in near]), ring).area if near else 0.0
|
| 38 |
+
inchip = shapely.intersection(scene.chip, ring).area
|
| 39 |
+
vals += [gm / A, om / A, max(inchip - gm - om, 0.0) / A]
|
| 40 |
+
return vals
|
| 41 |
+
|
| 42 |
+
for k, vals in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely releases the GIL
|
| 43 |
+
out[k] = vals
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
LG_R_UM = 100.0
|
| 48 |
+
TOK = ["log_dmin"] + [f"sep_{k:02d}" for k in range(10)] + ["mom_0.5", "mom_1", "mom_2", "log_cps"]
|
| 49 |
+
LG_KEYS = [f"lg_{k}" for k in TOK]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def ground_tokens(scene) -> np.ndarray:
|
| 53 |
+
"""(n, len(LG_KEYS)) per signal conductor: the ground-pair tokens of blocks.edge_features (separation spectrum, minimum
|
| 54 |
+
gap, coupling moments, coplanar-strip coupling) from the ground-edge samples within LG_R_UM of the conductor only
|
| 55 |
+
(fixed radius: independent of the ground window)."""
|
| 56 |
+
conds = scene.conductors
|
| 57 |
+
out = np.full((len(conds), len(LG_KEYS)), np.nan)
|
| 58 |
+
|
| 59 |
+
def one(k):
|
| 60 |
+
g = conds[k].geom
|
| 61 |
+
b = g.bounds
|
| 62 |
+
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)
|
| 63 |
+
pj = sample_boundary(g, STEP_UM)
|
| 64 |
+
pg = sample_boundary(P, STEP_UM) if not P.is_empty else np.zeros((0, 2))
|
| 65 |
+
if len(pg):
|
| 66 |
+
pg = pg[_dist(_tree(pj), pg) < LG_R_UM] # drops the clip-box edges (>= LG_R_UM away) and the far ground
|
| 67 |
+
if not len(pg):
|
| 68 |
+
return None
|
| 69 |
+
wj = 2 * g.area / g.length
|
| 70 |
+
hist = np.zeros(len(SEP_EDGES_UM) - 1)
|
| 71 |
+
mom = np.zeros(len(MOMENTS))
|
| 72 |
+
cps, dmin = 0.0, np.inf
|
| 73 |
+
for a_, b_ in ((pj, pg), (pg, pj)):
|
| 74 |
+
d = _dist(_tree(b_), a_)
|
| 75 |
+
dmin = min(dmin, d.min())
|
| 76 |
+
hist += 0.5 * np.histogram(d, bins=SEP_EDGES_UM, weights=np.full(len(d), STEP_UM))[0]
|
| 77 |
+
dd = np.maximum(d, 0.05)
|
| 78 |
+
mom += 0.5 * np.array([np.sum(STEP_UM * dd ** (-p)) for p in MOMENTS])
|
| 79 |
+
cps += 0.5 * np.sum(STEP_UM * _kratio(dd / (dd + wj)))
|
| 80 |
+
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))]
|
| 81 |
+
|
| 82 |
+
sig = [k for k, c in enumerate(conds) if c.role != "ground"]
|
| 83 |
+
for k, v in zip(sig, _pmap(one, sig, _nthreads())): # threads: shapely and the k-d tree queries release the GIL
|
| 84 |
+
if v is not None:
|
| 85 |
+
out[k] = v
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def add_tokens(scene, row: dict) -> dict:
|
| 90 |
+
"""Row (scene graph dict) with the KEYS added to every edge (shallow copy)."""
|
| 91 |
+
return add_from_tokens(row, node_tokens(scene), ground_tokens(scene), [c.role != "ground" for c in scene.conductors])
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def add_from_tokens(row: dict, T: np.ndarray, Lg: np.ndarray, sig) -> dict:
|
| 95 |
+
"""Edges + KEYS (mean over the signal ends) + LG_KEYS (ground pairs: the fixed-radius tokens of the signal end; other
|
| 96 |
+
pairs: their own tokens, unchanged)."""
|
| 97 |
+
sig = np.asarray(sig)
|
| 98 |
+
if isinstance(row["edges"], EdgeTable):
|
| 99 |
+
return {**row, "edges": _add_table(row["edges"], T, Lg, sig)}
|
| 100 |
+
edges = {}
|
| 101 |
+
for (i, j), f in row["edges"].items():
|
| 102 |
+
ends = [e for e in (i, j) if sig[e]]
|
| 103 |
+
new = {k: float(x) for k, x in zip(KEYS, T[ends].mean(0))}
|
| 104 |
+
if len(ends) == 1 and np.all(np.isfinite(Lg[ends[0]])):
|
| 105 |
+
new.update({k: float(x) for k, x in zip(LG_KEYS, Lg[ends[0]])})
|
| 106 |
+
else:
|
| 107 |
+
new.update({f"lg_{k}": float(f[k]) for k in TOK})
|
| 108 |
+
edges[(i, j)] = {**f, **new}
|
| 109 |
+
return {**row, "edges": edges}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _add_table(E: EdgeTable, T: np.ndarray, Lg: np.ndarray, sig: np.ndarray) -> EdgeTable:
|
| 113 |
+
"""add_from_tokens on an EdgeTable, per column with the same arithmetic: the mean over two signal ends is (a + b) / 2
|
| 114 |
+
(numpy's mean of two rows), over one end the row itself."""
|
| 115 |
+
I, J = np.triu_indices(E.n, 1)
|
| 116 |
+
sI, sJ = sig[I], sig[J]
|
| 117 |
+
both, oi, oj = sI & sJ, sI & ~sJ, ~sI & sJ
|
| 118 |
+
M = np.full((len(I), len(KEYS)), np.nan)
|
| 119 |
+
M[both] = (T[I[both]] + T[J[both]]) / 2
|
| 120 |
+
M[oi], M[oj] = T[I[oi]], T[J[oj]]
|
| 121 |
+
end = np.where(oi, I, J)
|
| 122 |
+
use = (oi | oj) & np.isfinite(Lg[end]).all(1)
|
| 123 |
+
new = {k: M[:, c] for c, k in enumerate(KEYS)}
|
| 124 |
+
for c, k in enumerate(TOK):
|
| 125 |
+
new[f"lg_{k}"] = np.where(use, Lg[end][:, c], E.cols[k])
|
| 126 |
+
return E.with_cols(new)
|