${logx?fmt(xx,0)+' Hz':'M = '+fmt(xx,3)} ${lines.join(' ')}`;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=>` ${s.name} `).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=`${esc(d.summary)}
Candidate: ${esc(candidate?.name||'not identified')}
${d.uncertainties.map(v=>''+esc(v)+' ').join('')} Review extracted connections and model conditions ${esc(JSON.stringify({components:d.components,gates:d.gates,magnetic_coupling:d.magnetic_coupling,model_conditions:d.model_conditions,derivation:d.derivation},null,2))} ${esc(candidate?.note||'An unfamiliar topology needs its own state and loss derivation.')}
${d.configured&&candidate?' I checked the connections, winding polarity and gate sequence against this reference model.Show topology and equivalent circuit → ':''}`;
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} `).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=`Fixed-width example: flat-current buck models; exact linear periodic RC for SP-SC. Not measured efficiency. Topology CF each (μF) RFET (mΩ) RCAP (mΩ) RIND (mΩ) RHC,add (mΩ) Req (mΩ) Rg at Vx (Ω) Ross at Vx (Ω) Iout²Req + Pg + known Poss (mW) ${t.rows.map(r=>r.valid?`${esc(report.rows.find(a=>a.id===r.id).short)} ${r.cf?unit(r.cf,1e6):'—'} ${['fet','cap','ind','hc','req'].map(k=>`${unit(r[k],1e3)} `).join('')}${unit(r.gate_r)} ${unit(r.oss_r)} ${unit(r.partial_loss,1e3)}${r.poss===null?' + unknown Coss':''} `:`${esc(r.id)} Outside the supported analytical model `).join('')}
`;
}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=`Revent / RSSL · log axis green: finite RC · blue: FSL · orange: SSL ${[.01,.1,1,10,100].map(a=>`${a} `).join('')}${[1,10,100].map(v=>`${v} `).join('')}d / (fs Rpath C) · log axis `})();
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}${type==='select'?`${options.map(([v,t])=>`${t} `).join('')} `:` `} `).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=`Calculated load resistance Rload ${fmt(op.load_resistance,4)} Ω
Calculated output power ${fmt(op.output_power)} W
Derived input voltage: ${ratio} × ${fmt(op.requested_vout)} V = ${fmt(op.parameters.vin)} V . Output voltage and current stay fixed when the ratio changes.
`}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 `THE LOSS LINEUP Higher score = lower modeled loss · actual values in mW
${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.
What is included in each loss? 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.
`;
}
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 `${esc(r.short)} · ${r.reasons.map(esc).join('; ')}
`;
const image=r.asset.replace('.svg','-candidate.svg');
return `${eligible?'#'+r.rank:'Not eligible'} ${r.native_ratio}:1 cancellation point
${esc(r.name)} ${eligible?`${fmt(r.loss*1e3,1)} mW Modeled loss
${fmt(r.rout*1e3,2)} mΩ Converter Rout · ${fmt(r.req_pu)} p.u.
Rload = ${fmt(t.load_resistance,4)} Ω · Rout /Rload = ${fmt(r.rout_over_rload*100,2)}% RS = ${fmt(r.rs*1e3,2)} mΩ${r.capacitors?' · RC = '+fmt(p.rc_mohm,1)+' mΩ':''}${r.windings?' · RL = '+fmt(p.rl_mohm,1)+' mΩ/winding':''}
${r.capacitors} flying/clamp caps · ${r.windings} windings ${fmt(r.width_mm,1)} mm FET width · ${fmt(r.drop_percent,1)}% nominal droop ${r.ripple_model==='ideal_midpoint_hold'?'Ideally zero winding ripple at 2:1 Capacitor-ripple and mismatch effects are not quantified.':`${fmt(r.phase_ripple_percent,2)}% phase ripple pp · ${fmt(r.phase_ripple_pp*1e3,1)} mA · ${fmt(r.effective_frequency/1e6,1)} MHz effective excitation`}
Inspect circuit and die allocation → `:`${r.reasons.map(esc).join('; ')}
${r.ripple_model==='ideal_midpoint_hold'?'Ideal 2:1 midpoint hold gives zero winding ripple; real capacitor-ripple and mismatch effects are not quantified.
':''}`} `;
};
$('#shortlist-results').innerHTML=`${t.eligible.length?`Loss scoreboard Circuit cards
${lossScoreboard(t)}
`:''}RS : unit-area MOSFET on-resistance · RC : main-capacitor ESR · RL : 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.
${t.eligible.map(candidatePanel).join('')||'
No candidate satisfies all currently modeled screens.
'}
Cancellation-point candidates failing constraints (${t.rows.length-t.eligible.length}) ${t.rows.filter(r=>r.status==='excluded').map(candidatePanel).join('')}
${t.rows.filter(r=>r.status==='unmodeled').map(candidatePanel).join('')} `;
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)}})();