Spaces:
Running
Running
Download static/compare/app.js from minjiechen/OpenPELS: direct link, hf CLI and curl.
- Browser
- Download file 68.6 kB
-
https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/static/compare/app.js
- Command line
-
hf download hf://spaces/minjiechen/OpenPELS/static/compare/app.js
-
curl -L -o app.js https://huggingface.co/spaces/minjiechen/OpenPELS/resolve/main/static/compare/app.js
68.6 kB
| ; | |
| const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)]; | |
| const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); | |
| const fmt=(v,n=3)=>Number(v).toLocaleString('en-US',{minimumFractionDigits:n,maximumFractionDigits:n}); | |
| let focusedTopology=null; | |
| const isDutyBuck = id => ['si2','buck_stacked'].includes(id); | |
| const isSI = () => isDutyBuck(focusedTopology) && ratio===2; | |
| const isStacked = () => focusedTopology==='buck_stacked' && ratio===2; | |
| let ratio=4,catalog=[],selected=new Set(['xfly2p','xfly4p','3lbuck','2sbuck','buck']),report=null,imageData=null,timer,requestId=0; | |
| async function api(path,p){return window.OpenPELSEngine.api(path,p)} | |
| function toast(text){$('#toast').textContent=text;$('#toast').hidden=false;clearTimeout(timer);timer=setTimeout(()=>$('#toast').hidden=true,5000)} | |
| function download(name,body,type='image/svg+xml'){const u=URL.createObjectURL(new Blob([body],{type})),a=document.createElement('a');a.href=u;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(u),1000)} | |
| function params(){ | |
| const duty=sp2Analysis?.operating_point?.duty; | |
| return {ratio,topologies:[...selected],...(isSI()?{si_duty:duty??.5}:{}), | |
| ...Object.fromEntries(['rho_c','rho_l','rho_q','rho_t','si_coupling','si_ripple'].map(k=>[k,Number($('#'+k).value)]))}; | |
| } | |
| function equivalent(r){ | |
| const resonant=['si2','rsc2','buck_stacked'].includes(r.id),boost=r.id==='boost',unknown=r.id==='ns',ratioText=unknown?'1 : M':boost?`1 : ${ratio}`:`${isDutyBuck(r.id)&&r.gate_duty?fmt(1/r.gate_duty):ratio} : 1`,M=unknown?null:boost?ratio:isDutyBuck(r.id)&&r.gate_duty?r.gate_duty:1/ratio; | |
| const ink='#455c50',teal='#157e70',orange='#bb7d37',blue='#62869d',value=v=>r.valid?fmt(v)+' Rₛ':'not derived'; | |
| const blocks=[{x:480,key:'R_FET',sub:'S',v:r.coefficients?.[0],base:'Rₛ'},{x:600,key:'R_CAP',sub:'C',v:r.coefficients?.[1],base:'R꜀'},{x:720,key:'R_IND',sub:'L',v:r.coefficients?.[2],base:'Rₗ'}]; | |
| return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1120 380" role="img" aria-label="${esc(r.short)} ideal DC transformer, FSL series losses, charging increment, and separate gate-drive and Coss accounting shunts"><title>${esc(r.short)} power-loss equivalent circuit</title><rect width="1120" height="380" fill="white"/> | |
| <g fill="none" stroke="${ink}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M35 110H165M165 230V284M35 284H1080M240 230V284M240 110H480M565 110H600M685 110H720M805 110H900M985 110H1080"/><path d="M165 110c20 0 20 30 0 30c20 0 20 30 0 30c20 0 20 30 0 30c20 0 20 30 0 30M240 110c-20 0 -20 30 0 30c-20 0 -20 30 0 30c-20 0 -20 30 0 30c-20 0 -20 30 0 30"/><path d="M200 106V234M207 106V234" stroke="#90a394" stroke-width="1.5"/> | |
| ${[330,415].map((x,i)=>`<path d="M${x} 110V169M${x} 221V284" stroke="${blue}"/><rect data-loss="${i?'R_OSS':'R_GATE'}" x="${x-12}" y="169" width="24" height="52" fill="#f1f5f8" stroke="${blue}" stroke-dasharray="5 3"/><circle cx="${x}" cy="110" r="3" fill="${ink}"/><circle cx="${x}" cy="284" r="3" fill="${ink}"/>`).join('')} | |
| <path d="M480 160V169H805V160" stroke="${teal}" stroke-width="1.4"/> | |
| ${blocks.map(b=>`<rect data-loss="${b.key}" x="${b.x}" y="96" width="85" height="29" fill="#eef5ef" stroke="${teal}"/>`).join('')} | |
| <rect data-loss="R_SSL_SERIES" x="900" y="96" width="85" height="29" fill="#faf2e6" stroke="${orange}"/> | |
| ${[35,1080].flatMap(x=>[110,284].map(y=>`<circle cx="${x}" cy="${y}" r="4" fill="white"/>`)).join('')} | |
| <path d="M1010 75H1055l-7 -4m7 4l-7 4"/></g> | |
| <g fill="${ink}" font-family="Arial,Helvetica,sans-serif" text-anchor="middle"><text x="203" y="43" font-size="23" fill="${teal}">${ratioText}</text><text x="203" y="64" font-size="11">Ideal averaged DC conversion</text><text x="49" y="87" font-size="18">V<tspan baseline-shift="sub" font-size="12">in</tspan></text><text x="280" y="87" font-size="15">Vx</text><text x="1065" y="87" font-size="18">V<tspan baseline-shift="sub" font-size="12">out</tspan></text><text x="1030" y="61" font-size="15">Iout</text> | |
| ${blocks.map(b=>`<text x="${b.x+42}" y="84" font-size="18">R<tspan baseline-shift="sub" font-size="12">${b.sub}</tspan></text><text x="${b.x+42}" y="147" font-size="15" fill="${teal}">${r.valid?Number(b.v.toPrecision(4))+' '+b.base:'unknown'}</text>`).join('')} | |
| <text x="330" y="155" font-size="17" fill="${blue}">Rg</text><text x="415" y="155" font-size="17" fill="${blue}">Ross</text><text x="330" y="244" font-size="11" fill="${blue}">gate drive</text><text x="415" y="244" font-size="11" fill="${blue}">Coss loss</text><text x="373" y="263" font-size="10" fill="${blue}">FOM example panel</text> | |
| <text x="643" y="194" font-size="18" fill="${teal}">R<tspan baseline-shift="sub" font-size="12">${resonant?'RMS':'FSL'}</tspan> = ${value(r.fsl)}</text><text x="942" y="84" font-size="17" fill="${orange}">R<tspan baseline-shift="sub" font-size="11">SSL,add</tspan></text><text x="942" y="147" font-size="15" fill="${orange}">${value(r.ssl_series)}</text> | |
| <rect x="858" y="171" width="210" height="64" rx="5" fill="#fcf7ee" stroke="#e6d5b8"/><text x="963" y="195" font-size="16" fill="${orange}">R<tspan baseline-shift="sub" font-size="11">SSL</tspan> = ${value(r.ssl)}</text><text x="963" y="218" font-size="11" fill="${orange}">${resonant?'No separate charging term':'estimated charge-sharing limit'}</text><text x="650" y="244" font-size="14">${M!==null?`M = ${fmt(M)} · Req / Rs = ${r.valid?fmt(r.total):'unknown'}`:'State model required'}</text> | |
| <text x="350" y="320" font-size="13" fill="${blue}">Vx = M Vin · Rg = Vx²/Pg · Ross = Vx²/Poss</text><text x="865" y="320" font-size="12">${resonant?'Req = RFET + RCAP + RIND':'Req = RFSL + RSSL,add'}</text><text x="560" y="351" font-size="12" fill="#7b898e">Shunts account for loss power; series loss uses load current only. Gate supply is tracked separately.</text><text x="560" y="372" font-size="11" fill="#7b898e">Device-transition data are required for Coss energy; Qoss alone is insufficient.</text></g></svg>`; | |
| } | |
| function dieAllocation(r){ | |
| const a=r.allocation;if(!a)return ''; | |
| const width=r.id===focusedTopology&&typeof sp2Analysis!=='undefined'?sp2Analysis?.deviceReport?.parameters.width_mm:null; | |
| const si=isDutyBuck(r.id),stacked=r.id==='buck_stacked',split=r.id==='xfly2p'; | |
| const ratios={xfly2p:'1 : 1 : 1 : 3',xfly4p:'1 : 1 : 1 : √5','3lbuck':'1 : 1 : √3 : √3','2sbuck':'1 : 1 : 1 : 3',buck:'1 : 1 : √3 : √3',buck2:'1 : 1',sp2:'1 : 1 : 1 : 1',rsc2:'1 : 1 : 1 : 1'}; | |
| const sizing=si?`Upper / lower width = ${fmt(a.areas[0]/a.areas[stacked?2:1])}`:ratios[r.id]; | |
| const n=stacked?4:2; | |
| const columns=si?[a.areas.slice(0,n),a.areas.slice(n)]:[a.areas,a.areas]; | |
| const blocks=columns.map((areas,col)=>{let y=24;const prefix=['S','Q'][col];return areas.map((area,i)=>{const h=216*area/6,label=si?a.labels[n*col+i]:split?[prefix+'1',prefix+'2a',prefix+'2b',prefix+'3'][i]:prefix+(i+1),x=18+col*100,color=Math.abs(area-Math.min(...a.areas))<1e-10?'#dd544c':'#217db6';const out=`<g data-device="${label}" data-area="${area}"><title>${label}: ${fmt(area)} A₀; ${fmt(area/12*100,1)}% of total die area${width?'; '+fmt(area*width/12,3)+' mm used width':''}</title><rect x="${x}" y="${y}" width="80" height="${h}" fill="${color}"/><text x="${x+40}" y="${y+h/2}" dominant-baseline="central" text-anchor="middle" fill="white" font-size="15" font-weight="bold">${label}</text></g>`;y+=h+7;return out}).join('')}).join(''); | |
| return `<figure class="die-allocation"><figcaption>DIE AREA ALLOCATION</figcaption><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 216 315" role="img" aria-label="${esc(r.short)} die area allocation ${sizing}; total area 12 A0"><rect x="4" y="8" width="208" height="270" rx="4" fill="#e0f4bc"/>${blocks}<text x="108" y="301" text-anchor="middle" font-size="12" fill="#526b5e">${sizing}</text></svg><p>Block area ∝ transistor area<br>Total: 12 A₀ · ${si?'sized for selected duty':'fixed at '+a.reference_ratio+':1'}${split?'<br>S2 = S2a + S2b in series; Q2 likewise.':''}</p></figure>`; | |
| } | |
| function sp2ComparisonLoss(row){ | |
| const loss=row.sp2_loss; | |
| if(!loss)return ''; | |
| const value=r=>r==null?'undefined':fmt(r)+' Rₛ'; | |
| return `<p class="device-note" data-sp2-loss-view="physical"><strong>Physical finite-RC conduction</strong> · MOSFET ${value(loss.rms_fet)} · capacitor ESR ${value(loss.rms_cap)}. The FSL baselines plus finite-RC increment give the same total.</p>`; | |
| } | |
| function cards(){ | |
| $('#circuits').innerHTML=report.rows.map(r=>{const meta=catalog.find(c=>c.id===r.id),sub=r.id==='xfly2p'?'Six-switch cell · two-command reference':r.id==='xfly4p'?'Split-middle cell · four-pulse reference':meta.family;return `<article class="circuit-card" data-topology="${r.id}"><div class="topology"><h2>${esc(meta.name)}</h2><div class="sub">${esc(sub)}</div><div class="topology-visuals"><img src="./assets/${['xfly2p','xfly4p','3lbuck','2sbuck','buck'].includes(r.id)?meta.asset.replace('.svg','-loss.svg'):meta.asset}" alt="${esc(meta.name)} ${['sp2','rsc2','si2','buck_stacked'].includes(r.id)?'topology schematic':'topology with individual device resistance labels'}">${dieAllocation(r)}</div>${r.allocation?`<p class="device-note">${isDutyBuck(r.id)?'Duty-dependent die allocation.':'Fixed '+r.allocation.reference_ratio+':1 die allocation; each device value is an on-resistance.'} ${isDutyBuck(r.id)?'Switches sized from their RMS currents. Output capacitor ESR is included.':r.id==='rsc2'?'Matched flying capacitors and series inductors.':r.id==='sp2'?'Equal flying capacitors; no power inductors.':'Clamp ESR = 0 in clamp-cell models.'}${isDutyBuck(r.id)?'':' Input/output capacitor ESR is omitted.'}</p>`:''}</div><div class="equivalent"><div class="eq-heading"><span>IDEAL CONVERSION + LOSS MODEL</span><span class="eq-value ${r.valid?'':'unsupported'}">${r.valid?'Req / RS = '+fmt(r.total):'No numerical loss model'}</span></div><div class="equivalent-drawing">${equivalent(r)}</div><span class="scroll-note">Swipe to view the full loss circuit →</span><div class="eq-caption"><p>${r.valid?`${isDutyBuck(r.id)?'Piecewise-linear CCM RMS · ':r.id==='rsc2'?'Exact periodic RLC · ':r.id==='sp2'?'Exact periodic RC · ':''}${isDutyBuck(r.id)?'RMS loss / RS = '+fmt(r.fsl):r.resonant?'Tank RMS loss / RS = '+fmt(r.fsl):'RFSL / RS = '+fmt(r.fsl)+' · RSSL,add / RS = '+fmt(r.ssl_series)} · Rg and Ross: see FOM example`:esc(r.domain)}</p><button data-svg="${r.id}">↓ SVG</button></div>${r.valid?`<div class="components">${['RFET','RCAP','RIND','RSSL'].map((n,i)=>`<span>${r.id==='sp2'&&i<2?n+',FSL':n}/RS <b>${fmt(r[['fet','cap','ind','ssl'][i]])}</b></span>`).join('')}</div>${sp2ComparisonLoss(r)}`:''}</div></article>`}).join(''); | |
| $$('[data-svg]').forEach(b=>b.onclick=()=>download('openpels-'+b.dataset.svg+'-equivalent.svg',$(`[data-topology="${b.dataset.svg}"] .equivalent-drawing svg`).outerHTML)); | |
| $('#coefficients').innerHTML=report.rows.map(r=>`<div class="formula"><b>${esc(r.short)}</b> · ${esc(r.domain)}${(r.formulas||['Not derived for this topology.']).map((f,i)=>`<code>${r.id==='buck_stacked'?'':(['RFET','RCAP','RIND','RSSL'][i]+' = ')}${esc(f)}</code>`).join('')}<p>${esc(r.note)}</p></div>`).join(''); | |
| } | |
| function picker(){ | |
| const ids=OpenPELSRecommendation.familyIds(ratio),groups=[[`${ratio}:1 coupled-inductor cancellation family`,catalog.filter(c=>ids.includes(c.id))]]; | |
| if(ratio===2)groups.push(['Duty-regulated switched inductor',catalog.filter(c=>isDutyBuck(c.id))]); | |
| if(ratio===2)groups.push(['Fixed 2:1 switched-capacitor references',catalog.filter(c=>['sp2','rsc2'].includes(c.id))]); | |
| $('#topology-picker').innerHTML=groups.map(([label,items])=>`<div class="picker-group"><span>${label}</span><div>${items.map(c=>`<button data-topology-choice="${c.id}" class="${selected.has(c.id)?'active':''}" aria-pressed="${selected.has(c.id)}">${selected.has(c.id)?'✓ ':''}${esc(c.short)}</button>`).join('')}</div></div>`).join(''); | |
| $$('[data-topology-choice]').forEach(b=>b.onclick=()=>{const id=b.dataset.topologyChoice;if(selected.has(id)){if(typeof isDedicatedReference==='function'&&isDedicatedReference()&&id===focusedTopology){toast('The focused reference stays in this comparison.');return}if(selected.size===1){toast('Keep at least one topology selected.');return}selected.delete(id)}else selected.add(id);picker();update(typeof manualSp2Weights!=='undefined'&&manualSp2Weights)}); | |
| } | |
| async function update(useEnteredWeights=false){const id=++requestId;try{ | |
| if(typeof isDedicatedReference==='function'&&isDedicatedReference()){ | |
| const base=(await api('/api/analyze-pu',{ratio:2,topologies:[focusedTopology]})).rows[0]; | |
| if(id!==requestId)return; | |
| prepareSp2Analysis(base,useEnteredWeights); | |
| if (isSI()) updateLoadSummary(); | |
| reportOperatingPoint(true); | |
| } | |
| const result=selected.size?await api('/api/analyze-pu',params()):{rows:[],curves:[],M:1/ratio,normalization:{rho_c:1,rho_l:1,rho_q:20}};if(id!==requestId)return;report=result;$('#si-model').hidden=![...selected].some(isDutyBuck);for(const id of ['si_coupling','si_ripple'])$('#'+id).parentElement.hidden=![...selected].some(isDutyBuck);$('#resonant-model').hidden=!selected.has('rsc2');$('#rho_t').parentElement.hidden=!selected.has('rsc2');cards();renderRecommendation();$('#status').textContent=`Step-down ${ratio}:1 · M = ${fmt(isSI()?(sp2Analysis?.operating_point?.idealGain??.5):1/ratio)} · RS base · ${isSI()?'positive-current CCM':(selected.has('sp2')||selected.has('rsc2'))?'fixed switched-capacitor reference':'cancellation-point family only'} · ${isSI()?'duty-dependent area allocation':'fixed loss-sizing allocations'}${selected.has('boost')?' · boost uses ratio 1:'+ratio:''}`;if($('#sweep-section').open){drawSweep();drawSIOperatingSweep()}}catch(e){$('#status').textContent='Check inputs';toast(e.message)}} | |
| function chart(id,series,{xlabel='',ylabel='',logx=false,logy=false,xrange,yrange,marker=null,hline=null,cursorLabel='M'}={}){ | |
| const host=$('#'+id);const W=Math.max(310,host.clientWidth),H=280,L=55,R=16,T=15,B=45;const all=series.flatMap(s=>s.points).filter(p=>p.every(Number.isFinite)); | |
| if(!all.length){host.innerHTML='<p class="muted">No supported numerical model selected.</p>';return} | |
| const tx=v=>logx?Math.log10(v):v,ty=v=>logy?Math.log10(Math.max(v,1e-12)):v; | |
| let [xmin,xmax]=xrange||[Math.min(...all.map(p=>p[0])),Math.max(...all.map(p=>p[0]))]; | |
| let [ymin,ymax]=yrange||[Math.min(...all.map(p=>p[1])),Math.max(...all.map(p=>p[1]))]; | |
| if(ymax===ymin){ymax+=1;ymin-=1}const X=v=>L+(tx(v)-tx(xmin))/(tx(xmax)-tx(xmin))*(W-L-R),Y=v=>H-B-(ty(v)-ty(ymin))/(ty(ymax)-ty(ymin))*(H-B-T); | |
| let svg=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(ylabel+' versus '+xlabel)}"><title>${esc(ylabel+' versus '+xlabel)}</title><defs><clipPath id="clip-${id}"><rect x="${L}" y="${T}" width="${W-L-R}" height="${H-B-T}"/></clipPath></defs><rect width="${W}" height="${H}" fill="white"/>`; | |
| const xt=logx?Array.from({length:Math.floor(Math.log10(xmax))-Math.ceil(Math.log10(xmin))+1},(_,i)=>10**(Math.ceil(Math.log10(xmin))+i)):Array.from({length:W<450?4:6},(_,i)=>xmin+(xmax-xmin)*i/(W<450?3:5)); | |
| const yt=logy?[1,2,5,10,20,50,100,200,500,1000,2000,5000,10000].filter(v=>v>=ymin&&v<=ymax):Array.from({length:6},(_,i)=>ymin+(ymax-ymin)*i/5); | |
| const tick=v=>v>=1e6?fmt(v/1e6,0)+'M':v>=1000?fmt(v/1000,0)+'k':Math.abs(v)<1&&v!==0?fmt(v,2):fmt(v,0); | |
| for(const v of yt)svg+=`<path d="M${L},${Y(v)}H${W-R}" stroke="#e9eeea"/><text x="${L-12}" y="${Y(v)+4}" text-anchor="end" fill="#91a09e" font-family="Arial" font-size="10">${tick(v)}</text>`; | |
| for(const v of xt)svg+=`<path d="M${X(v)},${T}V${H-B}" stroke="#f2f4f1"/><text x="${X(v)}" y="${H-B+21}" text-anchor="middle" fill="#91a09e" font-family="Arial" font-size="10">${logx?tick(v):fmt(v,2)}</text>`; | |
| if(marker&&marker>=xmin&&marker<=xmax)svg+=`<path d="M${X(marker)},${T}V${H-B}" stroke="#c9a46a" stroke-dasharray="4 5"/><text x="${Math.min(X(marker)+7,W-100)}" y="${T+14}" fill="#aa8448" font-family="Arial" font-size="9">Design point</text>`; | |
| if(hline!==null)svg+=`<path d="M${L},${Y(hline)}H${W-R}" stroke="#a7b5b1" stroke-dasharray="3 4"/>`; | |
| for(const s of series){const pts=s.points.filter(p=>p.every(Number.isFinite));if(pts.length===1)svg+=`<circle data-fixed-ratio="true" cx="${X(pts[0][0])}" cy="${Y(pts[0][1])}" r="4" fill="${s.color}"/>`;const d=pts.map((p,i)=>`${i?'L':'M'}${X(p[0]).toFixed(2)},${Y(p[1]).toFixed(2)}`).join(' ');svg+=`<path d="${d}" fill="none" stroke="${s.color}" stroke-width="2.3" stroke-linejoin="round" clip-path="url(#clip-${id})"/>`} | |
| svg+=`<text x="${(L+W-R)/2}" y="${H-8}" text-anchor="middle" fill="#81928c" font-family="Arial" font-size="10">${esc(xlabel)}</text><text transform="translate(15,${(T+H-B)/2}) rotate(-90)" text-anchor="middle" fill="#81928c" font-family="Arial" font-size="10">${esc(ylabel)}</text><path id="cursor-${id}" stroke="#bac9c2" stroke-dasharray="3 3" visibility="hidden"/><rect class="hit" x="${L}" y="${T}" width="${W-L-R}" height="${H-B-T}" fill="transparent"/></svg><div class="chart-tooltip" hidden></div>`; | |
| host.innerHTML=svg;const canvas=host.querySelector('svg'),tip=host.querySelector('.chart-tooltip'),cursor=host.querySelector('#cursor-'+id); | |
| canvas.addEventListener('pointermove',e=>{const point=canvas.createSVGPoint();point.x=e.clientX;point.y=e.clientY;const p=point.matrixTransform(canvas.getScreenCTM().inverse());if(p.x<L||p.x>W-R)return;let xx=tx(xmin)+(p.x-L)/(W-L-R)*(tx(xmax)-tx(xmin));if(logx)xx=10**xx;let lines=[];for(const s of series){const a=s.points;if(a.length===1?Math.abs(X(a[0][0])-p.x)>9:xx<a[0][0]||xx>a.at(-1)[0])continue;let nearest=a.reduce((a,b)=>Math.abs(a[0]-xx)<Math.abs(b[0]-xx)?a:b);lines.push(`${esc(s.name)}: ${fmt(nearest[1])}`)}tip.innerHTML=`<b>${logx?fmt(xx,0)+' Hz':esc(cursorLabel)+' = '+fmt(xx,3)}</b><br>${lines.join('<br>')}`;tip.hidden=false;tip.style.left=Math.min(e.clientX-host.getBoundingClientRect().left+12,host.clientWidth-170)+'px';tip.style.top='35px';cursor.setAttribute('d',`M${p.x},${T}V${H-B}`);cursor.setAttribute('visibility','visible')});canvas.addEventListener('pointerleave',()=>{tip.hidden=true;cursor.setAttribute('visibility','hidden')}); | |
| } | |
| function drawSweep(){if(!report)return;chart('rout-chart',report.curves,{xlabel:'Nominal Vout / Vin',ylabel:'Req / Rs (p.u.)',logy:true,xrange:[0,[...selected].some(isDutyBuck)?.75:.5],yrange:[Math.max(.001,Math.min(...report.curves.flatMap(s=>s.points.map(p=>p[1])))*.8),Math.max(50,...report.curves.filter(s=>s.points.length===1).map(s=>1.15*s.points[0][1]))],marker:isSI()?report.normalization.si_duty:report.M});$('#legend').innerHTML=report.curves.map(s=>`<span><i style="background:${s.color}"></i>${s.name}</span>`).join('')} | |
| let siSweepRows=[]; | |
| function setSISweepDefaults() { | |
| const point=sp2Analysis?.operating_point?.inputs; | |
| const axis=OpenPELSOperatingPoint.definition(focusedTopology)?.analysis_sweep_axes[$("#si-sweep-axis").value]; | |
| if (!axis)return; | |
| const bases={input_voltage_v:point?.input_voltage_v??3,output_current_a:point?.load.value??1, | |
| switching_frequency_mhz:(point?.switching_frequency_hz??2e6)/1e6}; | |
| const scale=axis.basis?bases[axis.basis]:1; | |
| $("#si-sweep-start").value=Number((axis.start*scale).toPrecision(7)); | |
| $("#si-sweep-stop").value=Number((axis.stop*scale).toPrecision(7)); | |
| } | |
| function drawSIOperatingSweep(){ | |
| const panel=$("#si-operating-sweep"); | |
| panel.hidden=!isSI(); | |
| if (!isSI())return; | |
| const axes=OpenPELSOperatingPoint.definition(focusedTopology).analysis_sweep_axes; | |
| if (!$("#si-sweep-axis").options.length) | |
| $("#si-sweep-axis").replaceChildren(...Object.entries(axes).map(([id,entry])=>new Option(entry.label,id))); | |
| if ($("#si-sweep-start").value==="")setSISweepDefaults(); | |
| const result=sp2Analysis, row=result?.winner; | |
| const axis=$("#si-sweep-axis").value; | |
| const [start,stop,count]=["start","stop","count"].map(k=>$("#si-sweep-"+k).valueAsNumber); | |
| siSweepRows=[]; | |
| $("#si-export-sweep").disabled=true; | |
| const info=$("#si-sweep-status"), host=$("#si-voltage-chart"); | |
| host.replaceChildren(); | |
| if (!row) { | |
| info.textContent="Choose a feasible design to sweep at its sized width."; | |
| return; | |
| } | |
| if (!(start>0&&stop>start&&Number.isInteger(count)&&count>=2&&count<=51)) { | |
| info.textContent="Use positive increasing endpoints and 2–51 points."; | |
| return; | |
| } | |
| const model=OpenPELSSwitchedInductor, p=result.deviceReport.parameters; | |
| // Freeze the selected silicon design, including the upper and lower widths. | |
| const channels=isStacked()?2:1; | |
| const high=channels*row.device[0].ron,low=channels*row.device[channels].ron,dcr=p.rl_mohm/1000,esr=p.rc_mohm/1000; | |
| for (let i=0;i<count;i++) { | |
| const value=start+i*(stop-start)/(count-1); | |
| try { | |
| const inputs=OpenPELSOperatingPoint.sweepCommand(result.operating_point.inputs,axis,value); | |
| const vin=inputs.input_voltage_v,load=inputs.load.value,fs=inputs.switching_frequency_hz; | |
| const winding=p.si_l_nh*1e-9,coupling=p.si_coupling; | |
| const point=OpenPELSOperatingPoint.resolve(focusedTopology,inputs, | |
| model.operatingAdapter({vin,load,fs,winding,coupling,high,low,dcr})); | |
| if (!point.solver.valid) throw Error(point.solver.diagnostics.join(" ")); | |
| const c=model.currents(point.duty,coupling,vin/(fs*winding*load)); | |
| const req=2*(high*c.high_weight+low*c.low_weight+dcr*c.winding_weight)+esr*c.capacitor_weight; | |
| const delivered=load*point.analyticalVoltage; | |
| const auxiliary=(result.deviceReport.gate_power+(row.coss_power??0))*fs/(p.fs_mhz*1e6)*(isStacked()?(vin/p.vin)**2:1); | |
| siSweepRows.push({value,target_v:point.target,duty:point.duty,ideal_v:point.idealVoltage, | |
| analytical_v:point.analyticalVoltage,loaded_gain:point.loadedGain,req_ohm:req, | |
| efficiency:delivered/(delivered+load*load*req+auxiliary),status:"CCM", | |
| vin_v:vin,load_a:load,frequency_hz:fs,efficiency_includes_coss:row.coss_power!==null}); | |
| } catch (error) { | |
| siSweepRows.push({value,status:error.message}); | |
| } | |
| } | |
| const points=siSweepRows.filter(r=>r.status==="CCM"); | |
| info.textContent=`${points.length} of ${count} points inside the loaded positive-current CCM range. Device widths remain fixed.`; | |
| $("#si-export-sweep").disabled=false; | |
| const curves=[]; | |
| let line; | |
| for (const row of siSweepRows) { | |
| if (row.status!=="CCM"){line=null;continue;} | |
| if (!line) { | |
| line={name:"Analytical loaded output",color:"#436864",points:[]}; | |
| curves.push(line); | |
| } | |
| line.points.push([row.value,row.analytical_v]); | |
| } | |
| if(curves.length)chart("si-voltage-chart",curves,{xlabel:axes[axis].label, | |
| ylabel:"Loaded output (V)",cursorLabel:axes[axis].label}); | |
| } | |
| $("#si-sweep-axis").onchange=()=>{setSISweepDefaults();drawSIOperatingSweep()}; | |
| $("#si-run-sweep").onclick=drawSIOperatingSweep; | |
| $("#si-export-sweep").onclick=()=>{ | |
| const columns=["value","target_v","duty","ideal_v","analytical_v","loaded_gain","req_ohm","efficiency","status","vin_v","load_a","frequency_hz"]; | |
| if(isStacked()) columns.push("efficiency_includes_coss"); | |
| const csv=[columns.join(","),...siSweepRows.map(row=>columns.map(k=>JSON.stringify(row[k]??"")).join(","))]; | |
| download(isStacked()?"openpels-buck-stacked-operating-sweep.csv":"openpels-si-operating-sweep.csv",csv.join("\n"),"text/csv"); | |
| }; | |
| $('#sweep-section').addEventListener('toggle',()=>{if($('#sweep-section').open){drawSweep();drawSIOperatingSweep()}}); | |
| $$('[data-ratio]').forEach(b=>b.onclick=()=>{ratio=Number(b.dataset.ratio);updateLoadSummary();selected=new Set(OpenPELSRecommendation.familyIds(ratio));$$('[data-ratio]').forEach(v=>v.classList.toggle('active',v===b));picker();update()}); | |
| $('#apply-weights').onclick=()=>update(true);$('#reset').onclick=()=>{for(const [k,v] of Object.entries({rho_c:1,rho_l:1,rho_q:20,rho_t:.61,si_coupling:.6,si_ripple:.75}))$('#'+k).value=v;$('#toast').hidden=true;clearTimeout(timer);update(true)}; | |
| const sp2LossColumns=[ | |
| ['SP2_RFET_fsl_pu','fsl_fet'],['SP2_RCAP_fsl_pu','fsl_cap'], | |
| ['SP2_R_finite_rc_increment_pu','finite_rc_increment'], | |
| ['SP2_RFET_finite_rc_pu','rms_fet'],['SP2_RCAP_finite_rc_pu','rms_cap'], | |
| ]; | |
| function quoteCSV(rows){ | |
| return rows.map(row=>row.map(v=>'"'+String(v??'').replaceAll('"','""')+'"').join(',')).join('\n'); | |
| } | |
| $('#export-csv').onclick=()=>{ | |
| if(!report)return; | |
| const hasTank=report.rows.some(r=>r.id==='rsc2'),hasSI=report.rows.some(r=>isDutyBuck(r.id)), | |
| hasSP2=report.rows.some(r=>r.id==='sp2'); | |
| const header=['Topology','Target_ratio','kFET_Rs','kCAP_Rc','kIND_Rl','kSSL_over_Cf_fs', | |
| 'RFET_pu','RCAP_pu','RIND_pu','RSSL_pu','Req_pu','RFSL_pu','RSSL_add_pu','Switching_loss_scope', | |
| 'rho_C','rho_L','rho_Q','Model_domain',...(hasTank?['rho_T']:[]), | |
| ...(hasSI?['Duty','Coupling','Vin_over_L_fs_Iout']:[]), | |
| ...(hasSP2?sp2LossColumns.map(([label])=>label):[])]; | |
| const rows=report.rows.map(r=>[r.short,ratio,...(r.valid?r.coefficients:['','','','']), | |
| ...['fet','cap','ind','ssl','total','fsl','ssl_series'].map(k=>r.valid?r[k]:''), | |
| r.resonant?'Tank RMS partition in RFSL_pu; independent SSL and charging increment are inapplicable. Separate gate and optional Coss.': | |
| r.id==='sp2'?'RFET_pu and RCAP_pu are FSL baselines. Physical finite-RC terms sum independently to Req. Separate gate and optional Coss.': | |
| 'Separate technology example; Coss requires energy data', | |
| report.normalization.rho_c,report.normalization.rho_l,report.normalization.rho_q,r.domain, | |
| ...(hasTank?[r.id==='rsc2'?report.normalization.rho_t:'']:[]), | |
| ...(hasSI?isDutyBuck(r.id)?[report.normalization.si_duty,report.normalization.si_coupling,report.normalization.si_ripple]:['','','']:[]), | |
| ...(hasSP2?sp2LossColumns.map(([,key])=>r.sp2_loss?.[key]):[])]); | |
| download('openpels-per-unit-comparison.csv',quoteCSV([header,...rows]),'text/csv'); | |
| }; | |
| $('#open-upload').onclick=()=>$('#upload-dialog').showModal();$('#close-upload').onclick=()=>$('#upload-dialog').close(); | |
| async function loadImage(file){if(!file)return;if(!['image/png','image/jpeg','image/webp'].includes(file.type)||file.size>8000000){toast('Choose a PNG, JPEG or WebP smaller than 8 MB.');return}imageData=await new Promise((resolve,reject)=>{const r=new FileReader();r.onload=()=>resolve(r.result);r.onerror=reject;r.readAsDataURL(file)});$('#image-preview').src=imageData;$('#image-preview').hidden=false;$('#inspect').disabled=false;$('#upload-status').textContent=file.name+' · ready for interpretation';$('#interpretation').hidden=true} | |
| $('#image-upload').onchange=e=>loadImage(e.target.files[0]);$('#dropzone').ondragover=e=>{e.preventDefault();$('#dropzone').classList.add('drag')};$('#dropzone').ondragleave=()=>$('#dropzone').classList.remove('drag');$('#dropzone').ondrop=e=>{e.preventDefault();$('#dropzone').classList.remove('drag');loadImage(e.dataTransfer.files[0])}; | |
| $('#inspect').onclick=async()=>{const b=$('#inspect');b.disabled=true;$('#upload-status').textContent='Reading circuit connections…';try{const d=await api('/api/inspect',{image:imageData,api_key:$('#api-key').value,model:$('#vision-model').value,operating_notes:$('#operating-notes').value});$('#interpretation').hidden=false;const candidate=catalog.find(c=>c.id===d.candidate_id);$('#interpretation').innerHTML=`<p>${esc(d.summary)}</p><p>Candidate: <b>${esc(candidate?.name||'not identified')}</b></p><ul>${d.uncertainties.map(v=>'<li>'+esc(v)+'</li>').join('')}</ul><details><summary>Review extracted connections and model conditions</summary><pre>${esc(JSON.stringify({components:d.components,gates:d.gates,magnetic_coupling:d.magnetic_coupling,model_conditions:d.model_conditions,derivation:d.derivation},null,2))}</pre><p>${esc(candidate?.note||'An unfamiliar topology needs its own state and loss derivation.')}</p></details>${d.configured&&candidate?'<label><input type="checkbox" id="confirm-model"> I checked the connections, winding polarity where applicable, and gate sequence against this reference model.</label><button id="apply-model" class="primary" disabled>Show topology and equivalent circuit →</button>':''}`; | |
| if($('#confirm-model')){$('#confirm-model').onchange=e=>$('#apply-model').disabled=!e.target.checked;$('#apply-model').onclick=()=>{if(!OpenPELSRecommendation.referenceFamilyIds(ratio).includes(d.candidate_id)){toast('This topology has no qualified reference model at the selected ratio.');return}selected.add(d.candidate_id);picker();update();$('#upload-dialog').close()}} | |
| if(d.state_table){const area=document.createElement('textarea');area.rows=9;area.value=JSON.stringify(d.state_table,null,2);const button=document.createElement('button'),result=document.createElement('pre');button.textContent='Evaluate reviewed FSL state table';button.onclick=async()=>{try{const r=await api('/api/state-model-pu',JSON.parse(area.value));result.textContent=JSON.stringify(r,null,2)}catch(e){result.textContent=e.message}};$('#interpretation').append(area,button,result)} | |
| $('#upload-status').textContent=d.configured?'Review required before using the reference equations.':'No inference token: image recognition has not been performed.'; | |
| }catch(e){$('#upload-status').textContent=e.message}finally{$('#api-key').value='';b.disabled=false}}; | |
| const techFields=[['fs_mhz','fs (MHz)',10],['vgs','VGS (V)',3.3],['width_mm','Total FET width (mm)',360],['cap_uf','Flying + clamp budget (μF)',4],['rc_mohm','Main-cap ESR (mΩ)',20],['rl_mohm','Winding ESR (mΩ)',38],['events','Gate charges / period',1],['eoss_pj','Effective Eoss (pJ/mm/cycle)','']]; | |
| $('#tech-settings').innerHTML=techFields.map(([k,label,v])=>`<label>${label}<input id="tech-${k}" type="number" value="${v}" min="0" step="any" placeholder="unknown"></label>`).join(''); | |
| const sp2DesignColumns=[ | |
| ['FSL_MOSFET_W','fsl_fet'],['FSL_capacitor_ESR_W','fsl_cap'], | |
| ['Finite_RC_increment_W','finite_rc_increment'],['Physical_MOSFET_W','rms_fet'], | |
| ['Physical_capacitor_ESR_W','rms_cap'], | |
| ]; | |
| function sp2DesignLoss(report){ | |
| const row=report.rows.find(r=>r.sp2_loss); | |
| if(!row)return ''; | |
| const currentSquared=report.parameters.io**2,loss=row.sp2_loss; | |
| const power=key=>fmt(1000*currentSquared*loss[key]); | |
| const total=fmt(row.conduction_power*1e3); | |
| return `<table><caption>SP-SC series loss at the calculated device settings</caption><thead><tr><th>Loss calculation</th><th>MOSFET (mW)</th><th>Capacitor ESR (mW)</th><th>Finite-RC increment (mW)</th><th>Total (mW)</th></tr></thead><tbody> | |
| <tr><th>FSL baselines plus increment</th><td>${power('fsl_fet')}</td><td>${power('fsl_cap')}</td><td>${power('finite_rc_increment')}</td><td>${total}</td></tr> | |
| <tr><th>Physical finite-RC RMS</th><td>${power('rms_fet')}</td><td>${power('rms_cap')}</td><td>Included in RMS terms</td><td>${total}</td></tr></tbody></table> | |
| <button data-export-sp2-loss>Download SP-SC loss CSV</button>`; | |
| } | |
| let technologyReport; | |
| function technologyParameters(){return Object.fromEntries(techFields.filter(([k])=>k!=='eoss_pj'||$('#tech-'+k).value.trim()!=='').map(([k])=>[k,Number($('#tech-'+k).value)]))} | |
| function renderTechnology(){if(!report)return;try{ | |
| const switchedCap=typeof isDedicatedReference==='function'&&isDedicatedReference(); | |
| const p=technologyParameters();const design=designParameters(); | |
| if(!isSI()){const point=OpenPELSRecommendation.operatingPoint(design);p.vin=point.parameters.vin;p.io=point.output_current;}if(selected.has('rsc2')&&!switchedCap)p.tank_nh=Number($('#design-tank_nh').value);technologyReport=switchedCap?sp2Analysis?.deviceReport:OpenPELSTechnology.example(report.rows,p); | |
| if(!technologyReport)throw Error(sp2Error||'Enter a positive flying-capacitor budget for the device calculation.'); | |
| $('#export-technology').disabled=false;const t=technologyReport,unit=(v,scale=1)=>v==null?'unknown':!Number.isFinite(v)?'∞':fmt(v*scale); | |
| $('#technology-status').textContent=`Rs = ${fmt(t.rs*1e3)} mΩ · RΣ = ${fmt(t.parallel*1e3)} mΩ · gate demand = ${fmt(t.gate_power*1e3)} mW · ${switchedCap?'same sized device result as the loss lineup':'physical example is separate from the per-unit weights above'}`; | |
| $('#technology-results').innerHTML=`<table><caption>${switchedCap?(isSI()?'Optimized-width switched inductor · winding and capacitor RMS loss.':focusedTopology==='rsc2'?'Resonant SC equal-area constrained optimum · exact periodic RLC.':'Optimized-width SP-SC result · exact linear periodic RC.'):'Fixed-width example: flat-current buck models; exact linear periodic RC for SP-SC. Not measured efficiency.'}</caption><thead><tr><th>Topology</th><th>${isSI()?'Cout':'CF each'} (μF)</th><th>RFET (mΩ)</th><th>RCAP (mΩ)</th><th>RIND (mΩ)</th><th>RHC,add (mΩ)</th><th>Req (mΩ)</th><th>Rg at Vx (Ω)</th><th>Ross at Vx (Ω)</th><th>Iout²Req + Pg + known Poss (mW)</th></tr></thead><tbody>${t.rows.map(r=>r.valid?`<tr><th>${esc(report.rows.find(a=>a.id===r.id).short)}</th><td>${r.cf?unit(r.cf,1e6):'—'}</td>${['fet','cap','ind','hc','req'].map(k=>`<td>${(k==='ind'&&r.id==='sp2'||k==='hc'&&['rsc2','si2','buck_stacked'].includes(r.id))?'N/A':unit(r[k],1e3)}</td>`).join('')}<td>${unit(r.gate_r)}</td><td>${unit(r.oss_r)}</td><td>${unit(r.partial_loss,1e3)}${r.poss===null?' + unknown Coss':''}</td></tr>`:`<tr><th>${esc(r.id)}</th><td colspan="9">Outside the supported analytical model</td></tr>`).join('')}</tbody></table>`; | |
| $('#sp2-design-loss').innerHTML=sp2DesignLoss(t); | |
| const exportLoss=$('[data-export-sp2-loss]'); | |
| if(exportLoss)exportLoss.onclick=()=>{ | |
| const row=t.rows.find(r=>r.sp2_loss),currentSquared=t.parameters.io**2; | |
| download('openpels-sp2-loss-breakdown.csv',quoteCSV([ | |
| ['Output_current_A',...sp2DesignColumns.map(([label])=>label),'Series_loss_W'], | |
| [t.parameters.io,...sp2DesignColumns.map(([,key])=>currentSquared*row.sp2_loss[key]),row.conduction_power], | |
| ]),'text/csv'); | |
| }; | |
| }catch(e){technologyReport=null;$('#technology-status').textContent=e.message;$('#technology-results').innerHTML='';$('#sp2-design-loss').innerHTML='';$('#export-technology').disabled=true}} | |
| $('#apply-technology').onclick=()=>document.body.classList.contains('sp2-focused')?update():renderTechnology();$('#export-technology').onclick=()=>{if(technologyReport)download('openpels-180nm-example.json',JSON.stringify({...technologyReport,source:'User-supplied XFLY_Power_Analysis.md; not independently verified foundry data',method:document.body.classList.contains('sp2-focused')?(isSI()?'Piecewise-linear positive-current CCM with separate gate and optional Coss energy.':focusedTopology==='rsc2'?'Exact periodic RLC with separate gate and optional effective Coss energy.':'Exact periodic RC plus separate gate and optional effective Coss energy; Qoss does not establish Eoss'):'Paper FSL/SSL interpolation; separate gate demand; Qoss does not establish Eoss'},(k,v)=>typeof v==='number'&&!Number.isFinite(v)?String(v):v,2),'application/json')}; | |
| (function rcChart(){const w=600,h=210,x=a=>45+(Math.log10(a)+2)/4*530,y=v=>175-(Math.log10(v)+.3)/3*155,points=fn=>Array.from({length:161},(_,i)=>{const a=10**(-2+i/40);return `${x(a)},${y(fn(a))}`}).join(' ');$('#rc-limit-chart').innerHTML=`<svg viewBox="0 0 ${w} ${h}" role="img" aria-label="Finite RC event resistance and its SSL and FSL limits on log axes"><defs><clipPath id="rc-plot-clip"><rect x="45" y="15" width="530" height="160"/></clipPath></defs><rect width="600" height="210" fill="white"/><path d="M45 15V175H575" fill="none" stroke="#a6b6aa"/><g clip-path="url(#rc-plot-clip)"><polyline points="${points(a=>1/Math.tanh(a/2))}" fill="none" stroke="#157e70" stroke-width="2"/><polyline points="${points(a=>2/a)}" fill="none" stroke="#5c70b8" stroke-dasharray="5 4"/><polyline points="${points(()=>1)}" fill="none" stroke="#cf7b30" stroke-dasharray="5 4"/></g><g font-family="Arial" font-size="10" fill="#526b5e"><text x="65" y="18">Revent / RSSL · log axis</text><text x="340" y="18">green: finite RC · blue: FSL · orange: SSL</text>${[.01,.1,1,10,100].map(a=>`<text x="${x(a)}" y="190" text-anchor="middle">${a}</text>`).join('')}${[1,10,100].map(v=>`<text x="36" y="${y(v)+3}" text-anchor="end">${v}</text>`).join('')}<text x="310" y="207" text-anchor="middle">d / (fs Rpath C) · log axis</text></g></svg>`})(); | |
| const designFields=[ | |
| ['vout','Output voltage (V)',.825],['io','Output current (A)',2],['fs_mhz','Frequency (MHz)',10], | |
| ['budget_mode','Silicon budget','area','select',[['area','Die area + Ron × area'],['width','Total FET width']]], | |
| ['die_mm2','Total die area (mm²)',1],['utilization','Usable transistor fraction',.5],['ron_area_mohm_mm2','Ron × area (mΩ·mm²)',1],['width_mm','Maximum FET width (mm)',360], | |
| ['cap_uf','Flying / clamp budget (μF)',4],['max_caps','Maximum flying / clamp caps',4],['max_windings','Maximum power windings',2],['rc_mohm','Main-cap ESR (mΩ)',20],['rl_mohm','DCR per winding (mΩ)',38],['tank_nh','Series inductance per leg (nH)',5.5],['si_mode','Voltage operating mode','duty_cycle','select',[['duty_cycle','Duty cycle'],['output_voltage','Output voltage']]], | |
| ['si_target_v','Target output voltage (V)',1.5],['si_duty','High-side duty',.5],['si_l_nh','Self-inductance per winding (nH)',1000],['si_coupling','Inverse coupling magnitude',.6],['lk_nh','Leakage Lk per winding (nH)',50],['lm_uh','Magnetizing Lm (μH)',1],['max_phase_ripple_percent','Max phase ripple pp (% avg)',5],['max_drop_percent','Maximum estimated droop (%)',10], | |
| ['objective','Priority','loss','select',[['loss','Lowest modeled loss'],['capacitors','Fewest capacitors, then loss'],['magnetics','Fewest power windings, then loss']]] | |
| ]; | |
| $('#design-fields').innerHTML=designFields.map(([k,label,value,type,options])=>`<label data-design-field="${k}">${label}${type==='select'?`<select id="design-${k}">${options.map(([v,t])=>`<option value="${v}" ${value===v?'selected':''}>${t}</option>`).join('')}</select>`:`<input id="design-${k}" type="number" value="${value}" min="0" step="any">`}</label>`).join(''); | |
| const loadBudgetField=$('[data-design-field="budget_mode"]');$('#design-fields').insertBefore($('#load-summary'),loadBudgetField); | |
| let recommendationReport; | |
| function designParameters(){ | |
| const fields=Object.fromEntries(designFields | |
| .filter(([k])=>k.startsWith('si_')?isSI():k!=='tank_nh'||focusedTopology==='rsc2') | |
| .map(([k,label,value,type])=>[k,type==='select'?$('#design-'+k).value:Number($('#design-'+k).value)])); | |
| if(!isSI())return {ratio,voltage_mode:'output_ratio',load_mode:'current',...fields}; | |
| const {vout:vin,si_mode,si_target_v,si_duty,...values}=fields; | |
| return {ratio,vin,voltage_mode:si_mode,load_mode:'current',...values, | |
| ...(si_mode==='output_voltage'?{si_target_v}:{si_duty})}; | |
| } | |
| function showVoltageMode(){ | |
| const target=isSI()&&$('#design-si_mode').value==='output_voltage'; | |
| $('[data-design-field="si_target_v"]').hidden=!target; | |
| $('[data-design-field="si_duty"]').hidden=target; | |
| } | |
| $('#design-si_mode').addEventListener('change',showVoltageMode); | |
| function showBudgetFields(){const mode=$('#design-budget_mode').value;for(const k of ['die_mm2','utilization','ron_area_mohm_mm2'])$(`[data-design-field="${k}"]`).hidden=mode!=='area';$('[data-design-field="width_mm"]').hidden=mode!=='width'} | |
| showBudgetFields();$('#design-budget_mode').onchange=showBudgetFields; | |
| function updateLoadSummary(){ | |
| try{ | |
| if (isSI()) { | |
| const op=sp2Analysis?.operating_point; | |
| if(!op){ | |
| $('#load-summary').textContent=sp2Error||'Enter an operating point to calculate the loaded output.'; | |
| return; | |
| } | |
| const label=op.target==null?'':`Target ${fmt(op.target,4)} V · `; | |
| $('#load-summary').textContent=`${label}Command duty ${fmt(op.duty,6)} · Ideal ${fmt(op.idealVoltage,5)} V · Analytical loaded ${fmt(op.analyticalVoltage,5)} V · Ideal gain ${fmt(op.idealGain,6)} · Loaded gain ${fmt(op.loadedGain,6)} · ${fmt(op.analyticalVoltage/sp2Analysis.output_current,4)} Ω · ${fmt(op.analyticalVoltage*sp2Analysis.output_current)} W.`; | |
| return; | |
| } | |
| const op=OpenPELSRecommendation.operatingPoint(designParameters()); | |
| $('#load-summary').innerHTML=`<div><span>Calculated load resistance R<sub>load</sub></span><strong>${fmt(op.load_resistance,4)} Ω</strong></div><div><span>Calculated output power</span><strong>${fmt(op.output_power)} W</strong></div><p>Derived input voltage: ${ratio} × ${fmt(op.requested_vout)} V = <b>${fmt(op.parameters.vin)} V</b>. Output voltage and current stay fixed when the ratio changes.</p>`}catch(e){$('#load-summary').textContent=e.message}}updateLoadSummary(); | |
| function inspectRecommendation(id){const r=recommendationReport?.rows.find(r=>r.id===id);if(!r||r.status!=='eligible')return; | |
| if(document.body.classList.contains('sp2-focused')){ | |
| $('#analysis-workbench').open=true;update();$('#analysis-workbench').scrollIntoView({behavior:'smooth',block:'start'});return | |
| } | |
| selected=new Set([id]);const p=recommendationReport.parameters;$('#rho_c').value=(p.rc_mohm/1000/r.rs).toPrecision(8);$('#rho_l').value=(p.rl_mohm/1000/r.rs).toPrecision(8);$('#rho_q').value=r.cf?(1/(r.cf*p.fs_mhz*1e6*r.rs)).toPrecision(8):0;$('#analysis-workbench').open=true;$('#inspection-context').textContent=`${r.short}: ${fmt(r.width_mm)} mm total FET width, Rs = ${fmt(r.rs*1e3)} mΩ, modeled loss = ${fmt(r.loss*1e3)} mW. Reference die-map proportions are scaled to this width; A₀ = ${fmt(r.width_mm/12)} mm of width. The shortlist uses the common full-budget RS base; these diagrams use the actual sized-device Rs. The device example below is a separate reference calculation.`;picker();update();$('#analysis-workbench').scrollIntoView({behavior:'smooth',block:'start'})} | |
| let comparisonView='scoreboard'; | |
| function lossScoreboard(t){const data=t.loss_scoreboard;if(!data.rows.length)return ''; | |
| const switchedCap=t.rows[0]?.id==='sp2', resonant=t.rows[0]?.id==='rsc2', si=isDutyBuck(t.rows[0]?.id); | |
| const lossValue=(d,m)=>d.powers[m.id]===null?(m.id==='ind'?'N/A':'Unknown'):`${fmt(d.powers[m.id]*1e3,2)} <small>mW</small>`;const byId=Object.fromEntries(t.eligible.map(r=>[r.id,r]));const rating=n=>n==null?'—':String(n),tone=n=>n==null?'neutral':n>=66?'good':n>=33?'mid':'weak'; | |
| return `<section class="loss-scoreboard" aria-label="Loss mechanism scoreboard"><div class="scoreboard-intro"><b>THE LOSS LINEUP</b><span>Higher score = lower modeled loss · actual values in mW</span></div><div class="scoreboard-scroll"><table style="--teams:${data.rows.length}"><thead><tr><th class="mechanism-heading">Compare the same<br>mechanism across circuits</th>${data.rows.map(d=>{const r=byId[d.id];return `<th class="team-heading"><span class="team-family">${r.native_ratio}:1 FAMILY</span><h3>${esc(r.short)}</h3><img src="./assets/${r.asset.replace('.svg','-candidate.svg')}" alt="${esc(r.name)} topology"><div class="team-total">${fmt(d.total*1e3,1)} <small>mW</small></div><span class="team-total-label">TOTAL MODELED LOSS</span><div class="loss-mix" aria-label="Loss composition">${data.mechanisms.filter(m=>d.powers[m.id]!=null).map(m=>`<span style="width:${d.total?d.powers[m.id]/d.total*100:0}%;background:${m.color}" title="${m.name}: ${fmt(d.powers[m.id]*1e3,2)} mW"></span>`).join('')}</div><span class="team-rout">Rout ${fmt(r.rout*1e3,2)} mΩ</span></th>`}).join('')}</tr></thead><tbody>${data.mechanisms.map(m=>`<tr data-loss-mechanism="${m.id}"><th><span class="mechanism-symbol" style="color:${m.color}">${m.symbol}</span><span>${m.name}</span>${switchedCap&&['fet','cap'].includes(m.id)?'<small>Fast-switching baseline</small>':''}${m.id==='charging'?'<small>Finite-charge addition only</small>':''}</th>${data.rows.map(d=>`<td data-score-team="${d.id}" data-score-value="${d.ratings[m.id]??''}"><div class="mechanism-stat"><span class="mechanism-rating ${tone(d.ratings[m.id])}">${rating(d.ratings[m.id])}</span><strong>${lossValue(d,m)}</strong></div><div class="attribute-track"><span class="${tone(d.ratings[m.id])}" style="width:${d.ratings[m.id]??0}%"></span></div></td>`).join('')}</tr>`).join('')}${switchedCap?'':`<tr class="unquantified-row"><th>${resonant||si?'Core / dead time':'Coss / core / ripple'}<small>Outside the current loss model</small></th>${data.rows.map(()=>'<td>Not quantified<span>No score assigned</span></td>').join('')}</tr>`}<tr class="tradeoff-row"><th>PRO / TRADEOFF<small>Against the other displayed circuits</small></th>${data.rows.map(d=>`<td><p class="score-pro">+ ${esc(d.pro)}${d.pro_delta!=null?`<small>${fmt(d.pro_delta*1e3,2)} mW less than others’ mean</small>`:''}</p><p class="score-con">↔ ${esc(d.con)}${d.con_delta!=null?`<small>${fmt(d.con_delta*1e3,2)} mW more than others’ mean</small>`:''}</p><p class="score-resources">${byId[d.id].capacitors} caps · ${byId[d.id].windings} windings<br>${fmt(byId[d.id].width_mm,1)} mm FET width</p><button data-inspect-design="${d.id}">Inspect circuit →</button></td>`).join('')}</tr></tbody></table></div><p class="scoreboard-note">${esc(data.scale)} Unknown losses are not scored as zero. The stacked color strip shows each mechanism’s share of modeled loss; ratings compare mechanisms separately.</p><details class="scoreboard-method"><summary>What is included in each loss?</summary><p>${si?'Winding and channel RMS currents set resistive loss. Output-capacitor ESR uses the summed winding ripple. Gate and optional Coss energy are tracked separately.':resonant?'The periodic tank RMS current gives switch conduction, flying-capacitor ESR and inductor DCR losses. Gate demand and any entered Coss energy are separate. Core and dead-time effects are unquantified.':switchedCap?'Conduction and ESR are the fast-switching baseline. The finite-charge addition is Iout² (Req − RFSL). The exact finite-RC path dissipation is represented by the baseline plus this increment; the raw SSL asymptote is never summed again. Gate demand is separate. Coss is included once when effective energy is provided. Winding DCR and magnetic losses are not applicable.':`Switch = Iout² RFET; capacitor = Iout² RCAP; winding = Iout² RIND; charging = Iout² (Req − RFSL); gate = the FOM-based gate-drive demand. These five terms sum to the displayed modeled total. The raw RSSL asymptote is not added again. Coss, core and ripple corrections remain unquantified. Pros and tradeoffs identify the largest mW difference versus the mean of the other displayed circuits; ratings are recalculated when this comparison set changes.`}</p></details></section>`; | |
| } | |
| function setComparisonView(view){comparisonView=view;$('#loss-scoreboard-view').hidden=view!=='scoreboard';$('#candidate-cards-view').hidden=view!=='circuits';$$('[data-comparison-view]').forEach(b=>{b.classList.toggle('active',b.dataset.comparisonView===view);b.setAttribute('aria-pressed',String(b.dataset.comparisonView===view))})} | |
| function renderRecommendation(){if(!catalog.length)return; | |
| const switchedCap=typeof isDedicatedReference==='function'&&isDedicatedReference(); | |
| try{ | |
| if(switchedCap&&!sp2Analysis)throw Error(sp2Error||'Enter valid fixed-ratio design inputs.'); | |
| recommendationReport=switchedCap?sp2Analysis:OpenPELSRecommendation.recommend(designParameters(),{catalog},OpenPELSEngine,OpenPELSTechnology); | |
| if(!switchedCap&&typeof focusRecommendation==='function')recommendationReport=focusRecommendation(recommendationReport); | |
| recommendationReport.loss_scoreboard=OpenPELSScores.build(recommendationReport);$('#design-error').textContent='';$('#recommend-design').textContent=switchedCap?'Update design':'Update candidates';$('#export-recommendation').disabled=false;const t=recommendationReport,p=t.parameters,native=t.native_models; | |
| $('#family-context').textContent=switchedCap?(isSI()?'Duty-regulated switched inductor · 2:1 nominal at 50%':focusedTopology==='rsc2'?'Fixed 2:1 resonant SC · two uncoupled series-RLC legs':'Fixed 2:1 switched-capacitor reference · 50% duty · two flying capacitors'):native?`${ratio}:1 cancellation family · ${native} coupled-inductor candidates. Complementary winding excitation or ideal midpoint hold is admitted; estimated phase ripple must satisfy the entered limit.`:`${ratio}:1 · no verified coupled-inductor cancellation-point model in the current library. Off-duty and uncoupled circuits are omitted.`; | |
| $('#candidate-status').textContent=t.eligible.length?`${t.eligible.length} candidates meet the current limits · Rload = ${fmt(t.load_resistance,4)} Ω. Inspect any panel to review its model.`:!native?'No qualified coupled-inductor cancellation-point model is available for this ratio.':!t.voltage_ratio_match?'The requested output voltage does not match this ratio’s nominal cancellation point.':'No candidate passes the current constraints. Expand the excluded candidates below for reasons.'; | |
| const candidatePanel=r=>{ | |
| const supported=!!OpenPELSRecommendation.specs[r.id],eligible=r.status==='eligible'; | |
| if(!supported)return `<p class="unmodeled-candidate"><b>${esc(r.short)}</b> · ${r.reasons.map(esc).join('; ')}</p>`; | |
| const image=r.asset.replace('.svg','-candidate.svg'); | |
| return `<article class="candidate-panel ${eligible?'':'candidate-excluded'}" data-candidate="${r.id}" data-candidate-status="${r.status}"><div class="candidate-heading"><span class="candidate-rank">${eligible?'#'+r.rank:'Not eligible'}</span><span class="candidate-family">${r.native_ratio}:1 ${isSI()?'nominal':switchedCap?'fixed ratio':'cancellation point'}</span></div><h3>${esc(r.name)}</h3><div class="candidate-drawing"><img src="./assets/${image}" alt="${esc(r.name)} schematic" loading="lazy"></div>${eligible?`<div class="candidate-metrics"><div><strong>${fmt(r.loss*1e3,1)} mW</strong><span>Modeled loss</span></div><div><strong>${fmt(r.rout*1e3,2)} mΩ</strong><span>Converter Rout · ${fmt(r.req_pu)} p.u.</span></div></div><p class="candidate-resistances">R<sub>load</sub> = ${fmt(t.load_resistance,4)} Ω · R<sub>out</sub>/R<sub>load</sub> = ${fmt(r.rout_over_rload*100,2)}%<br>R<sub>S</sub> = ${fmt(r.rs*1e3,2)} mΩ${r.capacitors?' · R<sub>C</sub> = '+fmt(p.rc_mohm,1)+' mΩ':''}${r.windings?' · R<sub>L</sub> = '+fmt(p.rl_mohm,1)+' mΩ/winding':''}</p><p class="candidate-resources">${r.capacitors} ${isSI()?'output capacitor':'flying/clamp caps'} · ${r.windings} windings<br>${fmt(r.width_mm,1)} mm FET width · ${fmt(r.drop_percent,1)}% nominal droop<br>${isSI()?`<b>${fmt(100*r.efficiency,2)}% modeled efficiency</b> · ${fmt(r.phase_ripple_percent,2)}% phase ripple pp`:switchedCap?`<b>${fmt(100*r.efficiency,2)}% modeled efficiency</b> · ${fmt(r.cf*1e6)} μF each`:r.ripple_model==='ideal_midpoint_hold'?'<b>Ideally zero winding ripple at 2:1</b><br>Capacitor-ripple and mismatch effects are not quantified.':`<b>${fmt(r.phase_ripple_percent,2)}% phase ripple pp</b> · ${fmt(r.phase_ripple_pp*1e3,1)} mA · ${fmt(r.effective_frequency/1e6,1)} MHz effective excitation`}</p><button data-inspect-design="${r.id}">Inspect circuit and die allocation →</button>`:`<p class="candidate-reason">${r.reasons.map(esc).join('; ')}</p>${r.ripple_model==='ideal_midpoint_hold'?'<p class="candidate-reason">Ideal 2:1 midpoint hold gives zero winding ripple; real capacitor-ripple and mismatch effects are not quantified.</p>':''}`}</article>`; | |
| }; | |
| $('#shortlist-results').innerHTML=`${switchedCap?sp2EfficiencySummary(t):''}${t.eligible.length?`<div class="comparison-switch" aria-label="Comparison view"><button data-comparison-view="scoreboard">Loss scoreboard</button><button data-comparison-view="circuits">Circuit cards</button></div><div id="loss-scoreboard-view">${lossScoreboard(t)}</div>`:''}<div id="candidate-cards-view"><p class="candidate-legend">${isSI()?'R<sub>C</sub> is output-capacitor ESR. R<sub>L</sub> is DCR per winding. Device areas follow their RMS currents.':focusedTopology==='rsc2'?'R<sub>C</sub> and R<sub>L</sub> are per-leg losses. A and B identify the two complementary clock commands. Eight devices share the used width equally.':switchedCap?'R<sub>S</sub>: unit-area MOSFET on-resistance · R<sub>C</sub>: flying-capacitor ESR. Eight equal-width devices. Gate-control annotations are omitted from these previews.':`R<sub>S</sub>: unit-area MOSFET on-resistance · R<sub>C</sub>: main-capacitor ESR · R<sub>L</sub>: winding resistance. Device multipliers follow each topology’s die allocation; clamp ESR is zero in the clamp-cell model. Gate-control annotations are omitted from these previews.`}</p><div class="candidate-grid">${t.eligible.map(candidatePanel).join('')||'<p class="no-candidates">No candidate satisfies all currently modeled screens.</p>'}</div></div><details class="excluded-list"><summary>${isSI()?'Switched inductor candidates failing constraints':switchedCap?'Fixed-ratio candidates failing constraints':'Cancellation-point candidates failing constraints'} (${t.rows.length-t.eligible.length})</summary><div class="candidate-grid">${t.rows.filter(r=>r.status==='excluded').map(candidatePanel).join('')}</div>${t.rows.filter(r=>r.status==='unmodeled').map(candidatePanel).join('')}</details>`; | |
| if(t.eligible.length){setComparisonView(comparisonView);$$('[data-comparison-view]').forEach(b=>b.onclick=()=>setComparisonView(b.dataset.comparisonView))}$$('[data-inspect-design]').forEach(b=>b.onclick=()=>inspectRecommendation(b.dataset.inspectDesign));renderTechnology(); | |
| }catch(e){recommendationReport=null;$('#design-error').textContent=e.message;$('#candidate-status').textContent='Check the design inputs to calculate the candidates.';$('#shortlist-results').innerHTML='';$('#export-recommendation').disabled=true;renderTechnology()}} | |
| $('#design-fields').addEventListener('input',()=>{updateLoadSummary();if(document.body.classList.contains('sp2-focused'))return;$('#design-error').textContent='Inputs changed — update the recommendation.';$('#recommend-design').textContent='Update candidates';$('#export-recommendation').disabled=true;$$('[data-inspect-design]').forEach(b=>b.disabled=true)});$('#recommend-design').onclick=()=>document.body.classList.contains('sp2-focused')?update():renderRecommendation();$('#export-recommendation').onclick=()=>{if(recommendationReport)download('openpels-design-shortlist.json',JSON.stringify(recommendationReport,(k,v)=>k==='deviceReport'?undefined:v,2),'application/json')}; | |
| let resizeTimer;window.addEventListener('resize',()=>{clearTimeout(resizeTimer);resizeTimer=setTimeout(()=>{if($('#sweep-section').open)drawSweep()},200)}); | |
| (async()=>{try{await OpenPELSOperatingPoint.load('./operating-conditions.json');catalog=await api('/api/catalog');selected=new Set(OpenPELSRecommendation.familyIds(ratio));picker();await update();announceAnalysisReady()}catch(e){toast(e.message)}})(); | |
| // Appended inside the preserved analytical UI's scope. | |
| function focusRecommendation(result) { | |
| if (!focusedTopology) return result; | |
| const rows = result.rows.filter((row) => row.id === focusedTopology); | |
| const eligible = result.eligible.filter((row) => row.id === focusedTopology); | |
| return { | |
| ...result, | |
| rows, | |
| eligible, | |
| winner: eligible[0] ?? null, | |
| native_models: rows.filter((row) => row.reference_match).length, | |
| }; | |
| } | |
| function isDedicatedReference() { | |
| return ['sp2','rsc2','si2','buck_stacked'].includes(focusedTopology) && ratio === 2; | |
| } | |
| let sp2Analysis, sp2Error, manualSp2Weights = false; | |
| function prepareSp2Analysis(base, useEnteredWeights) { | |
| manualSp2Weights = useEnteredWeights; | |
| try { | |
| const {vgs, events, eoss_pj} = technologyParameters(); | |
| if(isStacked()) $('#tech-vgs').value=(Number($('#design-vout').value)/2).toString(); | |
| const recommend = isSI()?OpenPELSRecommendation.recommendSwitchedInductor:OpenPELSRecommendation.recommendSwitchedCap; | |
| sp2Analysis = recommend( | |
| designParameters(), {vgs:isStacked()?Number($('#design-vout').value)/2:vgs, events, ...(isStacked()?{stack_coss_pf_per_mm:eoss_pj}:{eoss_pj})}, base, | |
| catalog.find((item) => item.id === focusedTopology), OpenPELSTechnology, | |
| ); | |
| sp2Error = ""; | |
| } catch (error) { | |
| sp2Analysis = null; | |
| sp2Error = error.message; | |
| } | |
| const r = sp2Analysis?.deviceReport?.rows[0]; | |
| const context = $("#inspection-context"); | |
| if (useEnteredWeights || !r) { | |
| context.textContent = useEnteredWeights | |
| ? "Manual comparison weights are active. The physical results still use Design Constraints. Update the design to restore linked weights." | |
| : "No physical design result. The per-unit cards use the last valid comparison weights."; | |
| return; | |
| } | |
| const t = sp2Analysis.deviceReport; | |
| $("#rho_c").value = (t.parameters.rc_mohm / 1000 / t.rs).toPrecision(12); | |
| // The winding term is identically zero for SP-SC. Use the legacy | |
| // DCR assumption for any optional inductive comparison curves. | |
| $("#rho_l").value = (Number($("#design-rl_mohm").value) / 1000 / t.rs).toPrecision(12); | |
| $("#rho_q").value = (1 / (r.cf * t.parameters.fs_mhz * 1e6 * t.rs)).toPrecision(12); | |
| if (r.si) { | |
| $("#si_coupling").value = t.parameters.si_coupling; | |
| $("#si_ripple").value = (t.parameters.vin/(t.parameters.si_l_nh*1e-9*t.parameters.fs_mhz*1e6*t.parameters.io)).toPrecision(12); | |
| context.textContent = `Switched inductor design weights · Rs = ${fmt(t.rs*1e3)} mΩ at ${fmt(t.parameters.width_mm)} mm total width.`; | |
| return; | |
| } | |
| if (r.tank) { | |
| $("#rho_t").value = (t.parameters.tank_nh*1e-9*t.parameters.fs_mhz*1e6/t.rs).toPrecision(12); | |
| context.textContent = `Resonant design weights · Rs = ${fmt(t.rs*1e3)} mΩ, tank frequency ${fmt(r.tank.natural_frequency_hz/1e6)} MHz.`; | |
| return; | |
| } | |
| context.textContent = `SP-SC design weights · Rs = ${fmt(t.rs*1e3)} mΩ at ${fmt(t.parameters.width_mm)} mm of used FET width. Optional 2:1 circuit cards use the same normalized weights, with the legacy DCR assumption for windings only. The physical design and The Loss Lineup are for SP-SC.`; | |
| } | |
| function sp2EfficiencySummary(t) { | |
| const r = t.rows[0]; | |
| if (r.efficiency == null) | |
| return '<p id="sp2-efficiency">This operating point has no positive delivered-voltage estimate or capacitance budget. Check the design constraints and load.</p>'; | |
| return `<p id="sp2-efficiency">Modeled efficiency: ${(100*r.efficiency).toFixed(2)}% · delivered output ${r.estimated_open_loop_vout.toFixed(4)} V / ${r.delivered_w.toFixed(4)} W · modeled loss ${(1000*r.loss).toFixed(2)} mW.${r.sizing_constraint?' · '+esc(r.sizing_constraint)+'.':''}</p><p>Used ${fmt(r.width_mm)} mm of ${fmt(t.available_width_mm)} mm available. ${r.si?`Width per upper switch ${fmt(r.device[0].width_mm)} mm, per lower switch ${fmt(r.device[isStacked()?2:1].width_mm)} mm. Winding ripple ${fmt(r.phase_ripple_pp)} A pp. Winding RMS ${fmt(r.operating_waveforms.winding_rms_a)} A per leg and capacitor RMS ${fmt(r.operating_waveforms.output_cap_rms_a)} A. Droop resistance ${fmt(1000*r.droop_resistance)} mΩ. Ideal capacitor ripple ${fmt(r.capacitor_ripple_vpp*1000)} mV pp before ESR. `:`Each of eight devices gets 12.5% of used width (${r.device[0].width_mm.toFixed(3)} mm each).`} ${r.tank?`Tank RMS ${fmt(r.tank.tank_rms_per_output_amp*t.output_current)} A per leg · commutation current magnitude ${fmt(r.tank.commutation_current_per_output_amp*t.output_current)} A. `: ''}${r.coss_power===null?'Coss energy is unknown and is excluded from this estimate.':isStacked()?'It includes the half-input Coss event energy.':'It includes the entered Coss energy.'}</p>`; | |
| } | |
| const sp2Profile = { | |
| "design-si_mode":"duty_cycle","design-si_target_v":1.5, | |
| "design-fs_mhz": 2, "design-budget_mode": "width", "design-width_mm": 80.2666667, | |
| "design-die_mm2": 1, "design-utilization": .5, "design-ron_area_mohm_mm2": 1, | |
| "design-cap_uf": 2, "design-rc_mohm": 20, "design-max_caps": 2, | |
| "design-max_drop_percent": 10, "design-objective": "loss", | |
| "tech-vgs": 3.3, "tech-events": 1, "tech-eoss_pj": "", | |
| rho_c: 1, rho_l: 1, rho_q: 20, si_coupling:.6, si_ripple:.75, | |
| 'design-si_duty':.5,'design-si_l_nh':1000,'design-si_coupling':.6,'design-max_phase_ripple_percent':5, | |
| }; | |
| const profiles = new Map([ | |
| ['si2',{...sp2Profile,'design-width_mm':200,'design-cap_uf':47,'design-max_caps':1, | |
| 'design-max_windings':2,'design-rc_mohm':5,'design-rl_mohm':4,'design-max_phase_ripple_percent':100, | |
| 'design-tank_nh':5.5,rho_t:.61}], | |
| ['sp2', {...sp2Profile, 'design-tank_nh':5.5, 'design-max_windings':2, 'design-rl_mohm':38, rho_t:.61}], | |
| ['rsc2', {...sp2Profile, 'design-width_mm':401.3333333333, 'design-rc_mohm':5, | |
| 'design-tank_nh':5.5, 'design-max_windings':2, 'design-rl_mohm':4, rho_t:.61}], | |
| ]); | |
| profiles.set('buck_stacked',{...profiles.get('si2'),'design-width_mm':400,'tech-eoss_pj':.4}); | |
| let otherProfile = null; | |
| const defaultInputScope = $(".input-scope").textContent; | |
| const defaultIntro = $(".intro p").textContent; | |
| const defaultCossScope = $("#tech-coss-scope").textContent; | |
| const siLabels = {vout:'Input voltage (V)', cap_uf:'Output capacitance (μF)',max_caps:'Maximum output capacitors',rc_mohm:'Output capacitor ESR (mΩ)'}; | |
| const defaultLabels = Object.fromEntries(designFields.map(([key,label])=>[key,label])); | |
| function setInputLabels(si){ | |
| for (const [key,label] of Object.entries(siLabels)) | |
| $("[data-design-field='"+key+"']").firstChild.textContent=si?label:defaultLabels[key]; | |
| } | |
| function switchAnalysisScope(nextId) { | |
| const entering = profiles.has(nextId), previousFixed = isDedicatedReference(); | |
| if ((!entering&&!previousFixed)||nextId===focusedTopology) return; | |
| const fields = Object.keys(profiles.get('sp2')).map((id) => document.getElementById(id)); | |
| const current = Object.fromEntries(fields.map((field) => [field.id, field.value])); | |
| const next = entering ? profiles.get(nextId) : otherProfile; | |
| if (!previousFixed) { | |
| current.inspection = $("#inspection-context").textContent; | |
| otherProfile = current; | |
| } | |
| else profiles.set(focusedTopology,current); | |
| for (const field of fields) field.value = next[field.id]; | |
| setInputLabels(isDutyBuck(nextId)); | |
| const stacked=nextId==='buck_stacked'; | |
| for(const key of ['vgs','events']) $('#tech-'+key).readOnly=stacked; | |
| $('#tech-eoss_pj').parentElement.firstChild.textContent=stacked?'Linear Coss density (pF/mm)':techFields.find(([k])=>k==='eoss_pj')[1]; | |
| $("#tech-coss-scope").textContent=stacked | |
| ? "Linear Coss scales with transistor width. Each MOSFET discharges its nominal half-input voltage once per phase period. A blank entry leaves Coss loss unknown." | |
| : defaultCossScope; | |
| const declared=OpenPELSOperatingPoint.definition(nextId); | |
| if (declared?.simulator?.axes) { | |
| const select=$("#design-si_mode"), mode=select.value; | |
| select.replaceChildren(...declared.modes.map(id=>new Option( | |
| id==="duty_cycle"?"Duty cycle":"Output voltage",id))); | |
| select.value=mode||declared.default_mode; | |
| } | |
| if (!entering) $("#inspection-context").textContent = otherProfile.inspection; | |
| $("#design-objective option[value=magnetics]").hidden = nextId==='sp2'; | |
| $(".selection-method summary").textContent = entering | |
| ? (isDutyBuck(nextId)?"CCM feasibility and recommendation scope":"Fixed-ratio feasibility and recommendation scope") | |
| : "Ripple-cancellation criterion and recommendation scope"; | |
| $(".selection-method").classList.toggle("fixed-ratio-method", entering); | |
| $('.sp2-method').textContent = isDutyBuck(nextId) | |
| ? (stacked?'The design screens positive-current CCM, phase ripple, component counts and droop. Eight switches share the silicon budget. Fixed component counts leave the optimum unchanged under every priority.':'The design screens positive-current CCM, phase ripple, component counts and open-loop droop. The width budget covers all four switches. Fixed component counts leave the loss-minimizing width unchanged under every priority.') : nextId==='rsc2' | |
| ? 'Matched resonant legs use synchronized 50% commands. The design screens component counts, damping and droop, then sizes FET width. The capacitors and windings have fixed counts under all priorities. Tank current reverses during every period.' | |
| : sp2Method; | |
| showBudgetFields(); | |
| $(".intro p").textContent = entering | |
| ? (isDutyBuck(nextId)?"Size the inverse-coupled buck at a target output voltage or a commanded duty cycle.":"Size the fixed 2:1 switched-capacitor design and compare its per-unit loss model with other 2:1 references.") | |
| : defaultIntro; | |
| $(".input-scope").textContent = entering | |
| ? (stacked?"Eight switch areas follow RMS current. Gate swing and nominal blocking are fixed at Vin/2.":isDutyBuck(nextId)?"Four switch areas follow the RMS current weights. Gate and optional Coss data are in the 180 nm device panel.":"Total FET width is sized within the silicon budget for minimum modeled loss subject to droop. Each of eight switches gets equal width. Two matched flying capacitors share the budget. Gate and optional Coss inputs are in the 180 nm device panel.") | |
| : defaultInputScope; | |
| } | |
| function reportOperatingPoint(includeSolution=false) { | |
| if (!focusedTopology) return; | |
| const point={type:"pe:analysis-point",id:focusedTopology,ratio, | |
| operating_point:includeSolution&&sp2Analysis?.rows[0]?.id===focusedTopology?sp2Analysis.operating_point:undefined, | |
| iout:Number($("#design-io").value),vout:Number($("#design-vout").value)}; | |
| if (isSI()) { | |
| const input=designParameters(); | |
| const target=input.voltage_mode==="output_voltage"; | |
| Object.assign(point,{vin:input.vin,voltage_mode:input.voltage_mode, | |
| vout:target?input.si_target_v:input.vin*input.si_duty, | |
| duty:target?undefined:input.si_duty,target_vout:input.si_target_v}); | |
| const command=sp2Analysis?.operating_point; | |
| const row=sp2Analysis?.winner; | |
| if (command) point.operating_point=command; | |
| if (command && row && command.vin===input.vin) { | |
| point.duty=command.duty; | |
| point.analytical_vout=command.analyticalVoltage; | |
| const p=sp2Analysis.parameters; | |
| point.plant={fs:p.fs_mhz,lt:p.si_l_nh,coupling:p.si_coupling,dcr:p.rl_mohm, | |
| cout:p.cap_uf,esr:p.rc_mohm,rs:1000*row.device[0].ron,rslow:1000*row.device[isStacked()?2:1].ron, | |
| ...(isStacked()?{gatecap:sp2Analysis.deviceReport.rows[0].gate_cap_pf,coss:sp2Analysis.deviceReport.rows[0].coss_pf}:{gate:p.vgs})}; | |
| } | |
| } | |
| parent.postMessage(point,location.origin); | |
| } | |
| window.addEventListener("message", (event) => { | |
| if ( | |
| event.origin !== location.origin || | |
| event.source !== parent || | |
| event.data?.type !== "pe:topology" | |
| ) | |
| return; | |
| const next = event.data; | |
| if ( | |
| ![2, 4, 6, 8, 16].includes(next.ratio) || | |
| !OpenPELSRecommendation.referenceFamilyIds(next.ratio).includes(next.id) | |
| ) | |
| return; | |
| if (!catalog.some((entry) => entry.id === next.id)) return; | |
| switchAnalysisScope(next.id); | |
| document.body.classList.toggle("sp2-focused", profiles.has(next.id)); | |
| document.body.classList.toggle("rsc2-focused", next.id==='rsc2'); | |
| document.body.classList.toggle("si2-focused", isDutyBuck(next.id)); | |
| ratio = next.ratio; | |
| focusedTopology = next.id; | |
| selected = new Set([next.id]); | |
| if (Number.isFinite(next.vout) && next.vout > 0) | |
| document.querySelector("#design-vout").value = isSI()?next.vin:next.vout; | |
| if (isSI()) { | |
| $("#design-si_mode").value=next.voltage_mode??"duty_cycle"; | |
| if (Number.isFinite(next.duty)) $("#design-si_duty").value=next.duty; | |
| if (Number.isFinite(next.target_vout)) $("#design-si_target_v").value=next.target_vout; | |
| if (next.plant) { | |
| const fields=OpenPELSOperatingPoint.definition(focusedTopology).simulator.handoff; | |
| for (const [axis,id] of Object.entries(fields)) | |
| if (Number.isFinite(next.plant[axis])) $("#design-"+id).value=next.plant[axis]; | |
| } | |
| } | |
| showVoltageMode(); | |
| if (Number.isFinite(next.iout) && next.iout > 0) | |
| document.querySelector("#design-io").value = next.iout; | |
| document.body.classList.add("focused-topology"); | |
| document.querySelector("#analysis-workbench").open = true; | |
| document | |
| .querySelectorAll("[data-ratio]") | |
| .forEach((button) => | |
| button.classList.toggle("active", Number(button.dataset.ratio) === ratio), | |
| ); | |
| updateLoadSummary(); | |
| picker(); | |
| update(); | |
| if (!isSI()) reportOperatingPoint(); | |
| }); | |
| document | |
| .querySelector("#design-fields") | |
| .addEventListener("input", () => { | |
| if (!isSI()) reportOperatingPoint(); | |
| if (isDedicatedReference()) update(); | |
| }); | |
| $("#tech-settings").addEventListener("input", () => { | |
| if (isDedicatedReference()) update(); | |
| }); | |
| const sp2Method = "The fixed-ratio design checks a two-capacitor minimum, a positive capacitance budget and the allowable open-loop droop. The 2:1 operating point assumes 50% duty and matched capacitors. Fewest capacitors ties for this fixed circuit, so both priorities minimize loss over width. The per-unit comparison supports other qualified 2:1 references."; | |
| function renderSp2Method() { | |
| const panel = $(".selection-method"); | |
| const method = document.createElement("p"); | |
| method.className = "sp2-method"; | |
| method.textContent = sp2Method; | |
| panel.append(method); | |
| } | |
| renderSp2Method(); | |
| function announceAnalysisReady() { | |
| parent.postMessage({ type: "pe:analysis-ready" }, location.origin); | |
| } | |