File size: 16,143 Bytes
1e8420e
 
 
 
0a53b5b
1e8420e
 
0a53b5b
 
 
 
1e8420e
 
0a53b5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e8420e
 
 
 
 
 
 
 
 
0a53b5b
 
 
 
 
 
 
 
1e8420e
 
 
 
 
 
0a53b5b
1e8420e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* Browser execution of the paper models; regression-tested against models.py. */
(function(root){
'use strict';
let dataPromise;
const load=()=>dataPromise||(dataPromise=fetch('./models-data.json',{cache:'no-store'}).then(r=>{if(!r.ok)throw Error('Model library could not load');return r.json()}));
function num(p,k,d,lo,hi){const v=Number(p[k]??d);if(!Number.isFinite(v)||v<lo||v>hi)throw Error(`${k} must be between ${lo} and ${hi}`);return v}
const linspace=(a,b,n)=>Array.from({length:n},(_,i)=>a+(b-a)*i/(n-1));
const si = () => root.OpenPELSSwitchedInductor??require('./switched-inductor.js');
const stacked = () => root.OpenPELSBuckStacked??require('./buck-stacked.js');
const isDutyBuck = id => ['si2','buck_stacked'].includes(id);
function valid(k,m){if(isDutyBuck(k))return m>=.25&&m<=.75;if(k==='sp2'||k==='rsc2')return Math.abs(m-.5)<1e-12;if(k==='buck2')return m>0&&m<1;return ['xfly2p','xfly4p','3lbuck','2sbuck','buck'].includes(k)&&m>0&&(k==='xfly4p'?m<=.25+1e-12:['xfly2p','2sbuck'].includes(k)?m<.5:m<=.5)}
function coefficients(k,d){if(k==='buck2')return [1/6,0,0];if(k==='sp2')return [2/3,.5,1/8];if(k==='xfly2p')return d<=.5?[(2+5*d)/12,d/4,0]:[(5*d*d-2*d+2)/(12*(1-d)),d*d/(4*(1-d)),(2*d-1)**2/8];if(k==='xfly4p')return [(3+Math.sqrt(5))/24*(3*d+(2+d)/Math.sqrt(5)),d/2,0];if(k==='3lbuck'||k==='buck')return [(1+Math.sqrt(3))/6*(d+(2-d)/Math.sqrt(3)),k==='3lbuck'?d/2:0,0];if(k==='2sbuck')return [(2+d-d*d)/(12*(1-d)),d/(8*(1-d)),d*d/8];throw Error('No verified loss model')}
function chargingResistance(k,n,s){return k==='sp2'?(n&&s?s/Math.tanh(s/n):n+s):Math.hypot(n,s)}
// In matched SP-SC, the same RMS branch current flows through both channels and the ESR.
function sp2LossBreakdown(fet,cap,total){
 const fsl=fet+cap;
 const rmsScale=fsl>0?total/fsl:total===0?0:null;
 return {fsl_fet:fet,fsl_cap:cap,finite_rc_increment:total-fsl,
  rms_fet:rmsScale===null?null:fet*rmsScale,rms_cap:rmsScale===null?null:cap*rmsScale};
}
function evaluate(k,m,p){if(!valid(k,m))return null;if(isDutyBuck(k)){const r=(k==='si2'?si():stacked()).evaluate(m,p);return r.min_phase_per_amp>0?r:null}if(k==='rsc2')return p.rs>0?(root.OpenPELSResonant??require('./resonant.js')).evaluate(p):null;const d=2*m,[a,b,c]=coefficients(k,d),fet=a*p.rs,cap=b*p.rc,ind=(k==='sp2'?0:.5)*p.rl,ssl=c/(p.cf*p.fs),total=ind+chargingResistance(k,fet+cap,ssl);return {fet,cap,ind,ssl,fsl:fet+cap+ind,total,...(k==='sp2'?{sp2_loss:sp2LossBreakdown(fet,cap,total)}:{}),coefficients:[a,b,k==='sp2'?0:.5,c],D:d,gate_duty:k==='buck2'?m:k==='sp2'?.5:null}}
function allocation(k,index,point){
 if(isDutyBuck(k)&&point){const areas=point.fractions.map(x=>12*x);
  return {relative:point.fractions,areas,area_fractions:point.fractions,labels:k==='buck_stacked'?['Q1a','Q1b','Q2a','Q2b','Q3a','Q3b','Q4a','Q4b']:['Q1','Q2','Q3','Q4'],total_area:12,reference_ratio:2};}
 const relative=index[k].ratio,s=relative.reduce((a,b)=>a+b,0),areas=relative.map(v=>6*v/s);return {relative,areas,area_fractions:areas.map(v=>v/12),labels:areas.map((v,i)=>'S'+(i+1)),total_area:12,reference_ratio:['buck2','sp2','rsc2'].includes(k)?2:4}}
function analyze(payload,data){
 const p={rs:num(payload,'rs_mohm',20,0,1e5)/1000,rc:num(payload,'rc_mohm',20,0,1e5)/1000,
  rl:num(payload,'rl_mohm',20,0,1e5)/1000,cf:num(payload,'cf_nf',50,.001,1e9)*1e-9,
  fs:num(payload,'fs_mhz',50,.000001,1e4)*1e6,lt:num(payload,'lt_nh',5.5,.001,1e9)*1e-9};
 const ratio=num(payload,'ratio',4,1.01,256), M=1/ratio, io=num(payload,'iout',10,.001,1e6),
  vin=num(payload,'vin',16,.001,1e6), index=Object.fromEntries(data.catalog.map(c=>[c.id,c]));
 let selected=payload.topologies??['xfly2p','xfly4p','3lbuck','2sbuck','buck'];
 if(!Array.isArray(selected)||!selected.length||selected.some(k=>!index[k]))throw Error('Select known topologies');
 selected=[...new Set(selected)];
 const siInputs=selected.some(isDutyBuck)?{...p,coupling:num(payload,'coupling',.6,0,.85),rippleScale:vin/(io*p.fs*p.lt)}:null;
 const stackInputs=selected.includes('buck_stacked')?{...siInputs,vin,load:io,gateCap:num(payload,'gate_cap_pf',25,0,100)*1e-12,coss:payload.coss_pf===null||String(payload.coss_pf).trim()===''?null:num(payload,'coss_pf',10,0,30)*1e-12}:null;
 const at=(id,m)=>evaluate(id,m,id==='buck_stacked'?stackInputs:id==='si2'?siInputs:p);
 const rows=selected.map(id=>{
  const r=at(id,M),meta=index[id];
  const row={id,name:meta.name,short:meta.short,color:meta.color,note:meta.note,formulas:data.formulas[id],
   allocation:data.formulas[id]?allocation(id,index,r):null,valid:!!r,domain:meta.range};
  if(!r)return row;
  const conductionLoss=io*io*r.total,loss=conductionLoss+(r.gate_w??0)+(r.coss_w??0),pout=vin*M*io,drop=io*(r.droop_resistance??r.total);
  const delivered=(vin*M-drop)*io;
  // The original reference cells retain their documented nominal-power metric.
  const usesDeliveredPower=['si2','sp2','rsc2','buck2','buck_stacked'].includes(id);
  const eta=usesDeliveredPower?(delivered>0?100*delivered/(delivered+conductionLoss):null):100*pout/(pout+conductionLoss);
  return Object.assign(row,r,{loss_w:loss,conduction_efficiency:eta,droop_estimate_v:drop,
    ...(id==='buck_stacked'?{efficiency_includes_coss:r.coss_w!==null,efficiency_with_events:delivered>0?100*delivered/(delivered+loss):null}:{})});
 });
 const xs=[...new Set([...linspace(.0005,.4995,500),.25,.5,M])].sort((a,b)=>a-b);
 const siSamples=[...new Set([...linspace(.25,.75,251),M])].sort((a,b)=>a-b);
 const curves=selected.map(id=>({id,name:index[id].short,color:index[id].color,
  points:(isDutyBuck(id)?siSamples:xs).flatMap(m=>{const r=at(id,m);return r?[[m,r.total*1000]]:[]})}))
  .filter(s=>s.points.length);
 return {ratio,M,vin,iout:io,parameters:p,rows,curves,provenance:data.provenance,assumptions:data.assumptions};
}
function stateModel(p){const states=p.states??[],budget=num(p,'area_budget',12,.001,1e6);if(!Array.isArray(states)||!states.length||states.length>64)throw Error('Provide 1–64 switching states');const durations=states.map(s=>num(s,'fraction',0,0,1));if(Math.abs(durations.reduce((a,b)=>a+b)-1)>1e-7)throw Error('State fractions must sum to 1');const weights={},out={};for(const field of ['switch','capacitor','inductor']){const vs=states.map(s=>s[field+'_currents']??[]);if(vs.some(a=>!Array.isArray(a)||a.length>256||a.some(v=>typeof v!=='number'||!Number.isFinite(v)||Math.abs(v)>1e6)))throw Error('Invalid normalized current');if(new Set(vs.map(a=>a.length)).size!==1)throw Error(field+' current dimensions must match in every state');weights[field]=vs[0].map((_,i)=>vs.reduce((sum,a,j)=>sum+durations[j]*a[i]**2,0));if(field==='capacitor'){const charge=vs[0].map((_,i)=>vs.reduce((sum,a,j)=>sum+durations[j]*a[i],0));if(charge.some(v=>Math.abs(v)>1e-7))throw Error('Capacitor charge balance failed: '+JSON.stringify(charge));out.capacitor_charge_residuals=charge}}
 const roots=weights.switch.map(Math.sqrt),den=roots.reduce((a,b)=>a+b,0);if(den<=0)throw Error('At least one switch must carry current');return {...out,switch_weights:weights.switch,capacitor_weights:weights.capacitor,inductor_weights:weights.inductor,optimal_areas:roots.map(v=>budget*v/den),rfet:num(p,'rs_mohm',20,0,1e5)/1000*den**2/budget,rcap:num(p,'rc_mohm',20,0,1e5)/1000*weights.capacitor.reduce((a,b)=>a+b,0),rind:num(p,'rl_mohm',20,0,1e5)/1000*weights.inductor.reduce((a,b)=>a+b,0),status:'Conditional FSL result: charge balance checked; KCL, gate legality, voltage balance and graph consistency must be independently verified. SSL is not inferred from these currents.'}}
const add=(a,b)=>[a[0]+b[0],a[1]+b[1]],mul=(a,b)=>[a[0]*b[0]-a[1]*b[1],a[0]*b[1]+a[1]*b[0]],scale=(a,b)=>[a[0]*b,a[1]*b],div=(a,b)=>{const d=b[0]**2+b[1]**2;return [(a[0]*b[0]+a[1]*b[1])/d,(a[1]*b[0]-a[0]*b[1])/d]},abs=a=>Math.hypot(...a),arg=a=>Math.atan2(a[1],a[0]);
function control(p){const vin=num(p,'vin',16,.01,1e4),D=num(p,'duty',.4,.001,.5),io=num(p,'iout',10,.001,1e5),cf=num(p,'cf_uf',2,.001,1e6)*1e-6,co=num(p,'co_uf',10,.001,1e6)*1e-6,rl=num(p,'rl_mohm',20,.001,1e4)/1000,lk=num(p,'lk_nh',200,.01,1e9)*1e-9,lm=num(p,'lm_uh',2,0,1e6)*1e-6,fs=num(p,'fs_khz',500,.1,1e6)*1e3,fc=num(p,'fc_khz',5,.001,fs/1e3/4)*1e3,fp=Math.min(fc*10,fs/3),vo=D*vin/2-rl*io/2;if(vo<=0)throw Error('The requested load exceeds the positive-output equilibrium of this model');const load=vo/io,ldm=lk+2*lm,plant=f=>div([vin,0],add(mul([rl,lk*2*Math.PI*f],[1/load,co*2*Math.PI*f]),[2,0])),ki=2*Math.PI*fc*Math.hypot(1,fc/fp)/abs(plant(fc)),frequency=linspace(1,Math.log10(fs/2),1000).map(v=>10**v),phase=f=>arg(plant(f))-Math.PI/2-Math.atan(f/fp)-2*Math.PI*f/fs;const loop_db=frequency.map(f=>20*Math.log10(abs(plant(f))*ki/(2*Math.PI*f*Math.hypot(1,f/fp)))),loop_phase=frequency.map(f=>phase(f)*180/Math.PI),gcm_db=frequency.map(f=>20*Math.log10(abs(plant(f)))),gdm_db=frequency.map(f=>{const w=2*Math.PI*f,n=[-(io*rl+D*vin),-io*ldm*w],d=[2*(D*D-ldm*cf*w*w),2*rl*cf*w];return 20*Math.log10(abs(div(n,d)))});let unity_crossings=0;for(let i=1;i<loop_db.length;i++)if(Math.sign(loop_db[i])!==Math.sign(loop_db[i-1]))unity_crossings++;return {frequency,loop_db,loop_phase,gcm_db,gdm_db,fc,f_dm:D/(2*Math.PI*Math.sqrt(ldm*cf)),f_cm:Math.sqrt((2+rl/load)/(lk*co))/(2*Math.PI),phase_margin:180+phase(fc)*180/Math.PI,unity_crossings,ki,fp,vo,note:'XFLY6S symmetric nonoverlap CCM example only. Unity feedback/PWM gain, resistive load, stiff source, one-period delay. The voltage loop does not damp an unobservable differential mode; input-filter interaction requires an impedance model.'}}
async function inspect(p,data){if(typeof p.image!=='string'||!/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=\r\n]+$/.test(p.image)||p.image.length>11_000_000)throw Error('Upload a PNG, JPEG or WebP image under 8 MB');if(!p.api_key)return {configured:false,requires_review:true,summary:'Image received. Connect a vision model to extract the circuit graph, or choose and review a library model below.',candidate_id:'unknown',confidence:0,components:[],gates:[],magnetic_coupling:[],uncertainties:['No inference token was provided. No image recognition has been performed.'],analysis_plan:['Enter an inference token or use a manually reviewed library model.']};
 const body={model:p.model||'Qwen/Qwen2.5-VL-72B-Instruct',max_tokens:3500,temperature:.1,messages:[{role:'system',content:data.vision_prompt},{role:'user',content:[{type:'text',text:'Transcribe this circuit and flag uncertain connections. User-supplied operating conditions (claims to verify): '+String(p.operating_notes||'').slice(0,4000)},{type:'image_url',image_url:{url:p.image}}]}]};let r;try{r=await fetch('https://router.huggingface.co/v1/chat/completions',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+p.api_key},body:JSON.stringify(body),signal:AbortSignal.timeout(90000)})}catch(e){throw Error('Vision provider could not be reached. Check connection, browser access, token and model availability.')}if(!r.ok)throw Error(`Vision provider returned HTTP ${r.status}. Check inference permissions, model availability and quota.`);const result=await r.json();const content=result.choices?.[0]?.message?.content;if(typeof content!=='string')throw Error('Vision provider returned an unsupported response');let d;try{d=JSON.parse(content.trim().replace(/^```(?:json)?\s*|\s*```$/g,''))}catch(e){throw Error('Vision response was not valid circuit JSON. Try a clearer schematic or another vision model.')}if(!d||Array.isArray(d)||typeof d!=='object')throw Error('Circuit interpretation must be a JSON object');const out={summary:String(d.summary||''),candidate_id:data.catalog.some(c=>c.id===d.candidate_id)?d.candidate_id:'unknown',confidence:Number.isFinite(Number(d.confidence))?Math.max(0,Math.min(1,Number(d.confidence))):0,state_table:d.state_table&&typeof d.state_table==='object'&&!Array.isArray(d.state_table)?d.state_table:null};for(const k of ['components','gates','magnetic_coupling','uncertainties','analysis_plan','model_conditions','derivation'])out[k]=Array.isArray(d[k])?d[k]:d[k]?[String(d[k])]:[];return {...out,configured:true,requires_review:true,model:body.model,notice:'AI interpretation only. Confirm graph and modulation before using a library model.'}}
