main
John Lauer Correct R7 clamp fault power on board27; publish exact resistor assets, simulations and forming-study evidence without… 11c16d0
"""Compare R7 fault dissipation and partial servo response; no hardware proof.

Run with PYTHONNOUSERSITE=1. The amplifier is TI's unmodified OPAx189 model.
The MOSFET remains an illustrative Level-1 model, not an IXTP15N50L2 model.
"""
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import argparse, hashlib, itertools, json, math, subprocess
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

base=Path(__file__).resolve().parent
parser=argparse.ArgumentParser()
parser.add_argument('--out',default='gate-resistor-review')
parser.add_argument('--resistance',type=int,nargs='+',default=[1000,3300,4700,6800,10000])
parser.add_argument('--compensation-nf',type=float,default=1)
parser.add_argument('--rail-v',type=float,default=13)
args=parser.parse_args()
out=base/args.out; out.mkdir(exist_ok=True)
vendor=base/'vendor/opa189/OPAx189.LIB'
# This vendor model uses PSpice switches and TEMP expressions.
(out/'.spiceinit').write_text('set ngbehavior=ps\n')

def run(case):
    resistance,kp,scale,dut,target=case
    key=f'r{resistance}-kp{kp:g}-c{scale}-dut{dut:g}'
    # Ciss-Crss and Crss at the datasheet's 25 V point, varied parametrically.
    # This does not model nonlinear capacitance or guarantee device extremes.
    deck=f'''R7 comparison: partial illustrative model, not hardware qualification
.include "{vendor}"
Vcc vcc 0 PWL(0 0 100u {args.rail_v})
Vdut dut 0 {dut}
Vcmd dac 0 PWL(0 0 20m 0 20.1m {target*.792/2} 40m {target*.792/2} 40.1m {target*.792} 80m {target*.792})
R8 dac div 33k
R9 div iset 5.6k
R10 iset 0 1k
C1 iset 0 100n
XU3 iset fb vcc 0 out OPAx189
R11 sense fb 10k
C2 out fb {args.compensation_nf}n
R7 out gate {resistance}
R6 gate 0 100k
M1 dut gate sense sense illustrative
.model illustrative NMOS (LEVEL=1 VTO=3.5 KP={kp} LAMBDA=0.01)
Cgs gate sense {4012*scale}p
Cgd gate dut {68*scale}p
Rsh sense 0 .02
Vfault fault 0 PWL(0 1 19.99m 1 20m 0 59.99m 0 60m 1)
Sclamp gate 0 fault 0 gateclamp
.model gateclamp SW(RON=10 ROFF=1e12 VT=.5 VH=.1)
.option method=gear reltol=1e-4
.control
tran 2u 80m uic
wrdata {key}.dat v(sense) v(iset) v(gate) v(out)
quit
.endc
.end
'''
    (out/(key+'.cir')).write_text(deck)
    result=subprocess.run(['ngspice','-b',key+'.cir'],cwd=out,capture_output=True,text=True,timeout=120)
    (out/(key+'.log')).write_text(result.stdout+result.stderr)
    if result.returncode or not (out/(key+'.dat')).is_file():
        return {'case':key,'error':'ngspice failed','returncode':result.returncode}
    a=np.loadtxt(out/(key+'.dat'));t=a[:,0];current=a[:,1]/.02
    power=(a[:,7]-a[:,5])**2/resistance
    windows={}
    for name,start,end,aim in [('half_load',.035,.038,target/2),('full_load',.055,.058,target),('clamped_with_command_high',.075,.078,0)]:
        selected=(t>start)&(t<end);y=current[selected]
        windows[name]={'meanA':float(y.mean()),'ripplePpA':float(np.ptp(y)),'errorA':float(y.mean()-aim),'r7PowerMeanW':float(power[selected].mean())}
    good=all(abs(w['errorA'])<.005 and w['ripplePpA']<.005 for w in windows.values())
    return {'case':key,'resistanceOhm':resistance,'kpAssumed':kp,'capacitanceScaleAssumed':scale,'dutV':dut,'targetA':target,'settledWindowScreen':good,'windows':windows,'peakCurrentA':float(current.max()),'peakR7PowerW':float(power.max()),'dataFile':key+'.dat'}

cases=[(r,k,c,v,i) for r,k,c,(v,i) in itertools.product(args.resistance,[.4,4,40],[1,3],[(5,1),(1.5,3)])]
rows=[]
with ThreadPoolExecutor(max_workers=2) as pool:
    for future in as_completed([pool.submit(run,c) for c in cases]):
        row=future.result();rows.append(row)
        print(json.dumps({'completed':len(rows),'total':len(cases),'case':row['case'],'settled':row.get('settledWindowScreen'),'error':row.get('error')}),flush=True)
rows.sort(key=lambda r:r['case'])
report={'scope':'Partial servo and sustained-clamp sensitivity screen only; no acceptance gate attestation','vendorAmplifier':{'model':'TI OPAx189 Final1.2,21JUN2022, unmodified','sha256':hashlib.sha256(vendor.read_bytes()).hexdigest()},'mosfet':'Illustrative Level-1 NMOS; not manufacturer IXTP15N50L2 model','candidateC2nF':args.compensation_nf,'assumedRailV':args.rail_v,'caseCount':len(cases),'limitations':['Rail voltage is a review assumption, not a measured or guaranteed boost ceiling','No hot MOSFET, SOA, nonlinear gate capacitance, cable inductance or DUT control-loop model','Ideal clamp omits Q2/Q3/Q4, latch, GPIO and brownout dynamics','5mA settled-window checks do not establish phase margin or overshoot safety','Actual resistor temperature, pulse limits, thermal derating and hardware validation remain required'],'rows':rows}
(out/'report.json').write_text(json.dumps(report,indent=2)+'\n')
fig,ax=plt.subplots(figsize=(10,5))
for r in args.resistance:
    y=[row['windows']['clamped_with_command_high']['r7PowerMeanW']*1000 for row in rows if row.get('resistanceOhm')==r]
    ax.scatter([str(r/1000)+' kΩ']*len(y),y,label=f'{r/1000:g} kΩ',alpha=.7)
ax.axhline(62.5,color='red',ls='--',label='CR0402 rating at ≤70°C (not measured)')
ax.set(ylabel='Simulated sustained-clamp R7 power (mW)',xlabel='R7 candidate',title=f'Gate-resistor fault comparison — illustrative MOSFET / assumed {args.rail_v:g} V rail')
ax.grid(axis='y',alpha=.25);ax.legend();fig.tight_layout();fig.savefig(out/'fault-power.png',dpi=160)
print(json.dumps({'report':str(out/'report.json'),'settledPassed':sum(r.get('settledWindowScreen',False) for r in rows),'cases':len(rows)}))