ThinkPower / static /app.js
minjiechen's picture
Publish ThinkPower topology analysis website
17f4b23 verified
Raw History Blame Contribute Delete
37.4 kB
'use strict';
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const fmt=(v,n=3)=>Number(v).toLocaleString('en-US',{minimumFractionDigits:n,maximumFractionDigits:n});
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.ThinkPowerEngine.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(){return {ratio,topologies:[...selected],...Object.fromEntries(['rho_c','rho_l','rho_q'].map(k=>[k,Number($('#'+k).value)]))}}
function equivalent(r){
const boost=r.id==='boost',unknown=r.id==='ns',ratioText=unknown?'1 : M':boost?`1 : ${ratio}`:`${ratio} : 1`,M=unknown?null:boost?ratio: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">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}">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">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 split=r.id==='xfly2p',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'};
const blocks=['S','Q'].map((prefix,col)=>{let y=24;return a.areas.map((area,i)=>{const h=216*area/6,label=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</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 ${ratios[r.id]}; 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">${ratios[r.id]}</text></svg><p>Block area ∝ transistor area<br>Total: 12 A₀ · fixed at ${a.reference_ratio}:1${split?'<br>S2 = S2a + S2b in series; Q2 likewise.':''}</p></figure>`;
}
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)} topology with individual device resistance labels">${dieAllocation(r)}</div>${r.allocation?`<p class="device-note">Fixed ${r.allocation.reference_ratio}:1 die allocation; each device value is an on-resistance. ${r.id==='sp2'?'Equal flying capacitors; no power inductors.':'Clamp ESR = 0 in clamp-cell models.'} 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?`${r.id==='sp2'?'Exact periodic RC · ':''}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>${n}/RS <b>${fmt(r[['fet','cap','ind','ssl'][i]])}</b></span>`).join('')}</div>`:''}</div></article>`}).join('');
$$('[data-svg]').forEach(b=>b.onclick=()=>download('thinkpower-'+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>${['RFET','RCAP','RIND','RSSL'][i]} = ${esc(f)}</code>`).join('')}<p>${esc(r.note)}</p></div>`).join('');
}
function picker(){
const ids=ThinkPowerRecommendation.familyIds(ratio),groups=[[`${ratio}:1 coupled-inductor cancellation family`,catalog.filter(c=>ids.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(selected.size===1){toast('Keep at least one topology selected.');return}selected.delete(id)}else selected.add(id);picker();update()});
}
async function update(){const id=++requestId;try{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;cards();renderTechnology();renderRecommendation();$('#status').textContent=`Step-down ${ratio}:1 · M = ${fmt(1/ratio)} · RS base · cancellation-point family only · fixed loss-sizing allocations${selected.has('boost')?' · boost uses ratio 1:'+ratio:''}`;if($('#sweep-section').open)drawSweep()}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}={}){
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(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':'M = '+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,.5],yrange:[Math.max(.001,Math.min(...report.curves.flatMap(s=>s.points.map(p=>p[1])))*.8),50],marker:report.M});$('#legend').innerHTML=report.curves.map(s=>`<span><i style="background:${s.color}"></i>${s.name}</span>`).join('')}
$('#sweep-section').addEventListener('toggle',()=>{if($('#sweep-section').open)drawSweep()});
$$('[data-ratio]').forEach(b=>b.onclick=()=>{ratio=Number(b.dataset.ratio);updateLoadSummary();selected=new Set(ThinkPowerRecommendation.familyIds(ratio));$$('[data-ratio]').forEach(v=>v.classList.toggle('active',v===b));picker();update()});
$('#apply-weights').onclick=update;$('#reset').onclick=()=>{for(const [k,v] of Object.entries({rho_c:1,rho_l:1,rho_q:20}))$('#'+k).value=v;$('#toast').hidden=true;clearTimeout(timer);update()};
$('#export-csv').onclick=()=>{if(!report)return;const rows=[['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'],...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]:''),'Separate technology example; Coss requires energy data',report.normalization.rho_c,report.normalization.rho_l,report.normalization.rho_q,r.domain])];download('thinkpower-per-unit-comparison.csv',rows.map(r=>r.map(v=>'"'+String(v).replaceAll('"','""')+'"').join(',')).join('\n'),'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 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(!ThinkPowerRecommendation.familyIds(ratio).includes(d.candidate_id)){toast('This topology has no qualified coupled-inductor cancellation-point 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('');
let technologyReport;
function renderTechnology(){if(!report)return;try{const p=Object.fromEntries(techFields.filter(([k])=>k!=='eoss_pj'||$('#tech-'+k).value.trim()!=='').map(([k])=>[k,Number($('#tech-'+k).value)]));const point=ThinkPowerRecommendation.operatingPoint(designParameters());p.vin=point.parameters.vin;p.io=point.output_current;technologyReport=ThinkPowerTechnology.example(report.rows,p);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 · physical example is separate from the per-unit weights above`;
$('#technology-results').innerHTML=`<table><caption>Fixed-width example: flat-current buck models; exact linear periodic RC for SP-SC. Not measured efficiency.</caption><thead><tr><th>Topology</th><th>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>${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>`;
}catch(e){technologyReport=null;$('#technology-status').textContent=e.message;$('#technology-results').innerHTML=''}}
$('#apply-technology').onclick=renderTechnology;$('#export-technology').onclick=()=>{if(technologyReport)download('thinkpower-180nm-example.json',JSON.stringify({...technologyReport,source:'User-supplied XFLY_Power_Analysis.md; not independently verified foundry data',method:'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],['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(){return {ratio,voltage_mode:'output_ratio',load_mode:'current',...Object.fromEntries(designFields.map(([k,label,v,type])=>[k,type==='select'?$('#design-'+k).value:Number($('#design-'+k).value)]))}}
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{const op=ThinkPowerRecommendation.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;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 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.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>${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>${fmt(d.powers[m.id]*1e3,2)} <small>mW</small></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('')}<tr class="unquantified-row"><th>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>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;try{recommendationReport=ThinkPowerRecommendation.recommend(designParameters(),{catalog},ThinkPowerEngine,ThinkPowerTechnology);recommendationReport.loss_scoreboard=ThinkPowerScores.build(recommendationReport);$('#design-error').textContent='';$('#recommend-design').textContent='Update candidates';$('#export-recommendation').disabled=false;const t=recommendationReport,p=t.parameters,native=t.native_models;
$('#family-context').textContent=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=!!ThinkPowerRecommendation.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 cancellation point</span></div><h3>${esc(r.name)}</h3><div class="candidate-drawing"><img src="./assets/${image}" alt="${esc(r.name)} schematic with Rs, Rc and Rl resistance labels; gate-control annotations omitted" 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} flying/clamp caps · ${r.windings} windings<br>${fmt(r.width_mm,1)} mm FET width · ${fmt(r.drop_percent,1)}% nominal droop<br>${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=`${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">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>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=''}}
$('#design-fields').addEventListener('input',()=>{updateLoadSummary();$('#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=renderRecommendation;$('#export-recommendation').onclick=()=>{if(recommendationReport)download('thinkpower-design-shortlist.json',JSON.stringify(recommendationReport,null,2),'application/json')};
let resizeTimer;window.addEventListener('resize',()=>{clearTimeout(resizeTimer);resizeTimer=setTimeout(()=>{if($('#sweep-section').open)drawSweep()},200)});
(async()=>{try{catalog=await api('/api/catalog');selected=new Set(ThinkPowerRecommendation.familyIds(ratio));picker();await update()}catch(e){toast(e.message)}})();