function analyzePU(payload,data){
 const rho_c=num(payload,'rho_c',1,0,1e6),rho_l=num(payload,'rho_l',1,0,1e6),rho_q=num(payload,'rho_q',20,0,1e9),ratio=num(payload,'ratio',4,1.01,256),M=1/ratio,index=Object.fromEntries(data.catalog.map(c=>[c.id,c]));
 let selected=payload.topologies??['xfly2p','xfly4p','3lbuck','2sbuck','buck'];if(!Array.isArray(selected)||!selected.length||selected.some(k=>!index[k]))throw Error('Select known topologies');selected=[...new Set(selected)];
 const rho_t=num(payload,'rho_t',.61,1e-9,1e9);
 const si_coupling=num(payload,'si_coupling',.6,0,.85),
       si_ripple=num(payload,'si_ripple',.75,0,10000), si_duty=payload.si_duty==null?M:num(payload,'si_duty',.5,.25,.75);
 const result=(k,m)=>{if(!valid(k,m))return null;
 if(isDutyBuck(k))return evaluate(k,m,{rs:1,rc:rho_c,rl:rho_l,coupling:si_coupling,rippleScale:si_ripple});if(k==='rsc2')return rho_q>0?evaluate(k,m,{rs:1,rc:rho_c,rl:rho_l,cf:1/rho_q,fs:1,lt:rho_t}):null;const [a,b,c]=coefficients(k,2*m),fet=a,cap=b*rho_c,ind=(k==='sp2'?0:.5)*rho_l,ssl=c*rho_q;const net=fet+cap,ssl_series=k==='sp2'?chargingResistance(k,net,ssl)-net:(net||ssl)?ssl*ssl/(Math.hypot(net,ssl)+net):0;const total=ind+chargingResistance(k,net,ssl);return {fet,cap,ind,ssl,ssl_series,fsl:fet+cap+ind,total,...(k==='sp2'?{sp2_loss:sp2LossBreakdown(fet,cap,total)}:{}),coefficients:[a,b,k==='sp2'?0:.5,c],D:2*m,gate_duty:k==='buck2'?m:k==='sp2'?.5:null}};
 const rows=selected.map(id=>{const r=result(id,isDutyBuck(id)?si_duty:M),meta=index[id];return {id,name:meta.name,short:meta.short,color:meta.color,note:meta.note,formulas:data.formulas[id],allocation:data.formulas[id]?allocation(id,index,r):null,valid:!!r,domain:meta.range,...(r||{})}});
 const xs=[...new Set([...linspace(.0005,.4995,500),.25,.5,M])].sort((a,b)=>a-b),curves=selected.map(id=>({id,name:index[id].short,color:index[id].color,points:(isDutyBuck(id)?[...new Set([...linspace(.25,.75,251),si_duty])].sort((a,b)=>a-b):xs).flatMap(m=>{const r=result(id,m);return r?[[m,r.total]]:[]})})).filter(s=>s.points.length);
 return {ratio,M,normalization:{base:'R_S',rho_c,rho_l,rho_q,...(selected.includes('rsc2')?{rho_t}:{}),...(selected.some(isDutyBuck)?{si_coupling,si_ripple,si_duty}:{}),component_unit:'R/R_S',coefficient_bases:['R_S','R_C','R_L','1/(C_F f_s)']},rows,curves,provenance:'XFLY-IEEE Section V-F, Table I; Figures 18–20. Dimensionless form of the current manuscript models.',assumptions:[
 'Rs is the common resistance base. rho_C=Rc/Rs; rho_L=Rl/Rs; rho_Q=1/(Cf fs Rs). No absolute resistance, current or power is assigned.',
 'Table columns k_FET=RFET/Rs, k_CAP=RCAP/Rc, k_IND=RIND/Rl and k_SSL=RSSL Cf fs are independent coefficients. These columns are not directly additive. Coefficients remain defined when their corresponding loss scale is zero.',
 ...data.assumptions.filter(s=>!s.startsWith('Conduction efficiency'))]};
}
function stateModelPU(p){const out=stateModel({...p,rs_mohm:1000,rc_mohm:1000,rl_mohm:1000}),{rfet,rcap,rind,...rest}=out;return {...rest,k_fet:rfet,k_cap:rcap,k_ind:rind,bases:{k_fet:'R_S',k_cap:'R_C',k_ind:'R_L'},normalization:'Currents / Iout; areas / A0; resistances as coefficients of Rs, Rc, Rl. SSL requires a separate charge-transfer model.'}}
async function api(path,p={}){const data=await load();if(path==='/api/catalog')return data.catalog;if(path==='/api/health')return {ok:true,vision_configured:false,execution:'browser'};if(path==='/api/analyze-pu')return analyzePU(p,data);if(path==='/api/state-model-pu')return stateModelPU(p);if(path==='/api/analyze')return analyze(p,data);if(path==='/api/control')return control(p);if(path==='/api/state-model')return stateModel(p);if(path==='/api/inspect')return inspect(p,data);throw Error('Unknown analysis request')}
const engine={api,analyze,analyzePU,evaluate,control,stateModel,stateModelPU,valid,sp2LossBreakdown};root.OpenPELSEngine=engine;if(typeof module!=='undefined')module.exports=engine;
})(typeof window!=='undefined'?window:globalThis);