analog-circuits-sky130 / example_simulate.py
pphilip's picture
Fix netlist_json parser (params + comment filter); correct README counts; reproducibility example now positive-gain
5a859d4 verified
#!/usr/bin/env python3
"""Reproduce any row of `pphilip/analog-circuits-sky130` with ngspice.
Usage
-----
python example_simulate.py # first converged row of train
python example_simulate.py --split test --row 42
python example_simulate.py --circuit-id analoggym_amp_yan_az_pin_3_s015
python example_simulate.py --row 0 --print-spice # dump the reconstructed SPICE
Every row of the `with_testbench` config carries the exact, ngspice-ready
SPICE that produced its `metrics`. Reproducing a row is:
1. Load the row.
2. Substitute `{{SKY130_LIB}}` with your local SKY130 `.lib` path.
3. Run ngspice on the result.
4. Parse the `.meas` output.
Prerequisites
-------------
pip install datasets
# Install ngspice (v46+):
# brew install ngspice (macOS)
# apt install ngspice (Debian/Ubuntu)
# (or build from source: http://ngspice.sourceforge.net/)
# Install the SkyWater SKY130 PDK (Apache 2.0):
pip install volare && volare fetch --pdk sky130
# Point SKY130_LIB at the combined/continuous lib:
export SKY130_LIB="$(volare show sky130)/sky130A/libs.tech/combined/continuous/sky130.lib.spice"
"""
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
# ---------------------------------------------------------------------------
# Run ngspice + parse .meas output
# ---------------------------------------------------------------------------
def run_ngspice(spice_text: str) -> tuple[dict[str, float], str]:
"""Run ngspice in batch mode. Returns (parsed_metrics, raw_log).
ngspice's `ngbehavior=hs` mode lowercases every token, so `.meas`
labels come back as `dc_gain_db` even if the SPICE source wrote
`dc_gain_dB`. Parsing is case-insensitive.
"""
if shutil.which("ngspice") is None:
raise RuntimeError(
"ngspice not found on PATH. Install it (see prerequisites above)."
)
with tempfile.TemporaryDirectory() as d:
tb = Path(d) / "tb.spice"
tb.write_text(spice_text)
r = subprocess.run(
["ngspice", "-b", str(tb)],
capture_output=True, text=True, timeout=60,
)
log = r.stdout + r.stderr
# `.meas` output looks like: dc_gain_db = -3.07410e+01 at= 1.00000e+00
metrics: dict[str, float] = {}
for line in log.splitlines():
parts = line.strip().split("=", 1)
if len(parts) != 2:
continue
key = parts[0].strip().lower()
if not key or " " in key:
continue
# Take the first numeric token after `=`
for tok in parts[1].split():
try:
metrics[key] = float(tok)
break
except ValueError:
continue
return metrics, log
def first_reproducible_row(ds) -> int:
"""Return the index of the first converged row with a non-empty testbench_spice.
`failed` split rows can still carry a testbench_spice (the sim was attempted
but didn't converge), so testbench-presence alone isn't enough — we also
require `converged=True` so the shipped `metrics` are meaningful.
"""
for i in range(len(ds)):
row = ds[i]
if row.get("converged") and row.get("testbench_spice"):
return i
raise RuntimeError("no converged row with testbench_spice found in this split")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--split", default="train",
choices=["train", "validation", "test", "failed"])
ap.add_argument("--row", type=int, default=None,
help="Row index within the split (default: first usable row)")
ap.add_argument("--circuit-id", default=None,
help="Alternative to --row: look up by exact circuit_id")
ap.add_argument("--print-spice", action="store_true",
help="Print the reconstructed SPICE and exit without running")
args = ap.parse_args()
from datasets import load_dataset
print(f"Loading pphilip/analog-circuits-sky130 (config: with_testbench, split: {args.split})…")
ds = load_dataset(
"pphilip/analog-circuits-sky130",
"with_testbench",
split=args.split,
)
if args.circuit_id is not None:
idx = None
for i, r in enumerate(ds):
if r["circuit_id"] == args.circuit_id:
idx = i
break
if idx is None:
print(f"circuit_id {args.circuit_id!r} not in split {args.split!r}",
file=sys.stderr)
return 1
elif args.row is not None:
if not 0 <= args.row < len(ds):
print(f"--row {args.row} out of range (split has {len(ds)} rows)",
file=sys.stderr)
return 1
idx = args.row
else:
idx = first_reproducible_row(ds)
row = ds[idx]
shipped = json.loads(row["metrics"]) if row["metrics"] else {}
spice = row["testbench_spice"]
print(f" circuit_id: {row['circuit_id']}")
print(f" topology: {row['topology']} (source: {row['source_dataset']})")
print(f" shipped metric: dc_gain_dB = {shipped.get('dc_gain_dB', 'n/a')} dB")
if not spice:
print("\n ERROR: this row has no testbench_spice (failed-build case).",
file=sys.stderr)
return 1
if args.print_spice:
# Show the SPICE verbatim including the {{SKY130_LIB}} placeholder —
# this path doesn't run ngspice, so a local PDK isn't required.
print("\n--- reconstructed SPICE ---")
print(spice)
return 0
sky130_lib = os.environ.get("SKY130_LIB")
if not sky130_lib or not Path(sky130_lib).exists():
print(
"ERROR: SKY130_LIB env var not set or doesn't point to a valid file.\n"
"Install the PDK: `pip install volare && volare fetch --pdk sky130`\n"
"Then: `export SKY130_LIB=<path to sky130.lib.spice>` "
"(combined/continuous variant).",
file=sys.stderr,
)
return 2
# Swap the portability placeholder for the user's local PDK path.
spice = spice.replace("{{SKY130_LIB}}", sky130_lib)
print("\nRunning ngspice…")
try:
metrics, log = run_ngspice(spice)
except RuntimeError as e:
print(f"ERROR: {e}", file=sys.stderr)
return 3
reproduced = metrics.get("dc_gain_db") # ngspice lowercases output keys
print(f" reproduced: dc_gain_dB = {reproduced} dB")
if reproduced is not None and "dc_gain_dB" in shipped:
delta = abs(reproduced - shipped["dc_gain_dB"])
tag = "✓ bit-exact" if delta < 1e-3 else ("~ within 0.1 dB" if delta < 0.1 else "✗ mismatch")
print(f" delta: {delta:.6f} dB {tag}")
return 0
if __name__ == "__main__":
sys.exit(main())