main
John Lauer Publish 0.2.0 ca99db7
"""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}