skill
SPICE Simulation Skills
Public Made by Adomby adom
Pick, run and license the right SPICE simulator from an AI thread: ngspice in the container by default, LTspice and PSpice for TI on a Windows host for vendor models.
← Commit history
Publish 0.2.0
20 files changed
+1373−11
README.md+23−1SKILL.md+14app/adom_spice/analysis.py+59app/adom_spice/engines.py+219app/adom_spice/server.py+314app/bin/adom-spice+135app/examples/tps54202-buck/board_ltspice.cir+49app/examples/tps54202-buck/board_ngspice.cir+53app/examples/tps54202-buck/board_pspice.cir+48app/examples/tps54202-buck/study.json+26app/install.sh+16app/uninstall.sh+8app/web/app.js+141app/web/index.html+42app/web/style.css+62install.sh+3−1package.json+21−4page.json+87−3skills/adom-spice/SKILL.md+50uninstall.sh+3−2README.md+23−1@@ -42,6 +42,27 @@ We do not publish timing or head-to-head numbers for LTspice or PSpice because t | Runs PSpice-encrypted models | no | no | yes | | May back a hosted dashboard | yes | no | no | +## The Adom SPICE dashboard++The pack installs `adom-spice`, a dashboard that runs one study in all three engines and puts the results on one set of axes. ngspice runs in your container; LTspice and PSpice for TI run on your Windows machine through Adom Bridge. Every engine is measured by the same code, and the dashboard tells you whether they agree. When they do not, it names the measurement and the engine that is out of line, which is usually a netlist-translation or model problem worth finding before you build the board.++++It also keeps a ledger of each run: the simulation time (LTspice and PSpice times stay hidden by default, per their licences) and the AI tokens the run cost.++++Ask your AI: *"Simulate the TPS54202 buck in ngspice, LTspice and PSpice for TI with the Adom SPICE dashboard, and tell me whether they agree."* Or drive it yourself:++```bash+adom-spice --ai-thread "buck check" start+adom-spice --ai-thread "buck check" study ~/.adom/adom-spice/examples/tps54202-buck/study.json+adom-spice --ai-thread "buck check" run ngspice ltspice pspice+adom-spice --ai-thread "buck check" show+```++On the example board all three engines agree on all eight measurements (output voltage, ripple, inductor ripple, start-up peak current, time to 95 %, overshoot, undershoot, settling).+ ## Skills in this pack | Skill | Use it for |@@ -54,6 +75,7 @@ We do not publish timing or head-to-head numbers for LTspice or PSpice because t | **spice-vendor-models** | Encrypted models: what runs where, validating a behavioral model, what never to do. | | **spice-portable-netlists** | One netlist for ngspice, LTspice and PSpice; the dialect differences. | | **spice-licensing** | Where each tool may run, hosted dashboards, commercial use, publishing results. |+| **adom-spice** | The dashboard: study format, running engines through the bridge, agreement check, run ledger. | ## Examples @@ -68,4 +90,4 @@ We do not publish timing or head-to-head numbers for LTspice or PSpice because t adom-wiki pkg install adom-spice-skillpack ``` -This installs the main skill and all seven sub-skills into `~/.claude/skills/`.+This installs the main skill, all eight sub-skills and the `adom-spice` dashboard command.
SKILL.md+14@@ -54,6 +54,20 @@ We do not publish timing or head-to-head numbers for LTspice or PSpice: their li | **spice-vendor-models** | Encrypted models: who can run what, how to validate a hand-built model against the vendor model, what never to do. | | **spice-portable-netlists** | Writing one netlist that runs in ngspice, LTspice and PSpice; the dialect differences that bite. | | **spice-licensing** | Licence terms that decide where each tool may run: containers, VMs, hosted dashboards, commercial use, publishing results. |+| **adom-spice** | The dashboard app: run one study in ngspice, LTspice and PSpice for TI, overlay the waveforms, flag where the engines disagree, and log sim time and AI tokens per run. |++## The dashboard++`adom-spice` (installed with this pack) runs a study in all three engines and tells you whether they agree:++```bash+adom-spice --ai-thread "<name>" start+adom-spice --ai-thread "<name>" study ~/.adom/adom-spice/examples/tps54202-buck/study.json+adom-spice --ai-thread "<name>" run ngspice ltspice pspice+adom-spice --ai-thread "<name>" show+```++See **adom-spice** for the study format and the bridge settings. ## Defaults for an AI thread
app/adom_spice/analysis.pyadded+59@@ -0,0 +1,59 @@+"""Resample, measure and compare. Measurements are declared in the study (windows in seconds), so the same+code measures every engine. Agreement = spread of each measurement across engines against a tolerance."""+import numpy as np+++def resample(t, sigs, t0, t1, n):+ o = np.argsort(t, kind='stable'); t = t[o]+ g = np.linspace(t0, t1, n)+ return g, {k: np.interp(g, t, v[o]) for k, v in sigs.items()}+++def measure(t, s, spec):+ """spec: list of {name, signal, kind, from, to, [ref_window], unit, scale}. kinds: mean, pp, max, min,+ overshoot (max in window minus mean of ref window), undershoot (mean of ref minus min in window),+ t_reach (first time signal crosses frac * mean of ref window), settle (last time |s-ref| > band after 'from')."""+ o = np.argsort(t, kind='stable'); t = t[o]; s = {k: v[o] for k, v in s.items()}+ out = {}+ for m in spec:+ x = s[m['signal']]; w = (t >= m.get('from', t[0])) & (t <= m.get('to', t[-1]))+ ref = None+ if 'ref' in m:+ r = (t >= m['ref'][0]) & (t <= m['ref'][1]); ref = float(x[r].mean())+ k = m['kind']+ if k == 'mean': v = x[w].mean()+ elif k == 'pp': v = np.ptp(x[w])+ elif k == 'max': v = x[w].max()+ elif k == 'min': v = x[w].min()+ elif k == 'overshoot': v = x[w].max() - ref+ elif k == 'undershoot': v = ref - x[w].min()+ elif k == 't_reach': v = t[np.argmax(x > m['frac'] * ref)]+ elif k == 'settle':+ idx = np.where(w & (np.abs(x - ref) > m['band']))[0]+ v = (t[idx[-1]] - m['from']) if len(idx) else 0.0+ else: continue+ out[m['name']] = float(v) * m.get('scale', 1.0)+ return out+++def agreement(results, spec, tol):+ """results: {engine: {metric: value}}. Spread = max - min across engines; flagged when it exceeds the+ measurement's abs_tol, or (when it has none) the global relative tolerance times |median|."""+ rows = []+ engines = list(results)+ for m in spec:+ n = m['name']; vals = {e: results[e].get(n) for e in engines if results[e].get(n) is not None}+ if len(vals) < 2:+ rows.append({'metric': n, 'unit': m.get('unit', ''), 'values': vals, 'spread': None, 'ok': None}); continue+ arr = np.array(list(vals.values())); med = float(np.median(arr)); spread = float(arr.max() - arr.min())+ lim = m['abs_tol'] if 'abs_tol' in m else tol['rel'] * abs(med) # a study's own limit wins over the global %+ rows.append({'metric': n, 'unit': m.get('unit', ''), 'label': m.get('label', n), 'values': vals,+ 'spread': spread, 'limit': lim, 'ok': spread <= lim,+ 'outlier': max(vals, key=lambda e: abs(vals[e] - med)) if spread > lim else None})+ return rows+++def waveform_gap(grids, signal, a, b):+ """Max |a-b| of one signal on the common grid (for the 'where do they differ' highlight)."""+ d = np.abs(grids[a][signal] - grids[b][signal]); i = int(np.argmax(d))+ return float(d[i]), i
app/adom_spice/engines.pyadded+219@@ -0,0 +1,219 @@+"""Engine runners. Each returns (t, {signal: array}, wall_seconds, log_text).++ngspice : local, in this container (BSD, hostable).+ltspice : Windows host through Adom Bridge, batch mode (-b), .raw pulled back.+pspice : PSpice for TI on a Windows host through Adom Bridge. It has no batch mode, so the runner+ opens the netlist, maximizes the window, clicks Run on a full-screen capture, polls the+ .out file, then pulls the .PROBE/CSDF text output.+All three read the same study: one netlist per dialect plus a signal map per engine.+"""+import base64, json, os, re, shutil, subprocess, tempfile, time+import numpy as np++NGSPICE = os.environ.get('ADOM_SPICE_NGSPICE', shutil.which('ngspice') or 'ngspice')+for cand in ('/home/adom/spice-tools/ngspice-47/bin/ngspice',):+ if os.path.exists(cand) and 'ADOM_SPICE_NGSPICE' not in os.environ:+ NGSPICE = cand+++class EngineError(Exception):+ pass+++def _bridge(target, thread, verb, args, timeout=600):+ """Call adom-bridge; returns parsed JSON (the CLI prints JSON). Empty target = the primary machine."""+ cmd = ['adom-bridge'] + (['--target', target] if target else []) + ['--ai-thread', thread, verb, json.dumps(args)]+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)+ txt = r.stdout+ i = txt.find('{')+ try:+ return json.loads(txt[i:]) if i >= 0 else {'ok': False, 'error': r.stderr[-400:]}+ except json.JSONDecodeError:+ return {'ok': False, 'error': txt[-400:]}+++def _ps(target, thread, script, reason, timeout=600):+ args = {'interpreter': 'powershell', 'scriptB64': base64.b64encode(script.encode()).decode(),+ 'timeoutSeconds': timeout, 'reason': reason}+ d = _bridge(target, thread, 'run_script', args, timeout=timeout + 60)+ return d.get('stdout', '') or '', d+++def _strip_control(text):+ return re.sub(r'(?is)^\.control.*?^\.endc\s*$', '', text, flags=re.M)+++_HOSTENV = {}+++def host_paths(settings, thread):+ """Resolve empty path settings on the Windows host once (USERPROFILE / LOCALAPPDATA)."""+ target = settings['bridgeTarget']+ if target not in _HOSTENV:+ out, _ = _ps(target, thread, 'Write-Output ("UP=" + $env:USERPROFILE); Write-Output ("LA=" + $env:LOCALAPPDATA)', 'adom-spice: read the host profile paths', 60)+ up = re.search(r'UP=(.+)', out); la = re.search(r'LA=(.+)', out)+ if not up: raise EngineError('could not read the Windows host profile path through Adom Bridge')+ _HOSTENV[target] = (up.group(1).strip().replace('/', '\\'), la.group(1).strip().replace('/', '\\'))+ up, la = _HOSTENV[target]+ s = dict(settings)+ s['windowsWorkDir'] = settings['windowsWorkDir'] or up + '\\Downloads\\adom-spice'+ s['ltspiceExe'] = settings['ltspiceExe'] or la + '\\Programs\\ADI\\LTspice\\LTspice.exe'+ return s+++# ---------------------------------------------------------------- ngspice+def run_ngspice(study, workdir, thread, settings, log):+ src = study['netlists']['ngspice']+ sig = study['signals']['ngspice'] # e.g. {"vout": "v(vout)", "il": "i(Vsense)"}+ base = _strip_control(open(src).read())+ base = re.sub(r'(?im)^\.end\s*$', '', base)+ out = os.path.join(workdir, 'ngspice.txt')+ cir = os.path.join(workdir, 'ngspice.cir')+ names = list(sig.keys())+ open(cir, 'w').write(base + '\n.control\nset wr_singlescale\nrun\nwrdata ' + out + ' ' ++ ' '.join(sig[n] for n in names) + '\n.endc\n.end\n')+ log(f'ngspice: {NGSPICE} -b {os.path.basename(cir)}')+ t0 = time.time()+ r = subprocess.run(['nice', '-n', '10', NGSPICE, '-b', cir], capture_output=True, text=True)+ wall = time.time() - t0+ if r.returncode or not os.path.exists(out):+ raise EngineError('ngspice failed: ' + (r.stdout + r.stderr)[-800:])+ d = np.loadtxt(out)+ return d[:, 0], {n: d[:, i + 1] for i, n in enumerate(names)}, wall, r.stdout[-2000:]+++# ---------------------------------------------------------------- LTspice+def run_ltspice(study, workdir, thread, settings, log):+ settings = host_paths(settings, thread)+ target = settings['bridgeTarget']+ src = study['netlists']['ltspice']+ sig = study['signals']['ltspice']+ rdir = settings['windowsWorkDir'].rstrip('\\') + '\\ltspice'+ exe = settings['ltspiceExe']+ name = os.path.basename(src)+ log(f'ltspice: sending {name} to {target or "your primary machine"}')+ d = _bridge(target, thread, 'send_files', {'filePaths': [os.path.abspath(src)], 'dest': rdir.replace('\\', '/'),+ 'reason': 'adom-spice: stage the LTspice netlist'})+ if not d.get('success', d.get('ok')):+ raise EngineError('send_files failed: ' + str(d.get('error'))[:300])+ stem = os.path.splitext(name)[0]+ script = f'''$d="{rdir}"; Remove-Item "$d\\{stem}.raw","$d\\{stem}.log" -ErrorAction SilentlyContinue+$sw=[Diagnostics.Stopwatch]::StartNew()+$p=Start-Process -FilePath "{exe}" -ArgumentList "-b","$d\\{name}" -PassThru+if(-not $p.WaitForExit({int(settings['timeoutSeconds']) * 1000})){{ $p.Kill(); "TIMEOUT" }}+"WALL=" + [Math]::Round($sw.Elapsed.TotalSeconds,2)+if (Test-Path "$d\\{stem}.raw") {{ "RAW_OK" }}'''+ log('ltspice: batch run on the Windows host')+ out, _ = _ps(target, thread, script, 'adom-spice: run LTspice in batch mode', int(settings['timeoutSeconds']) + 30)+ if 'RAW_OK' not in out:+ raise EngineError('LTspice produced no .raw (a first-run dialog can hang batch mode; see spice-ltspice skill): ' + out[-300:])+ wall = float(re.search(r'WALL=([\d.]+)', out).group(1))+ d = _bridge(target, thread, 'pull_file', {'filePaths': [f'{rdir}\\{stem}.raw'.replace('\\', '/')], 'saveTo': workdir,+ 'reason': 'adom-spice: pull the LTspice waveforms'})+ raw = os.path.join(workdir, stem + '.raw')+ if not os.path.exists(raw):+ raise EngineError('pull of .raw failed')+ from spicelib import RawRead+ rr = RawRead(raw)+ t = np.abs(rr.get_trace('time').get_wave())+ return t, {n: np.asarray(rr.get_trace(tr).get_wave()) for n, tr in sig.items()}, wall, out+++# ---------------------------------------------------------------- PSpice for TI+def read_csdf(path, want):+ names, hdr, idx, inv = [], True, None, None+ t, cols = [], {w: [] for w in want}+ with open(path) as f:+ for line in f:+ if hdr:+ if line.startswith('#C'):+ hdr = False+ else:+ if not line.startswith(('SOURCE', 'TITLE', 'SUBTITLE', 'TIME', 'ANALYSIS', 'ALLVALUES', 'SWEEP', 'XBEGIN', 'FORMAT', 'DGTL', '#')):+ names += re.findall(r"'([^']+)'", line)+ continue+ if line.startswith('#C'):+ if inv is None:+ inv = {format(names.index(w) + 1, 'x'): w for w in want}+ t.append(float(line.split()[1])); continue+ if line.startswith('#'):+ continue+ for tok in line.split():+ v, _, k = tok.partition(':')+ if k in inv:+ cols[inv[k]].append(float(v))+ n = min([len(t)] + [len(c) for c in cols.values()])+ return np.array(t[:n]), {k: np.array(v[:n]) for k, v in cols.items()}+++def run_pspice(study, workdir, thread, settings, log):+ settings = host_paths(settings, thread)+ target = settings['bridgeTarget']+ src = study['netlists']['pspice']+ sig = study['signals']['pspice'] # e.g. {"vout": "V(Rpv)", "il": "I(L1)"}+ rdir = settings['windowsWorkDir'].rstrip('\\') + '\\pspice'+ exe = settings['pspiceExe']+ name = os.path.basename(src); stem = os.path.splitext(name)[0]+ log(f'pspice: sending {name} to {target or "your primary machine"}')+ d = _bridge(target, thread, 'send_files', {'filePaths': [os.path.abspath(src)], 'dest': rdir.replace('\\', '/'),+ 'reason': 'adom-spice: stage the PSpice netlist'})+ if not d.get('success', d.get('ok')):+ raise EngineError('send_files failed: ' + str(d.get('error'))[:300])+ open_ps = f'''$d="{rdir}"; Get-Process pspice -ErrorAction SilentlyContinue | Stop-Process -Force; Start-Sleep 1+Remove-Item "$d\\{stem}.out*","$d\\{stem}.csd","$d\\{stem}.dat" -ErrorAction SilentlyContinue+Start-Process -FilePath "{exe}" -ArgumentList "`"$d\\{name}`"" -WorkingDirectory $d+Start-Sleep 14+(Get-Process pspice | Where-Object {{ $_.MainWindowHandle -ne 0 }} | Select-Object -First 1).MainWindowHandle'''+ log('pspice: opening the netlist in PSpice for TI (no batch mode)')+ out, _ = _ps(target, thread, open_ps, 'adom-spice: open the netlist in PSpice for TI', 90)+ m = re.search(r'(\d{3,})', out)+ if not m:+ raise EngineError('PSpice window not found: ' + out[-300:])+ hwnd = int(m.group(1))+ _bridge(target, thread, 'desktop_set_window_state', {'hwnd': hwnd, 'state': 'maximize', 'reason': 'adom-spice: maximize PSpice to find Run'})+ time.sleep(2)+ shot = _bridge(target, thread, 'desktop_screenshot_screen', {'reason': 'adom-spice: locate the PSpice Run button'})+ sid = shot.get('shotId') or (shot.get('data') or {}).get('shotId')+ if not sid:+ raise EngineError('screenshot failed')+ fx, fy = settings['pspiceRunButton']+ W, H = 1400, 788 # ab "safe" image space for a 16:9 screen+ t0 = time.time()+ _bridge(target, thread, 'desktop_click', {'space': 'image', 'shotId': sid, 'x': int(fx * W), 'y': int(fy * H),+ 'reason': 'adom-spice: click Run in PSpice for TI'})+ log('pspice: Run clicked, polling for JOB CONCLUDED')+ poll = f'''$t0=Get-Date; $f="{rdir}\\{stem}.out"+while (((Get-Date)-$t0).TotalSeconds -lt 75) {{+ if (Test-Path $f) {{ $m = Select-String -Path $f -Pattern "JOB CONCLUDED|JOB ABORTED|ERROR\\(" -ErrorAction SilentlyContinue | Select-Object -First 1+ if ($m) {{ "DONE " + $m.Line; break }} }}+ Start-Sleep 3 }}'''+ out = ''+ while time.time() - t0 < int(settings['timeoutSeconds']): # short polls: the bridge caps sync calls near 2 min+ out, _ = _ps(target, thread, poll, 'adom-spice: wait for PSpice to finish', 90)+ if 'DONE' in out:+ break+ wall = time.time() - t0+ if 'JOB CONCLUDED' not in out:+ raise EngineError('PSpice did not conclude: ' + out[-300:])+ d = _bridge(target, thread, 'pull_file', {'filePaths': [f'{rdir}\\{stem}.csd'.replace('\\', '/')], 'saveTo': workdir,+ 'reason': 'adom-spice: pull the PSpice CSDF output'})+ _ps(target, thread, 'Get-Process pspice -ErrorAction SilentlyContinue | Stop-Process -Force', 'adom-spice: close PSpice', 30)+ csd = os.path.join(workdir, stem + '.csd')+ if not os.path.exists(csd):+ raise EngineError('pull of .csd failed')+ t, c = read_csdf(csd, list(sig.values()))+ return t, {n: c[tr] for n, tr in sig.items()}, wall, out+++def load_file(kind, path, sig):+ """Ingest an existing waveform file (e.g. a vendor-model reference run)."""+ if kind == 'csdf':+ t, c = read_csdf(path, list(sig.values())); return t, {n: c[tr] for n, tr in sig.items()}+ if kind == 'raw':+ from spicelib import RawRead+ rr = RawRead(path); t = np.abs(rr.get_trace('time').get_wave())+ return t, {n: np.asarray(rr.get_trace(tr).get_wave()) for n, tr in sig.items()}+ d = np.loadtxt(path); return d[:, 0], {n: d[:, i + 1] for i, n in enumerate(sig)}+++RUNNERS = {'ngspice': run_ngspice, 'ltspice': run_ltspice, 'pspice': run_pspice}
app/adom_spice/server.pyadded+314@@ -0,0 +1,314 @@+#!/usr/bin/env python3+"""Adom SPICE: one dashboard for ngspice, LTspice and PSpice for TI.+Runs a study in any engine, overlays the waveforms, measures every engine with the same code, flags+disagreement, and keeps a ledger of simulation time and AI tokens per run."""+import json, os, queue, re, signal, socket, sys, threading, time, traceback+from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler+from urllib.parse import urlparse++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from adom_spice import engines, analysis # noqa: E402++VERSION = '0.1.0'+SLUG = 'adom-spice'+HOME = os.path.expanduser('~')+INST = os.path.join(HOME, '.adom', 'instances', SLUG)+WEB = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'web')+FONTS = os.path.join(HOME, '.local', 'share', 'fonts', 'adom-theme')+os.makedirs(os.path.join(INST, 'snapshots'), exist_ok=True)+os.makedirs(os.path.join(INST, 'runs'), exist_ok=True)++DEFAULT_SETTINGS = {+ 'bridgeTarget': '',+ 'windowsWorkDir': '',+ 'ltspiceExe': '',+ 'pspiceExe': 'C:\\Cadence\\PSpiceTI\\tools\\bin\\pspice.exe',+ 'pspiceRunButton': [0.4314, 0.0609],+ 'timeoutSeconds': 900,+ 'relTolerancePct': 3.0,+ 'hideVendorTimes': True,+ 'pricePerMTokLow': 4.0,+ 'pricePerMTokHigh': 5.5,+ 'ttlHours': 24,+ 'defaultSurface': 'wv',+}+ENUMS = {'defaultSurface': ['wv', 'hbw', 'pup', 'nb'], 'hideVendorTimes': [True, False]}+SETTINGS_HELP = {+ 'bridgeTarget': 'Adom Bridge machine that runs LTspice and PSpice for TI (Windows). Empty = your primary machine.',+ 'windowsWorkDir': 'Folder on that machine for netlists and results. Empty = %USERPROFILE%\\Downloads\\adom-spice.',+ 'ltspiceExe': 'LTspice.exe on that machine. Empty = the per-user install in %LOCALAPPDATA%\\Programs\\ADI\\LTspice.',+ 'pspiceRunButton': 'Where the Run button sits in a full-screen capture of maximized PSpice for TI, as [x, y] fractions. Recalibrate if runs never start.',+ 'hideVendorTimes': 'Hide LTspice and PSpice run times (their licences restrict publishing benchmarks). Turn off for private use.',+ 'relTolerancePct': 'Engines "agree" on a measurement when their spread is within this percent of the median (or the per-measurement absolute limit).',+ 'ttlHours': 'Idle hours before the server saves its state and shuts itself down.',+ 'defaultSurface': 'Where `adom-spice show` opens the dashboard.',+}+COLORS = {'ngspice': '#2dd4bf', 'ltspice': '#ffb74d', 'pspice': '#f472b6', 'reference': '#ffffff'}+++def load_settings():+ p = os.path.join(INST, 'settings.json')+ s = dict(DEFAULT_SETTINGS)+ if os.path.exists(p):+ try: s.update(json.load(open(p)))+ except Exception: pass+ return s+++SETTINGS = load_settings()+STATE = {'version': VERSION, 'study': None, 'runs': [], 'agreement': [], 'verdict': None, 'busy': None, 'log': []}+WAVES = {} # run id -> {view index: [x..], [y..]}+RAW_GRIDS = {} # run id -> {view: (g, {sig: arr})}+CLIENTS = set(); LOCK = threading.RLock(); JOBS = queue.Queue()+LAST = [time.time()]; OWNER = [os.environ.get('ADOM_AI_THREAD', '')]+PORT = [0]+++def broadcast(event, data):+ msg = ('event: ' + event + '\ndata: ' + json.dumps(data, default=float) + '\n\n').encode()+ for c in list(CLIENTS):+ try: c.write(msg); c.flush()+ except Exception: CLIENTS.discard(c)+++def public_state():+ s = dict(STATE); s['settings'] = SETTINGS; s['colors'] = COLORS; s['waves'] = WAVES+ runs = []+ for r in STATE['runs']:+ r = dict(r)+ if SETTINGS['hideVendorTimes'] and r['engine'] in ('ltspice', 'pspice'): r['wall_s'] = None; r['timeHidden'] = True+ runs.append(r)+ s['runs'] = runs+ return s+++def push():+ broadcast('state', public_state()); snapshot()+++def log(line, thread=''):+ with LOCK:+ STATE['log'] = (STATE['log'] + [{'t': time.strftime('%H:%M:%S'), 'thread': thread, 'line': line}])[-200:]+ broadcast('log', STATE['log'][-1])+++def snapshot():+ name = re.sub(r'[^a-z0-9]+', '-', (OWNER[0] or 'default').lower()).strip('-') or 'default'+ try: json.dump({'study': STATE['study'], 'runs': STATE['runs']}, open(os.path.join(INST, 'snapshots', name + '.json'), 'w'), default=float)+ except Exception: pass+++def restore():+ name = re.sub(r'[^a-z0-9]+', '-', (OWNER[0] or 'default').lower()).strip('-') or 'default'+ p = os.path.join(INST, 'snapshots', name + '.json')+ if not os.path.exists(p): return False+ d = json.load(open(p)); STATE['study'] = d.get('study'); STATE['runs'] = d.get('runs', [])+ for r in STATE['runs']:+ f = os.path.join(INST, 'runs', r['id'] + '.json')+ if os.path.exists(f): WAVES[r['id']] = json.load(open(f))+ recompute(); return True+++def registry_path():+ name = re.sub(r'[^a-z0-9]+', '-', (OWNER[0] or 'default').lower()).strip('-') or 'default'+ return os.path.join(INST, name + '.reg.json')+++def register():+ json.dump({'pid': os.getpid(), 'port': PORT[0], 'thread': OWNER[0], 'task': (STATE['study'] or {}).get('name'),+ 'version': VERSION, 'startedAt': time.strftime('%Y-%m-%dT%H:%M:%S'), 'lastActivity': LAST[0]},+ open(registry_path(), 'w'))+++# ------------------------------------------------------------------ study + runs+def load_study(path):+ st = json.load(open(path)); base = os.path.dirname(os.path.abspath(path))+ for k, v in st['netlists'].items(): st['netlists'][k] = os.path.join(base, v) if not os.path.isabs(v) else v+ st['path'] = os.path.abspath(path)+ for ref in st.get('references', []):+ if not os.path.isabs(ref['file']): ref['file'] = os.path.join(base, ref['file'])+ return st+++def add_run(engine, label, t, sigs, wall, thread, extra=None):+ rid = f"{engine}-{time.strftime('%H%M%S')}-{len(STATE['runs'])}"+ views = STATE['study']['views']; waves = {}+ for i, v in enumerate(views):+ g, s = analysis.resample(t, sigs, v['from'], v['to'], v.get('n', 1500))+ waves[str(i)] = {'x': g.tolist(), 'y': s[v['signal']].tolist()}+ metrics = analysis.measure(t, sigs, STATE['study']['measurements'])+ run = {'id': rid, 'engine': engine, 'label': label, 'status': 'done', 'wall_s': wall, 'thread': thread,+ 'started': time.strftime('%H:%M:%S'), 'metrics': metrics, 'tokens': None, 'toolCalls': None, 'visible': True}+ if extra: run.update(extra)+ json.dump(waves, open(os.path.join(INST, 'runs', rid + '.json'), 'w'))+ with LOCK:+ STATE['runs'] = [r for r in STATE['runs'] if not (r['engine'] == engine and r['label'] == label)] + [run]+ for k in list(WAVES):+ if k not in {r['id'] for r in STATE['runs']}: WAVES.pop(k)+ WAVES[rid] = waves+ recompute(); return run+++def recompute():+ st = STATE['study']+ if not st: return+ engs = {r['engine']: r['metrics'] for r in STATE['runs'] if r['engine'] in ('ngspice', 'ltspice', 'pspice') and r['status'] == 'done'}+ tol = {'rel': SETTINGS['relTolerancePct'] / 100.0, 'abs': {}}+ rows = analysis.agreement(engs, st['measurements'], tol)+ refs = [r for r in STATE['runs'] if r['engine'] == 'reference']+ for row in rows:+ row['reference'] = {r['label']: r['metrics'].get(row['metric']) for r in refs}+ STATE['agreement'] = rows+ checked = [r for r in rows if r['ok'] is not None]+ if len(engs) < 2: STATE['verdict'] = {'kind': 'pending', 'text': 'Run at least two engines to check agreement.'}+ elif all(r['ok'] for r in checked):+ STATE['verdict'] = {'kind': 'agree', 'text': f'{len(engs)} engines agree on all {len(checked)} measurements.'}+ else:+ bad = [r for r in checked if not r['ok']]+ STATE['verdict'] = {'kind': 'disagree', 'text': f'{len(bad)} of {len(checked)} measurements disagree: ' ++ ', '.join(f"{r['label']} ({r['outlier']} is the outlier)" for r in bad[:3]) ++ '. Check that engine\'s netlist translation and models first.'}+++def worker():+ while True:+ engine, thread = JOBS.get()+ STATE['busy'] = {'engine': engine, 'since': time.strftime('%H:%M:%S')}; push()+ wd = os.path.join(INST, 'work', engine); os.makedirs(wd, exist_ok=True)+ try:+ t, sigs, wall, _ = engines.RUNNERS[engine](STATE['study'], wd, thread or f'{SLUG} worker', SETTINGS,+ lambda s: log(s, thread))+ run = add_run(engine, STATE['study'].get('model', 'study model'), t, sigs, wall, thread)+ log(f'{engine}: done' + ('' if SETTINGS['hideVendorTimes'] and engine != 'ngspice' else f' in {wall:.1f} s'), thread)+ except Exception as e:+ log(f'{engine}: FAILED {e}', thread); traceback.print_exc()+ finally:+ STATE['busy'] = None; LAST[0] = time.time(); push()+++# ------------------------------------------------------------------ HTTP+READ_ONLY = {'/state', '/settings', '/events', '/version', '/console'}+++class H(BaseHTTPRequestHandler):+ def log_message(self, *a): pass++ def _json(self, code, obj):+ b = json.dumps(obj, default=float).encode()+ self.send_response(code); self.send_header('Content-Type', 'application/json'); self.send_header('Content-Length', str(len(b)))+ self.end_headers(); self.wfile.write(b)++ def _file(self, path, ctype):+ if not os.path.exists(path): return self._json(404, {'ok': False, 'error': 'not found'})+ b = open(path, 'rb').read()+ self.send_response(200); self.send_header('Content-Type', ctype); self.send_header('Content-Length', str(len(b)))+ self.send_header('Cache-Control', 'no-cache'); self.end_headers(); self.wfile.write(b)++ def do_GET(self):+ LAST[0] = time.time(); p = urlparse(self.path).path+ if p in ('/', '/index.html'): return self._file(os.path.join(WEB, 'index.html'), 'text/html; charset=utf-8')+ if p in ('/app.js', '/style.css'):+ return self._file(os.path.join(WEB, p[1:]), 'text/javascript' if p.endswith('js') else 'text/css')+ if p.startswith('/fonts/'): return self._file(os.path.join(FONTS, os.path.basename(p)), 'font/woff2')+ if p == '/state': return self._json(200, public_state())+ if p == '/version': return self._json(200, {'version': VERSION})+ if p == '/settings': return self._json(200, {'settings': SETTINGS, 'enums': ENUMS, 'help': SETTINGS_HELP})+ if p == '/console': return self._json(200, {'log': STATE['log']})+ if p == '/events':+ self.send_response(200); self.send_header('Content-Type', 'text/event-stream'); self.send_header('Cache-Control', 'no-cache')+ self.send_header('Connection', 'keep-alive'); self.send_header('X-Accel-Buffering', 'no'); self.end_headers()+ self.wfile.write((':' + ' ' * 2048 + '\n\n').encode())+ self.wfile.write(('event: state\ndata: ' + json.dumps(public_state(), default=float) + '\n\n').encode()); self.wfile.flush()+ CLIENTS.add(self.wfile)+ try:+ while True:+ time.sleep(15); self.wfile.write(b': hb\n\n'); self.wfile.flush()+ except Exception: CLIENTS.discard(self.wfile)+ return+ return self._json(404, {'ok': False, 'error': 'unknown path', 'hint': 'GET /state, /settings, /events, /version, /console'})++ def do_POST(self):+ LAST[0] = time.time(); p = urlparse(self.path).path+ n = int(self.headers.get('Content-Length') or 0)+ try: body = json.loads(self.rfile.read(n) or b'{}')+ except Exception: return self._json(400, {'ok': False, 'error': 'body must be JSON'})+ thread = body.get('aiThread') or ''+ if not thread and not body.get('fromUi'):+ return self._json(400, {'ok': False, 'errorCode': 'caller_identity_required',+ 'error': 'This app requires every AI caller to give its ai-thread name.',+ 'hint': 'Re-run with the global flag: adom-spice --ai-thread "<name>" <verb>, or add a top-level "aiThread" field if POSTing directly. Use a short human-recognizable name for THIS conversation and reuse it everywhere.'})+ who = thread or 'dashboard user'+ try:+ if p == '/settings':+ bad = [k for k in body.get('set', {}) if k not in DEFAULT_SETTINGS]+ if bad: return self._json(400, {'ok': False, 'error': f'unknown setting(s) {bad}', 'hint': f'valid: {sorted(DEFAULT_SETTINGS)}'})+ for k, v in body.get('set', {}).items():+ if k in ENUMS and v not in ENUMS[k]: return self._json(400, {'ok': False, 'error': f'{k} must be one of {ENUMS[k]}'})+ SETTINGS[k] = v+ json.dump(SETTINGS, open(os.path.join(INST, 'settings.json'), 'w'), indent=1)+ recompute(); push(); broadcast('toast', {'text': 'Settings saved', 'kind': 'success'})+ return self._json(200, {'ok': True, 'settings': SETTINGS})+ if p == '/study':+ STATE['study'] = load_study(body['path']); STATE['runs'] = []; WAVES.clear()+ log(f'thread "{who}": loaded study {STATE["study"]["name"]}', who)+ for ref in STATE['study'].get('references', []):+ t, s = engines.load_file(ref['kind'], ref['file'], ref['signals'])+ add_run('reference', ref['label'], t, s, None, who)+ recompute(); register(); push()+ return self._json(200, {'ok': True, 'study': STATE['study']['name']})+ if p == '/run':+ if not STATE['study']: return self._json(400, {'ok': False, 'error': 'no study loaded', 'hint': 'adom-spice --ai-thread "<name>" study <study.json>'})+ engs = body.get('engines') or ['ngspice']+ bad = [e for e in engs if e not in engines.RUNNERS]+ if bad: return self._json(400, {'ok': False, 'error': f'unknown engine(s) {bad}', 'hint': 'engines: ngspice, ltspice, pspice'})+ for e in engs: JOBS.put((e, who)); log(f'thread "{who}": queued {e}', who)+ return self._json(200, {'ok': True, 'queued': engs})+ if p == '/ingest':+ sig = body['signals']; t, s = engines.load_file(body.get('kind', 'txt'), body['file'], sig)+ r = add_run(body.get('engine', 'reference'), body.get('label', os.path.basename(body['file'])), t, s, body.get('wall_s'), who)+ push(); return self._json(200, {'ok': True, 'run': r['id']})+ if p == '/tokens':+ for r in STATE['runs']:+ if r['engine'] == body['engine'] and (not body.get('label') or r['label'] == body['label']):+ r['tokens'] = int(body['tokens']); r['toolCalls'] = body.get('toolCalls')+ push(); return self._json(200, {'ok': True})+ if p == '/visible':+ for r in STATE['runs']:+ if r['id'] == body['id']: r['visible'] = bool(body['visible'])+ push(); return self._json(200, {'ok': True})+ if p in ('/ui/click', '/ui/reveal', '/ui/toast'):+ broadcast(p.split('/')[-1], body); return self._json(200, {'ok': True})+ if p == '/shutdown':+ if not body.get('reason'):+ return self._json(400, {'ok': False, 'errorCode': 'reason_required', 'error': 'shutdown needs a reason', 'hint': 'adom-spice --ai-thread "<name>" shutdown --reason "<why>"'})+ snapshot(); self._json(200, {'ok': True}); threading.Timer(0.3, lambda: os._exit(0)).start(); return+ except Exception as e:+ traceback.print_exc(); return self._json(500, {'ok': False, 'error': str(e)})+ return self._json(404, {'ok': False, 'error': 'unknown path'})+++def reaper():+ while True:+ time.sleep(60)+ if SETTINGS.get('ttlHours') and time.time() - LAST[0] > float(SETTINGS['ttlHours']) * 3600 and not STATE['busy']:+ snapshot()+ try: os.remove(registry_path())+ except Exception: pass+ os._exit(0)+++def main():+ port = int(os.environ.get('ADOM_SPICE_PORT', '0'))+ OWNER[0] = os.environ.get('ADOM_SPICE_THREAD', OWNER[0])+ srv = ThreadingHTTPServer(('0.0.0.0', port), H); PORT[0] = srv.server_address[1]+ if restore(): print(f'restored snapshot for thread "{OWNER[0]}"', flush=True)+ register()+ threading.Thread(target=worker, daemon=True).start()+ if '--keep-alive' not in sys.argv: threading.Thread(target=reaper, daemon=True).start()+ print(json.dumps({'ok': True, 'port': PORT[0], 'pid': os.getpid(), 'version': VERSION}), flush=True)+ signal.signal(signal.SIGTERM, lambda *a: (snapshot(), os._exit(0)))+ srv.serve_forever()+++if __name__ == '__main__':+ main()
app/bin/adom-spiceadded+135@@ -0,0 +1,135 @@+#!/usr/bin/env python3+"""adom-spice CLI: every verb takes the global --ai-thread "<name>" flag (any position)."""+import glob, json, os, subprocess, sys, time, urllib.request++ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))+INST = os.path.expanduser('~/.adom/instances/adom-spice')+os.makedirs(INST, exist_ok=True)+PY = os.environ.get('ADOM_SPICE_PYTHON') or next((p for p in (os.path.expanduser('~/.adom/adom-spice-venv/bin/python'), '/home/adom/spice-venv/bin/python', sys.executable) if os.path.exists(p)), 'python3')+HELP = """adom-spice: one dashboard for ngspice, LTspice and PSpice for TI++ adom-spice --ai-thread "<name>" start [--keep-alive] start (or reuse) this thread's dashboard server+ adom-spice --ai-thread "<name>" show [--surface wv|hbw|pup|nb] open the dashboard (default: Hydrogen webview)+ adom-spice --ai-thread "<name>" study <study.json> load a study (netlists per engine, signals, views, measurements)+ adom-spice --ai-thread "<name>" run ngspice ltspice pspice queue runs; LTspice/PSpice go to the bridge target in Settings+ adom-spice --ai-thread "<name>" ingest <file> --kind csdf|raw|txt --label "<label>" --signals '{"vout":"V(x)"}' [--engine reference]+ adom-spice --ai-thread "<name>" tokens <engine> <tokens> [--tool-calls N] record the AI tokens a run cost+ adom-spice --ai-thread "<name>" settings [key=value ...] read or change settings+ adom-spice ls | state | console read-only+ adom-spice --ai-thread "<name>" shutdown --reason "<why>"+"""+++def args_and_thread(argv):+ th, out, i = os.environ.get('ADOM_AI_THREAD', ''), [], 0+ while i < len(argv):+ if argv[i] == '--ai-thread': th = argv[i + 1]; i += 2; continue+ out.append(argv[i]); i += 1+ return th, out+++def flag(a, name, default=None):+ if name in a:+ i = a.index(name); v = a[i + 1]; del a[i:i + 2]; return v+ return default+++def instances():+ live = []+ for f in glob.glob(os.path.join(INST, '*.reg.json')):+ d = json.load(open(f))+ try: os.kill(d['pid'], 0); live.append(d)+ except OSError: os.remove(f)+ return live+++def mine(th):+ for d in instances():+ if d['thread'] == th: return d+ return None+++def call(port, path, body=None):+ req = urllib.request.Request(f'http://127.0.0.1:{port}{path}', data=None if body is None else json.dumps(body).encode(),+ headers={'Content-Type': 'application/json'}, method='GET' if body is None else 'POST')+ try:+ with urllib.request.urlopen(req, timeout=60) as r: return json.loads(r.read())+ except urllib.error.HTTPError as e: return json.loads(e.read())+++def need(th):+ if not th:+ print(json.dumps({'ok': False, 'errorCode': 'caller_identity_required', 'hint': 'Re-run with: adom-spice --ai-thread "<short name for this conversation>" <verb>'})); sys.exit(2)+ d = mine(th)+ if not d:+ print(json.dumps({'ok': False, 'error': f'no dashboard running for thread "{th}"', 'hint': f'adom-spice --ai-thread "{th}" start'})); sys.exit(2)+ return d['port']+++def url_for(port):+ tpl = os.environ.get('VSCODE_PROXY_URI', '')+ return tpl.replace('{{port}}', str(port)) if '{{port}}' in tpl else f'http://localhost:{port}/'+++def main():+ th, a = args_and_thread(sys.argv[1:])+ if not a or a[0] in ('-h', '--help', 'help'): print(HELP); return+ v = a.pop(0)+ if v == 'ls':+ for d in instances():+ print(f"port {d['port']} thread \"{d['thread']}\" task {d.get('task')} version {d['version']} idle {int(time.time() - d['lastActivity'])} s")+ return+ if v == 'start':+ if not th: need(th)+ d = mine(th)+ if d: print(json.dumps({'ok': True, 'port': d['port'], 'reused': True, 'url': url_for(d['port']), 'note': 'already running for this thread; use it'})); return+ env = dict(os.environ, ADOM_SPICE_THREAD=th, PYTHONUNBUFFERED='1')+ logf = open(os.path.join(INST, 'server.log'), 'a')+ p = subprocess.Popen([PY, os.path.join(ROOT, 'adom_spice', 'server.py')] + (['--keep-alive'] if '--keep-alive' in a else []),+ env=env, stdout=subprocess.PIPE, stderr=logf, start_new_session=True, text=True)+ line = p.stdout.readline()+ while line and not line.startswith('{'):+ line = p.stdout.readline()+ d = json.loads(line)+ d['url'] = url_for(d['port']); print(json.dumps(d)); return+ if v in ('state', 'console'):+ ds = instances(); d = mine(th) if th else (ds[0] if ds else None)+ if not d: print('{"ok": false, "error": "no dashboard running"}'); return+ r = call(d['port'], '/' + v)+ if v == 'state' and '--full' not in a: r.pop('waves', None)+ print(json.dumps(r, indent=1)); return+ port = need(th)+ if v == 'show':+ surface = flag(a, '--surface') or call(port, '/settings')['settings'].get('defaultSurface', 'wv')+ u = url_for(port)+ if surface in ('wv', 'hbw'):+ r = subprocess.run(['adom-cli', 'hydrogen', 'webview', 'open-or-refresh', '--name', 'Adom SPICE', '--url', u], capture_output=True, text=True)+ print(json.dumps({'ok': r.returncode == 0, 'surface': 'wv', 'url': u, 'detail': (r.stdout + r.stderr)[-300:]}))+ else:+ print(json.dumps({'ok': True, 'surface': surface, 'url': u, 'hint': 'open this URL with the pup or nb skill'}))+ return+ if v == 'study': print(json.dumps(call(port, '/study', {'aiThread': th, 'path': os.path.abspath(a[0])}))); return+ if v == 'run': print(json.dumps(call(port, '/run', {'aiThread': th, 'engines': a or ['ngspice']}))); return+ if v == 'ingest':+ kind = flag(a, '--kind', 'txt'); label = flag(a, '--label'); sig = json.loads(flag(a, '--signals', '{}')); eng = flag(a, '--engine', 'reference')+ print(json.dumps(call(port, '/ingest', {'aiThread': th, 'file': os.path.abspath(a[0]), 'kind': kind, 'label': label, 'signals': sig, 'engine': eng}))); return+ if v == 'tokens':+ tc = flag(a, '--tool-calls')+ print(json.dumps(call(port, '/tokens', {'aiThread': th, 'engine': a[0], 'tokens': int(a[1]), 'toolCalls': int(tc) if tc else None}))); return+ if v == 'settings':+ if not a: print(json.dumps(call(port, '/settings'), indent=1)); return+ s = {}+ for kv in a:+ k, _, val = kv.partition('=')+ try: s[k] = json.loads(val)+ except json.JSONDecodeError: s[k] = val+ print(json.dumps(call(port, '/settings', {'aiThread': th, 'set': s}))); return+ if v == 'shutdown':+ print(json.dumps(call(port, '/shutdown', {'aiThread': th, 'reason': flag(a, '--reason')}))); return+ if v == 'ui':+ sub = a.pop(0); print(json.dumps(call(port, '/ui/' + sub, {'aiThread': th, 'selector': a[0] if a else None, 'text': a[0] if a else None}))); return+ print(HELP); sys.exit(2)+++if __name__ == '__main__':+ main()
app/examples/tps54202-buck/board_ltspice.ciradded+49@@ -0,0 +1,49 @@+* TPS54202 12V->5V/1A molecule, portable peak-current-mode model (board values)+Vsrc src 0 12+Rcable src vinc 0.05+Lcable vinc vin 0.5u+Cbulk vin b1 47u+Rbulk b1 0 0.3+Cin vin 0 12u+S1 vin sw hg 0 SWHS+S2 sw 0 lg 0 SWLS+Dls 0 sw DBODY+Csw sw 0 100p+L1 sw lx 15u+Vsense lx lxs 0+Rdcr lxs vout 0.118+Cout vout ce 3.63e-05+Resr ce 0 1m+Rload vout 0 10+Rstep vout st 10+Sstep st 0 stp 0 SWSTEP+Vstp stp 0 PWL(0 1 7m 1 7.0001m 0 8m 0 8.0001m 1)+Rtop vout fb 73600+Cff vout fb 6.8e-11+Rbot fb 0 10000+Vref vref 0 PWL(0 0 5m 0.596)+Gea vc 0 fb vref 0.0001+Rea vc 0 1e+07+Rc vc cz 104105+Cc cz 0 7.64398e-10+Cp vc 0 7.64398e-12+Vclk set 0 PULSE(0 1 0 1n 1n 20n 2u)+Vramp ramp 0 PULSE(0 0.0833333 0 1.98u 10n 10n 2u)+Rqd q qd 1+Cqd qd 0 1n+Rqbd qb qbd 1k+Cqbd qbd 0 10p+.func su(x) {0.5+0.5*tanh(2000*x)}+Brst rst 0 V=max(su(I(Vsense)*0.25+V(ramp)-V(vc)), su(I(Vsense)-2.5))+Bq q 0 V=su(V(set)-0.5) + (1-su(V(set)-0.5))*(1-su(V(rst)-0.5))*su(V(qd)-0.5)+Bqb qb 0 V=1-V(q)+Bhg hg 0 V=su(V(q)-0.5)+Blg lg 0 V=su(V(qbd)-0.9)*su(0.5-V(q))+.model SWHS SW(Ron=0.148 Roff=1Meg Vt=0.5 Vh=0)+.model SWLS SW(Ron=0.078 Roff=1Meg Vt=0.5 Vh=0)+.model SWSTEP SW(Ron=1m Roff=1G Vt=0.5 Vh=0)+.model DBODY D(Is=1e-9 N=1.2 Rs=0.05)+.options method=gear reltol=1e-3+.tran 10n 9m 0 10n uic+.save V(vout) I(Vsense)+.end
app/examples/tps54202-buck/board_ngspice.ciradded+53@@ -0,0 +1,53 @@+* TPS54202 12V->5V/1A molecule, portable peak-current-mode model (board values)+Vsrc src 0 12+Rcable src vinc 0.05+Lcable vinc vin 0.5u+Cbulk vin b1 47u+Rbulk b1 0 0.3+Cin vin 0 12u+S1 vin sw hg 0 SWHS+S2 sw 0 lg 0 SWLS+Dls 0 sw DBODY+Csw sw 0 100p+L1 sw lx 15u+Vsense lx lxs 0+Rdcr lxs vout 0.118+Cout vout ce 3.63e-05+Resr ce 0 1m+Rload vout 0 10+Rstep vout st 10+Sstep st 0 stp 0 SWSTEP+Vstp stp 0 PWL(0 1 7m 1 7.0001m 0 8m 0 8.0001m 1)+Rtop vout fb 73600+Cff vout fb 6.8e-11+Rbot fb 0 10000+Vref vref 0 PWL(0 0 5m 0.596)+Gea vc 0 fb vref 0.0001+Rea vc 0 1e+07+Rc vc cz 104105+Cc cz 0 7.64398e-10+Cp vc 0 7.64398e-12+Vclk set 0 PULSE(0 1 0 1n 1n 20n 2u)+Vramp ramp 0 PULSE(0 0.0833333 0 1.98u 10n 10n 2u)+Rqd q qd 1+Cqd qd 0 1n+Rqbd qb qbd 1k+Cqbd qbd 0 10p+.func su(x) {0.5+0.5*tanh(2000*x)}+Brst rst 0 V=max(su(I(Vsense)*0.25+V(ramp)-V(vc)), su(I(Vsense)-2.5))+Bq q 0 V=su(V(set)-0.5) + (1-su(V(set)-0.5))*(1-su(V(rst)-0.5))*su(V(qd)-0.5)+Bqb qb 0 V=1-V(q)+Bhg hg 0 V=su(V(q)-0.5)+Blg lg 0 V=su(V(qbd)-0.9)*su(0.5-V(q))+.model SWHS SW(Ron=0.148 Roff=1Meg Vt=0.5 Vh=0)+.model SWLS SW(Ron=0.078 Roff=1Meg Vt=0.5 Vh=0)+.model SWSTEP SW(Ron=1m Roff=1G Vt=0.5 Vh=0)+.model DBODY D(Is=1e-9 N=1.2 Rs=0.05)+.options method=gear reltol=1e-3+.tran 10n 9m 0 10n uic+.control+set wr_singlescale+run+wrdata /home/adom/spice-compare/board/board_ngspice.txt v(vout) i(Vsense)+.endc+.end
app/examples/tps54202-buck/board_pspice.ciradded+48@@ -0,0 +1,48 @@+* TPS54202 12V->5V/1A molecule, portable peak-current-mode model (board values) +Vsrc src 0 12 +Rcable src vinc 0.05 +Lcable vinc vin 0.5u +Cbulk vin b1 47u +Rbulk b1 0 0.3 +Cin vin 0 12u +S1 vin sw hg 0 SWHS +S2 sw 0 lg 0 SWLS +Dls 0 sw DBODY +Csw sw 0 100p +L1 sw lx 15u +Vsense lx lxs 0 +Rdcr lxs vout 0.118 +Cout vout ce 3.63e-05 +Resr ce 0 1m +Rload vout 0 10 +Rstep vout st 10 +Sstep st 0 stp 0 SWSTEP +Vstp stp 0 PWL(0 1 7m 1 7.0001m 0 8m 0 8.0001m 1) +Rtop vout fb 73600 +Cff vout fb 6.8e-11 +Rbot fb 0 10000 +Vref vref 0 PWL(0 0 5m 0.596) +Gea vc 0 fb vref 0.0001 +Rea vc 0 1e+07 +Rc vc cz 104105 +Cc cz 0 7.64398e-10 +Cp vc 0 7.64398e-12 +Vclk set 0 PULSE(0 1 0 1n 1n 20n 2u) +Vramp ramp 0 PULSE(0 0.0833333 0 1.98u 10n 10n 2u) +Rqd q qd 1 +Cqd qd 0 1n +Rqbd qb qbd 1k +Cqbd qbd 0 10p +Erst rst 0 VALUE={IF((I(Vsense)*0.25+V(ramp)>=V(vc)) | (I(Vsense)>=2.5),1,0)} +Eq q 0 VALUE={IF(V(set)>0.5,1,IF(V(rst)>0.5,0,IF(V(qd)>0.5,1,0)))} +Eqb qb 0 VALUE={1-V(q)} +Ehg hg 0 VALUE={IF(V(q)>0.5,1,0)} +Elg lg 0 VALUE={IF((V(qbd)>0.9) & (V(q)<0.5),1,0)} +.model SWHS VSWITCH(RON=0.148 ROFF=1MEG VON=0.501 VOFF=0.499) +.model SWLS VSWITCH(RON=0.078 ROFF=1MEG VON=0.501 VOFF=0.499) +.model SWSTEP VSWITCH(RON=1m ROFF=1G VON=0.6 VOFF=0.4) +.model DBODY D(IS=1e-9 N=1.2 RS=0.05) +Rpv vout 0 1G +.TRAN 10n 9m 0 10n UIC +.PROBE/CSDF V(Rpv) I(L1) +.END
app/examples/tps54202-buck/study.jsonadded+26@@ -0,0 +1,26 @@+{+ "name": "TPS54202 12 V to 5 V buck molecule",+ "model": "portable PCM model (board values)",+ "netlists": {"ngspice": "board_ngspice.cir", "ltspice": "board_ltspice.cir", "pspice": "board_pspice.cir"},+ "signals": {+ "ngspice": {"vout": "v(vout)", "il": "i(Vsense)"},+ "ltspice": {"vout": "V(vout)", "il": "I(Vsense)"},+ "pspice": {"vout": "V(Rpv)", "il": "I(L1)"}+ },+ "views": [+ {"title": "VOUT: start-up from 12 V, then 1 A to 0.5 A at 7 ms and back at 8 ms (V vs ms)", "signal": "vout", "from": 0, "to": 0.009, "n": 1800, "xscale": 1000},+ {"title": "Zoom on the load steps (V vs ms)", "signal": "vout", "from": 0.0068, "to": 0.009, "n": 2200, "xscale": 1000},+ {"title": "Inductor current across the 7 ms step (A vs ms)", "signal": "il", "from": 0.00697, "to": 0.00703, "n": 1500, "xscale": 1000}+ ],+ "measurements": [+ {"name": "vout_mean", "label": "VOUT at 1 A", "signal": "vout", "kind": "mean", "from": 0.0065, "to": 0.007, "unit": "V", "abs_tol": 0.005},+ {"name": "vout_ripple", "label": "VOUT ripple", "signal": "vout", "kind": "pp", "from": 0.0065, "to": 0.007, "unit": "mV", "scale": 1000, "abs_tol": 1.0},+ {"name": "il_ripple", "label": "Inductor ripple", "signal": "il", "kind": "pp", "from": 0.0069, "to": 0.007, "unit": "A", "abs_tol": 0.02},+ {"name": "il_peak_startup", "label": "Start-up peak current", "signal": "il", "kind": "max", "from": 0, "to": 0.006, "unit": "A", "abs_tol": 0.03},+ {"name": "t_reach", "label": "Time to 95 %", "signal": "vout", "kind": "t_reach", "frac": 0.95, "ref": [0.0065, 0.007], "unit": "ms", "scale": 1000, "abs_tol": 0.05},+ {"name": "overshoot", "label": "Overshoot, 1 A to 0.5 A", "signal": "vout", "kind": "overshoot", "from": 0.007, "to": 0.0075, "ref": [0.0065, 0.007], "unit": "mV", "scale": 1000, "abs_tol": 4.0},+ {"name": "undershoot", "label": "Undershoot, 0.5 A to 1 A", "signal": "vout", "kind": "undershoot", "from": 0.008, "to": 0.0085, "ref": [0.0076, 0.008], "unit": "mV", "scale": 1000, "abs_tol": 4.0},+ {"name": "settle", "label": "Settling to 1 %", "signal": "vout", "kind": "settle", "from": 0.008, "to": 0.009, "ref": [0.0065, 0.007], "band": 0.01, "unit": "us", "scale": 1000000, "abs_tol": 15}+ ],+ "references": []+}
app/install.shadded+16@@ -0,0 +1,16 @@+#!/usr/bin/env bash+set -e+HERE="$(cd "$(dirname "$0")" && pwd)"+DEST="$HOME/.adom/adom-spice"+VENV="$HOME/.adom/adom-spice-venv"+mkdir -p "$DEST" "$HOME/.local/bin" "$HOME/.claude/skills/adom-spice"+cp -r "$HERE/adom_spice" "$HERE/web" "$HERE/bin" "$HERE/examples" "$DEST/"+chmod +x "$DEST/bin/adom-spice"+ln -sfn "$DEST/bin/adom-spice" "$HOME/.local/bin/adom-spice"+cp "$HERE/../skills/adom-spice/SKILL.md" "$HOME/.claude/skills/adom-spice/SKILL.md" 2>/dev/null || true+if [ ! -x "$VENV/bin/python" ]; then python3 -m venv "$VENV"; fi+"$VENV/bin/pip" install -q numpy spicelib >/dev/null+if ! command -v ngspice >/dev/null 2>&1; then+ if command -v sudo >/dev/null 2>&1; then sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -q ngspice >/dev/null || echo "WARN: install ngspice (apt-get install ngspice) to run the ngspice engine"; fi+fi+echo "OK: adom-spice installed. Try: adom-spice --ai-thread \"<name>\" start"
app/uninstall.shadded+8@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -e+for f in "$HOME"/.adom/instances/adom-spice/*.reg.json; do+ [ -f "$f" ] && kill "$(python3 -c "import json;print(json.load(open('$f'))['pid'])")" 2>/dev/null || true+done+rm -rf "$HOME/.adom/adom-spice" "$HOME/.adom/adom-spice-venv" "$HOME/.claude/skills/adom-spice"+rm -f "$HOME/.local/bin/adom-spice"+echo "OK: adom-spice removed (saved settings and snapshots stay in ~/.adom/instances/adom-spice)."
app/web/app.jsadded+141@@ -0,0 +1,141 @@+// Adom SPICE dashboard: all state lives on the server; this page renders it and posts user actions.+let S = null;+const ENG = {+ ngspice: { name: 'ngspice', where: 'Adom container (BSD, can be hosted)' },+ ltspice: { name: 'LTspice', where: 'Windows host via Adom Bridge, batch mode' },+ pspice: { name: 'PSpice for TI', where: 'Windows host via Adom Bridge, driven through its window' },+};+const $ = (s) => document.querySelector(s);+const post = (path, body) => fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(Object.assign({ fromUi: true }, body)) }).then(r => r.json());+const fmt = (v, d = 3) => v == null ? '-' : (Math.abs(v) >= 100 ? v.toFixed(1) : Math.abs(v) >= 10 ? v.toFixed(2) : v.toFixed(d));+const cost = (t) => t == null ? '-' : `$${(t * S.settings.pricePerMTokLow / 1e6).toFixed(2)}-${(t * S.settings.pricePerMTokHigh / 1e6).toFixed(2)}`;++function toast(text, kind) {+ const d = document.createElement('div'); d.className = 'toast'; d.textContent = text;+ if (kind === 'error') d.style.borderLeftColor = 'var(--red)';+ $('#toasts').appendChild(d); setTimeout(() => d.remove(), 4000);+}++function runFor(e) { return S.runs.filter(r => r.engine === e).slice(-1)[0]; }++function renderEngines() {+ const box = $('#engines'); box.innerHTML = '';+ const list = Object.keys(ENG).map(e => ({ key: e, run: runFor(e) }));+ for (const r of S.runs.filter(r => r.engine === 'reference')) list.push({ key: 'reference', run: r });+ for (const { key, run } of list) {+ const busy = S.busy && S.busy.engine === key;+ const st = busy ? 'running' : run ? run.status : 'idle';+ const c = document.createElement('div'); c.className = 'eng'; c.id = 'eng-' + key;+ const time = run ? (run.timeHidden ? 'hidden (licence)' : run.wall_s != null ? run.wall_s.toFixed(1) + ' s' : '-') : '-';+ c.innerHTML = `<div class="name"><span class="sw" style="background:${S.colors[key]}"></span>${key === 'reference' ? run.label : ENG[key].name}</div>+ <div class="where">${key === 'reference' ? 'Reference run (does not vote)' : ENG[key].where}</div>+ <div class="stats">status <span class="state-${st}">${st}</span><br>sim time ${time}<br>AI tokens ${run && run.tokens != null ? run.tokens.toLocaleString() + ' ' + cost(run.tokens) : '-'}</div>+ <div class="row">${key === 'reference' ? '' : `<button class="run" data-e="${key}" ${S.busy || !S.study ? 'disabled' : ''}>${busy ? 'Running' : 'Run'}</button>`}+ ${run ? `<label class="toggle"><input type="checkbox" data-id="${run.id}" ${run.visible !== false ? 'checked' : ''}> show on charts</label>` : ''}</div>`;+ box.appendChild(c);+ }+ box.querySelectorAll('.run').forEach(b => b.onclick = (ev) => {+ const e = b.dataset.e;+ if (!ev.isTrusted) return; // only real user clicks start runs+ if (e !== 'ngspice' && !confirm(`${ENG[e].name} runs on ${S.settings.bridgeTarget || 'your primary machine'} through Adom Bridge and uses its screen while it works. Start it?`)) return;+ post('run', { engines: [e] }).then(r => r.ok ? toast('Queued ' + ENG[e].name) : toast(r.error, 'error'));+ });+ box.querySelectorAll('input[data-id]').forEach(i => i.onchange = () => post('visible', { id: i.dataset.id, visible: i.checked }));+}++function drawChart(canvas, view, idx) {+ const dpr = window.devicePixelRatio || 1, W = canvas.clientWidth, H = canvas.clientHeight;+ canvas.width = W * dpr; canvas.height = H * dpr;+ const g = canvas.getContext('2d'); g.scale(dpr, dpr); g.clearRect(0, 0, W, H);+ const L = 56, R = 10, T = 8, B = 30;+ const series = S.runs.filter(r => r.visible !== false && S.waves[r.id] && S.waves[r.id][idx]);+ if (!series.length) { g.fillStyle = '#9aa4b2'; g.font = '14px Familjen Grotesk'; g.fillText('No runs yet', L, H / 2); return; }+ let x0 = view.from, x1 = view.to, y0 = Infinity, y1 = -Infinity;+ for (const r of series) for (const y of S.waves[r.id][idx].y) { if (y < y0) y0 = y; if (y > y1) y1 = y; }+ if (view.ylim) [y0, y1] = view.ylim; else { const p = (y1 - y0) * 0.08 || 0.1; y0 -= p; y1 += p; }+ const X = (x) => L + (x - x0) / (x1 - x0) * (W - L - R), Y = (y) => T + (1 - (y - y0) / (y1 - y0)) * (H - T - B);+ g.strokeStyle = '#232833'; g.lineWidth = 1; g.fillStyle = '#9aa4b2'; g.font = '12px JetBrains Mono';+ for (let i = 0; i <= 5; i++) {+ const yv = y0 + (y1 - y0) * i / 5, xv = x0 + (x1 - x0) * i / 5;+ g.beginPath(); g.moveTo(L, Y(yv)); g.lineTo(W - R, Y(yv)); g.stroke(); g.fillText(fmt(yv * (view.yscale || 1), 2), 4, Y(yv) + 4);+ g.beginPath(); g.moveTo(X(xv), T); g.lineTo(X(xv), H - B); g.stroke(); g.fillText(fmt(xv * (view.xscale || 1), 2), X(xv) - 14, H - 10);+ }+ const order = ['ngspice', 'ltspice', 'pspice', 'reference'], widths = { ngspice: 6, ltspice: 3.6, pspice: 1.6, reference: 1.8 };+ series.sort((a, b) => order.indexOf(a.engine) - order.indexOf(b.engine));+ for (const r of series) {+ const d = S.waves[r.id][idx]; g.strokeStyle = S.colors[r.engine]; g.lineWidth = widths[r.engine] || 2;+ g.setLineDash(r.engine === 'reference' ? [6, 4] : []); g.lineJoin = 'round'; g.beginPath();+ d.x.forEach((x, i) => { const px = X(x), py = Y(d.y[i]); i ? g.lineTo(px, py) : g.moveTo(px, py); }); g.stroke();+ }+ g.setLineDash([]);+}++function renderCharts() {+ const box = $('#charts');+ if (!S.study) { box.innerHTML = ''; return; }+ if (box.children.length !== S.study.views.length) {+ box.innerHTML = S.study.views.map((v, i) => `<div class="chart"><h3>${v.title}</h3><canvas id="c${i}" style="height:${i === 0 ? 520 : 240}px"></canvas></div>`).join('');+ }+ S.study.views.forEach((v, i) => drawChart($('#c' + i), v, String(i)));+}++function renderAgree() {+ const t = $('#agree');+ if (!S.agreement.length) { t.innerHTML = '<tr><td>No measurements yet.</td></tr>'; return; }+ const engs = Object.keys(ENG).filter(e => runFor(e) && runFor(e).status === 'done');+ const refs = S.runs.filter(r => r.engine === 'reference').map(r => r.label);+ t.innerHTML = `<tr><th>Measurement</th>${engs.map(e => `<th><span class="sw" style="background:${S.colors[e]}"></span> ${ENG[e].name}</th>`).join('')}<th>Spread</th><th>Limit</th><th>Engines</th>${refs.map(r => `<th>${r}</th>`).join('')}</tr>` ++ S.agreement.map(row => `<tr class="${row.ok === false ? 'flag' : ''}"><td>${row.label || row.metric} <span class="sub">${row.unit}</span></td>+ ${engs.map(e => `<td class="num ${row.outlier === e ? 'outlier' : ''}">${fmt(row.values[e])}</td>`).join('')}+ <td class="num">${fmt(row.spread)}</td><td class="num">${fmt(row.limit)}</td>+ <td class="${row.ok ? 'ok' : row.ok === false ? 'bad' : ''}">${row.ok ? 'agree' : row.ok === false ? 'differ' : '-'}</td>+ ${refs.map(r => `<td class="num">${fmt((row.reference || {})[r])}</td>`).join('')}</tr>`).join('');+}++function renderLedger() {+ const t = $('#ledger');+ t.innerHTML = '<tr><th>Run</th><th>Model</th><th>AI thread</th><th>Started</th><th>Sim time</th><th>AI tokens</th><th>Tool calls</th><th>AI cost</th></tr>' ++ S.runs.map(r => `<tr><td><span class="sw" style="background:${S.colors[r.engine]}"></span> ${r.engine === 'reference' ? 'reference' : ENG[r.engine].name}</td><td>${r.label}</td><td>${r.thread || '-'}</td><td>${r.started}</td>+ <td class="num">${r.timeHidden ? 'hidden' : r.wall_s != null ? r.wall_s.toFixed(1) + ' s' : '-'}</td><td class="num">${r.tokens != null ? r.tokens.toLocaleString() : '-'}</td>+ <td class="num">${r.toolCalls != null ? r.toolCalls : '-'}</td><td class="num">${cost(r.tokens)}</td></tr>`).join('');+}++function renderLog(line) {+ const l = $('#log'); const add = (e) => { const d = document.createElement('div'); d.textContent = `${e.t} ${e.thread ? '[' + e.thread + '] ' : ''}${e.line}`; l.appendChild(d); };+ if (line) add(line); else { l.innerHTML = ''; (S.log || []).forEach(add); }+ l.scrollTop = l.scrollHeight;+}++function render() {+ $('#study').textContent = S.study ? S.study.name : 'no study loaded';+ $('#busy').textContent = S.busy ? `running ${ENG[S.busy.engine].name}...` : '';+ const v = S.verdict || { kind: 'pending', text: 'Load a study to begin.' };+ $('#verdict').className = 'verdict ' + v.kind; $('#verdict').textContent = v.text;+ renderEngines(); renderCharts(); renderAgree(); renderLedger(); renderLog();+}++async function openSettings() {+ const d = await fetch('settings').then(r => r.json());+ $('#settingsBody').innerHTML = Object.entries(d.settings).map(([k, v]) => {+ const help = d.help[k] || '', en = d.enums[k];+ const input = en ? `<select data-k="${k}">${en.map(o => `<option ${String(o) === String(v) ? 'selected' : ''}>${o}</option>`).join('')}</select>`+ : `<input data-k="${k}" value='${typeof v === 'object' ? JSON.stringify(v) : v}'>`;+ return `<div class="setrow"><div><div>${k.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase())}</div><div class="help">${help}</div></div>${input}</div>`;+ }).join('');+ $('#ver').textContent = 'Adom SPICE ' + S.version;+ $('#settingsBody').querySelectorAll('[data-k]').forEach(el => el.onchange = () => {+ let v = el.value; try { v = JSON.parse(v); } catch (e) { }+ post('settings', { set: { [el.dataset.k]: v } }).then(r => r.ok ? null : toast(r.error, 'error'));+ });+ $('#settings').classList.remove('hidden');+}+$('#gear').onclick = openSettings;+$('#closeSettings').onclick = () => $('#settings').classList.add('hidden');++const es = new EventSource('events');+es.addEventListener('state', (e) => { S = JSON.parse(e.data); render(); });+es.addEventListener('log', (e) => { if (S) { S.log.push(JSON.parse(e.data)); renderLog(JSON.parse(e.data)); } });+es.addEventListener('toast', (e) => { const d = JSON.parse(e.data); toast(d.text, d.kind); });+es.addEventListener('click', (e) => { const el = document.querySelector(JSON.parse(e.data).selector); if (el) el.click(); });+es.addEventListener('reveal', (e) => { const el = document.querySelector(JSON.parse(e.data).selector); if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.add('hl'); setTimeout(() => el.classList.remove('hl'), 2500); } });+window.addEventListener('resize', () => S && renderCharts());
app/web/index.htmladded+42@@ -0,0 +1,42 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Adom SPICE</title>+<link rel="stylesheet" href="style.css">+</head>+<body>+<header>+ <div class="brand"><span class="logo">◆</span> Adom SPICE <span id="study" class="study"></span></div>+ <div class="hdr-right">+ <span id="busy" class="busy"></span>+ <button id="gear" class="icon" data-tip="Settings" aria-label="Settings">+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="#fff" stroke-width="1.8"><circle cx="12" cy="12" r="3.2"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>+ </button>+ </div>+</header>+<main>+ <div id="verdict" class="verdict pending">Load a study to begin.</div>+ <section id="engines" class="engines"></section>+ <section class="charts" id="charts"></section>+ <section class="panel">+ <h2>Do the engines agree?</h2>+ <p class="sub">Every engine is measured by the same code. A measurement agrees when the spread across engines is within the tolerance in Settings. A reference (such as a vendor model) is shown for comparison but does not vote.</p>+ <table id="agree"></table>+ </section>+ <section class="panel">+ <h2>Run ledger</h2>+ <p class="sub">Simulation time and the AI tokens each run cost (recorded with <code>adom-spice tokens</code>).</p>+ <table id="ledger"></table>+ </section>+ <section class="panel log"><h2>Activity</h2><div id="log"></div></section>+</main>+<div id="settings" class="modal hidden"><div class="card">+ <div class="card-hdr"><h2>Settings</h2><button id="closeSettings" class="icon" aria-label="Close">✕</button></div>+ <div id="settingsBody"></div><div class="ver" id="ver"></div>+</div></div>+<div id="toasts"></div>+<script src="app.js"></script>+</body>+</html>
app/web/style.cssadded+62@@ -0,0 +1,62 @@+@font-face { font-family: 'Familjen Grotesk'; src: url('fonts/FamiljenGrotesk-Variable.woff2') format('woff2'); font-weight: 400 700; }+@font-face { font-family: 'JetBrains Mono'; src: url('fonts/JetBrainsMono-Regular.woff2') format('woff2'); }+:root { --bg: #0f1115; --panel: #161a21; --line: #262c37; --txt: #e6e6e6; --dim: #9aa4b2; --teal: #2dd4bf; --amber: #ffb74d; --red: #f87171; --green: #4ade80; }+* { box-sizing: border-box; }+body { margin: 0; background: var(--bg); color: var(--txt); font-family: 'Familjen Grotesk', system-ui, sans-serif; font-size: 15px; }+header { height: 44px; display: flex; align-items: center; justify-content: space-between; padding: 0 16px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--bg); z-index: 5; }+.brand { font-weight: 700; font-size: 17px; display: flex; align-items: center; gap: 8px; }+.logo { color: var(--teal); }+.study { font-weight: 500; color: var(--dim); font-size: 14px; margin-left: 10px; }+.hdr-right { display: flex; align-items: center; gap: 12px; }+.busy { color: var(--amber); font-size: 14px; }+button { font-family: inherit; }+.icon { background: none; border: 0; cursor: pointer; padding: 6px; border-radius: 6px; color: #fff; }+.icon:hover { background: #222834; }+[data-tip] { position: relative; }+[data-tip]:hover::after { content: attr(data-tip); position: absolute; right: 0; top: 110%; background: #222834; color: #fff; padding: 5px 8px; border-radius: 6px; font-size: 13px; white-space: nowrap; opacity: 0; animation: tip .2s .6s forwards; pointer-events: none; }+@keyframes tip { to { opacity: 1; } }+main { padding: 16px; display: flex; flex-direction: column; gap: 16px; max-width: 1600px; margin: 0 auto; }+.verdict { padding: 14px 18px; border-radius: 10px; font-size: 18px; font-weight: 600; border: 1px solid var(--line); }+.verdict.agree { background: #0f2a22; border-color: #1f6f5b; color: #7ff0d6; }+.verdict.disagree { background: #2b1414; border-color: #7f2a2a; color: #fca5a5; }+.verdict.pending { background: var(--panel); color: var(--dim); }+.engines { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }+.eng { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px; display: flex; flex-direction: column; gap: 8px; }+.eng .name { display: flex; align-items: center; gap: 8px; font-weight: 700; font-size: 17px; }+.sw { width: 14px; height: 14px; border-radius: 3px; display: inline-block; }+.eng .where { color: var(--dim); font-size: 13px; }+.eng .stats { font-family: 'JetBrains Mono', monospace; font-size: 13px; color: #cfd8dc; line-height: 1.6; }+.eng .row { display: flex; gap: 8px; align-items: center; }+.run { background: var(--teal); color: #0f1115; border: 0; border-radius: 7px; padding: 7px 14px; font-weight: 700; cursor: pointer; }+.run:disabled { background: #2a303b; color: var(--dim); cursor: default; }+.toggle { margin-left: auto; color: var(--dim); font-size: 13px; display: flex; gap: 6px; align-items: center; cursor: pointer; }+.state-running { color: var(--amber); } .state-done { color: var(--green); } .state-failed { color: var(--red); }+.charts { display: grid; grid-template-columns: 1.25fr 1fr; grid-template-rows: auto auto; gap: 12px; }+.chart { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; }+.chart:first-child { grid-row: span 2; }+.chart h3 { margin: 2px 0 6px; font-size: 15px; font-weight: 600; }+.chart canvas { width: 100%; display: block; }+.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 14px 16px; }+.panel h2 { margin: 0 0 4px; font-size: 18px; }+.sub { margin: 0 0 12px; color: var(--dim); font-size: 14px; }+table { width: 100%; border-collapse: collapse; font-size: 14px; }+th, td { text-align: right; padding: 7px 10px; border-bottom: 1px solid var(--line); }+th:first-child, td:first-child { text-align: left; }+th { color: var(--dim); font-weight: 600; }+td.num { font-family: 'JetBrains Mono', monospace; }+.ok { color: var(--green); font-weight: 600; } .bad { color: var(--red); font-weight: 700; }+tr.flag td { background: #2b1414; }+.outlier { outline: 2px solid var(--red); outline-offset: -2px; border-radius: 4px; }+.log #log { font-family: 'JetBrains Mono', monospace; font-size: 12.5px; color: #cfd8dc; max-height: 180px; overflow: auto; }+.modal { position: fixed; inset: 0; background: rgba(0,0,0,.55); display: flex; align-items: center; justify-content: center; z-index: 20; }+.hidden { display: none; }+.card { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; width: min(620px, 94vw); max-height: 86vh; overflow: auto; padding: 16px 18px; }+.card-hdr { display: flex; justify-content: space-between; align-items: center; }+.setrow { display: grid; grid-template-columns: 1fr 220px; gap: 10px; padding: 10px 0; border-bottom: 1px solid var(--line); align-items: center; }+.setrow .help { color: var(--dim); font-size: 13px; }+.setrow input, .setrow select { background: #0f1115; color: var(--txt); border: 1px solid var(--line); border-radius: 6px; padding: 6px 8px; font-family: inherit; width: 100%; }+.ver { color: var(--dim); font-size: 13px; margin-top: 10px; }+#toasts { position: fixed; bottom: 16px; right: 16px; display: flex; flex-direction: column; gap: 8px; z-index: 30; }+.toast { background: #222834; border-left: 4px solid var(--teal); padding: 10px 14px; border-radius: 8px; font-size: 14px; }+.hl { box-shadow: 0 0 0 3px var(--amber); transition: box-shadow .3s; }+@media (max-width: 900px) { .charts { grid-template-columns: 1fr; } .chart:first-child { grid-row: auto; } }
install.sh+3−1@@ -10,4 +10,6 @@ install_skill spice-pspice-ti skills/spice-pspice-ti/SKILL.md install_skill spice-vendor-models skills/spice-vendor-models/SKILL.md install_skill spice-portable-netlists skills/spice-portable-netlists/SKILL.md install_skill spice-licensing skills/spice-licensing/SKILL.md-echo "OK: Installed adom-spice-skillpack plus 7 bundled skills to $DEST/."+install_skill adom-spice skills/adom-spice/SKILL.md+bash "$(dirname "$0")/app/install.sh"+echo "OK: Installed adom-spice-skillpack plus 8 bundled skills and the adom-spice dashboard to $DEST/."
package.json+21−4@@ -2,8 +2,8 @@ "slug": "adom-spice-skillpack", "title": "SPICE Simulation Skills", "type": "skill",- "version": "0.1.1",- "description": "Pick and run the right SPICE simulator from an AI thread: ngspice in the Ubuntu container by default, LTspice and PSpice for TI on a Windows host through Adom Bridge for vendor models, with the licensing limits of each.",+ "version": "0.2.0",+ "description": "Pick, run and compare SPICE simulators from an AI thread: ngspice in the Ubuntu container, LTspice and PSpice for TI on a Windows host through Adom Bridge, plus the adom-spice dashboard that overlays all three and flags where they disagree.", "tags": [ "skill", "skillpack",@@ -22,7 +22,10 @@ "ngspice or ltspice", "run the TI pspice model", "can we host ltspice in a dashboard",- "spice licensing"+ "spice licensing",+ "compare ngspice ltspice and pspice",+ "do my simulators agree",+ "spice dashboard" ], "discovery_pitch": "Reach for this whenever a circuit needs simulating or a SPICE tool or vendor model has to be chosen, installed or licensed.", "sample_prompts": [@@ -55,7 +58,21 @@ "examples/buck_portable.cir", "examples/buck_portable_pspice.cir", "examples/sallen_key_ac.cir",- "examples/csdf.py"+ "examples/csdf.py",+ "skills/adom-spice/SKILL.md",+ "app/adom_spice/analysis.py",+ "app/adom_spice/engines.py",+ "app/adom_spice/server.py",+ "app/bin/adom-spice",+ "app/examples/tps54202-buck/board_ltspice.cir",+ "app/examples/tps54202-buck/board_ngspice.cir",+ "app/examples/tps54202-buck/board_pspice.cir",+ "app/examples/tps54202-buck/study.json",+ "app/install.sh",+ "app/uninstall.sh",+ "app/web/app.js",+ "app/web/index.html",+ "app/web/style.css" ], "scripts": { "install": "./install.sh",
page.json+87−3@@ -2,7 +2,91 @@ "title": "SPICE Simulation Skills", "brief": "Pick, run and license the right SPICE simulator from an AI thread: ngspice in the container by default, LTspice and PSpice for TI on a Windows host for vendor models.", "type": "skill",- "tags": ["skill", "skillpack", "spice", "simulation", "ngspice", "ltspice", "pspice", "electronics"],+ "tags": [+ "skill",+ "skillpack",+ "spice",+ "simulation",+ "ngspice",+ "ltspice",+ "pspice",+ "electronics"+ ], "visibility": "public",- "hero": { "type": "image", "path": "docs/hero.png" }-}+ "hero": {+ "type": "image",+ "path": "docs/hero.png"+ },+ "slug": "adom-spice-skillpack",+ "version": "0.2.0",+ "description": "Pick, run and compare SPICE simulators from an AI thread: ngspice in the Ubuntu container, LTspice and PSpice for TI on a Windows host through Adom Bridge, plus the adom-spice dashboard that overlays all three and flags where they disagree.",+ "dependencies": {},+ "discovery_triggers": [+ "simulate this circuit",+ "run a spice simulation",+ "which spice simulator should I use",+ "ngspice or ltspice",+ "run the TI pspice model",+ "can we host ltspice in a dashboard",+ "spice licensing",+ "compare ngspice ltspice and pspice",+ "do my simulators agree",+ "spice dashboard"+ ],+ "discovery_pitch": "Reach for this whenever a circuit needs simulating or a SPICE tool or vendor model has to be chosen, installed or licensed.",+ "sample_prompts": [+ {+ "label": "Simulate a buck",+ "prompt": "Simulate my 12 V to 5 V buck converter and check the load-step response"+ },+ {+ "label": "Vendor model",+ "prompt": "TI only gives a PSpice model for this regulator, how do we simulate it?"+ },+ {+ "label": "Pick a tool",+ "prompt": "Should we use ngspice, LTspice or PSpice for our simulation dashboard?"+ }+ ],+ "files": [+ "SKILL.md",+ "README.md",+ "package.json",+ "install.sh",+ "uninstall.sh",+ "skills/spice-choose/SKILL.md",+ "skills/spice-ngspice/SKILL.md",+ "skills/spice-ltspice/SKILL.md",+ "skills/spice-pspice-ti/SKILL.md",+ "skills/spice-vendor-models/SKILL.md",+ "skills/spice-portable-netlists/SKILL.md",+ "skills/spice-licensing/SKILL.md",+ "examples/buck_portable.cir",+ "examples/buck_portable_pspice.cir",+ "examples/sallen_key_ac.cir",+ "examples/csdf.py",+ "skills/adom-spice/SKILL.md",+ "app/adom_spice/analysis.py",+ "app/adom_spice/engines.py",+ "app/adom_spice/server.py",+ "app/bin/adom-spice",+ "app/examples/tps54202-buck/board_ltspice.cir",+ "app/examples/tps54202-buck/board_ngspice.cir",+ "app/examples/tps54202-buck/board_pspice.cir",+ "app/examples/tps54202-buck/study.json",+ "app/install.sh",+ "app/uninstall.sh",+ "app/web/app.js",+ "app/web/index.html",+ "app/web/style.css"+ ],+ "scripts": {+ "install": "./install.sh",+ "uninstall": "./uninstall.sh"+ },+ "org": "adom",+ "author": {+ "name": "John Lauer",+ "email": "[email protected]"+ }+}
skills/adom-spice/SKILL.mdadded+50@@ -0,0 +1,50 @@+---+name: adom-spice+description: The Adom SPICE dashboard - run one circuit study in ngspice (in the container), LTspice and PSpice for TI (on a Windows host through Adom Bridge), overlay the waveforms on one set of axes, measure every engine with the same code, flag where the engines disagree, and keep a ledger of simulation time and AI tokens per run. Use when simulating a circuit in more than one SPICE engine, checking that simulators agree, debugging a model or netlist translation, or showing SPICE results in a dashboard. Trigger words - adom-spice, spice dashboard, compare simulators, run in ngspice ltspice and pspice, do the simulators agree, three engine simulation, overlay waveforms, simulation ledger, spice tokens cost, pspice for ti run, ltspice run from ai.+---++Parent skill: **adom-spice-skillpack**++# Adom SPICE dashboard++Pairs with the **adom-spice-skillpack** (which engine to use, licensing, the traps). This app is the tool: one study, three engines, one verdict.++## Quick start++```bash+adom-spice --ai-thread "<name>" start+adom-spice --ai-thread "<name>" study ~/.adom/adom-spice/examples/tps54202-buck/study.json+adom-spice --ai-thread "<name>" run ngspice ltspice pspice # queued, one at a time+adom-spice --ai-thread "<name>" show # Hydrogen webview tab "Adom SPICE"+adom-spice --ai-thread "<name>" state # verdict + agreement table as JSON+```++- **ngspice** runs in this container.+- **LTspice** and **PSpice for TI** run on the Windows machine named in Settings (`bridgeTarget`) through Adom Bridge. PSpice for TI has no batch mode: the app opens the netlist, maximizes the window, clicks Run, polls the `.out` file and pulls the `.PROBE/CSDF` text output. It uses that machine's screen for a few minutes; tell the user before starting it.+- Record what the AI side cost: `adom-spice --ai-thread "<name>" tokens pspice 49099 --tool-calls 16`.+- Add a vendor-model run as a reference that is shown but does not vote: `adom-spice --ai-thread "<name>" ingest ti.csd --kind csdf --label "TI model" --signals '{"vout":"V(Rpv)","il":"I(L1)"}'`.++## The study file++`study.json` holds one netlist per engine dialect, the signal names per engine, the chart views (time windows) and the measurements (windows, kind, unit, tolerance). Every engine is measured by the same code, so a disagreement always means the engines or the netlist translations differ, never the measuring. Kinds: `mean`, `pp`, `max`, `min`, `overshoot`, `undershoot` (need `ref` window), `t_reach` (needs `frac`, `ref`), `settle` (needs `band`, `ref`). `abs_tol` per measurement; otherwise the global percent in Settings.++When engines disagree the verdict names the measurement and the outlier engine. Check that engine's netlist translation first (switch models, behavioural source syntax, `.PROBE` names), then its models.++## Licence rule built in++Settings `hideVendorTimes` (default on) hides LTspice and PSpice run times everywhere in the UI, because their licences restrict publishing benchmarks. Leave it on for anything you record or publish.++## Displaying this app (REQUIRED - read before showing anything)++To SHOW this app, use `adom-spice show` (it opens the proper Hydrogen webview tab itself). For+manual display, FIRST load the `webview` skill (adom-workspace-control) and follow it.+- **NEVER open this app in VS Code's "Simple Browser"** - not a webview in the Adom+ ecosystem: no live channel, no console read-back, no AI drivability. Using it is a bug.+- Surfaces: **wv** - Hydrogen webview panel (`webview` skill; Hydrogen's pane tab inside Hydrogen),+ **pup** (`pup` skill), the user's **real signed-in browser** (Adom browser extension),+ and **hdbw** - Hydrogen's standalone Tauri browser window (only under Hydrogen). Simple Browser is+ NEVER one of them.++## Lifecycle++One server per ai-thread (`adom-spice ls`); `start` reuses a live one. It saves state per thread and shuts itself down after `ttlHours` idle (Settings). Stop it early with `adom-spice --ai-thread "<name>" shutdown --reason "<why>"`.
uninstall.sh+3−2@@ -1,7 +1,8 @@ #!/usr/bin/env bash set -e DEST="$HOME/.claude/skills"-for s in adom-spice-skillpack spice-choose spice-ngspice spice-ltspice spice-pspice-ti spice-vendor-models spice-portable-netlists spice-licensing; do+bash "$(dirname "$0")/app/uninstall.sh" || true+for s in adom-spice adom-spice-skillpack spice-choose spice-ngspice spice-ltspice spice-pspice-ti spice-vendor-models spice-portable-netlists spice-licensing; do rm -rf "$DEST/$s" done-echo "OK: Removed adom-spice-skillpack and its 7 bundled skills from $DEST/."+echo "OK: Removed adom-spice-skillpack and its 8 bundled skills and the dashboard from $DEST/."