minjiechen commited on
Commit
89206e4
·
verified ·
1 Parent(s): 522393f

Publish ThinkPower topology analysis website

Browse files

Independent static website with browser-based analysis and optional direct vision inference. Links to the restored original XFLY simulation Space.

Files changed (5) hide show
  1. README.md +23 -0
  2. static/app.js +10 -10
  3. static/index.html +2 -2
  4. static/recommend.js +10 -7
  5. test_recommendation.py +22 -10
README.md CHANGED
@@ -237,3 +237,26 @@ inspection links. Excluded modeled candidates also have panels. Detailed
237
  control sequences remain available in the inspection schematics. Candidate
238
  assets are generated by `annotate_schematics.py` from the current schematic
239
  sources; these are intentional presentation views, not revision backups.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  control sequences remain available in the inspection schematics. Candidate
238
  assets are generated by `annotate_schematics.py` from the current schematic
239
  sources; these are intentional presentation views, not revision backups.
240
+
241
+ ## Coupled-inductor cancellation-point policy
242
+
243
+ Recommendations and visible inspection choices now list only supported
244
+ cancellation-point families, not every cell that can reach the nominal ratio.
245
+ 2:1 lists coupled BUCK2Phi and stacked BUCK. 4:1 lists XFLY2P, XFLY4P,
246
+ 3LBUCK and 2SBUCK under their specified balanced complementary sequences.
247
+ The stacked buck still uses its existing 4:1 device-size allocation; grouping
248
+ at 2:1 refers to electrical excitation rather than allocation optimality.
249
+ Pure SC and off-duty buck comparisons are omitted. 6:1/8:1/16:1 have no verified
250
+ cancellation-point model yet, so their visible candidate lists are empty.
251
+
252
+ First-order symmetric magnetic model: Lself=Lk+Lm, M=-Lm,
253
+ Ldm=Lk+2Lm. With complementary 50% winding inputs at levels 0/Vstep,
254
+ phase-current ripple pp = Vstep/(4 feff Ldm). Vstep=Vin for buck cells and
255
+ Vin/2 for these hybrid cells; feff=fs for two-command sequences and 2fs for
256
+ the specified four-pulse / 3L sequence. Ripple percentage uses Iout/2 as base.
257
+ Default Lk=50 nH, Lm=1 uH and maximum pp ripple=5% are editable illustrative
258
+ inputs, not characterized TSMC magnetics. The threshold is a hard screen.
259
+ The ideal summed switching ripple cancels; phase ripple is finite for finite Ldm.
260
+ No measured zero-ripple result is claimed. Capacitor ripple, timing/mismatch,
261
+ resistive drops and regulation-duty correction can invalidate this ideal estimate.
262
+ Loss ranking retains flat-current terms and excludes ripple-loss corrections.
static/app.js CHANGED
@@ -38,11 +38,11 @@ function cards(){
38
  $('#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('');
39
  }
40
  function picker(){
41
- const groups=[['2:1 design family',catalog.filter(c=>ThinkPowerRecommendation.specs[c.id]?.ratio===2)],['4:1 design family',catalog.filter(c=>ThinkPowerRecommendation.specs[c.id]?.ratio===4)],['Scalable / topology only',catalog.filter(c=>!ThinkPowerRecommendation.specs[c.id])]];
42
  $('#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('');
43
  $$('[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()});
44
  }
45
- async function update(){const id=++requestId;try{const result=await api('/api/analyze-pu',params());if(id!==requestId)return;report=result;cards();renderTechnology();renderRecommendation();$('#status').textContent=`Step-down ${ratio}:1 · M = ${fmt(1/ratio)} · RS base · fixed reference allocations (2:1 additions; 4:1 paper cells)${selected.has('boost')?' · boost uses ratio 1:'+ratio:''}`;if($('#sweep-section').open)drawSweep()}catch(e){$('#status').textContent='Check inputs';toast(e.message)}}
46
  function chart(id,series,{xlabel='',ylabel='',logx=false,logy=false,xrange,yrange,marker=null,hline=null}={}){
47
  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));
48
  if(!all.length){host.innerHTML='<p class="muted">No supported numerical model selected.</p>';return}
@@ -65,14 +65,14 @@ function chart(id,series,{xlabel='',ylabel='',logx=false,logy=false,xrange,yrang
65
  }
66
  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('')}
67
  $('#sweep-section').addEventListener('toggle',()=>{if($('#sweep-section').open)drawSweep()});
68
- $$('[data-ratio]').forEach(b=>b.onclick=()=>{ratio=Number(b.dataset.ratio);selected=new Set(ratio===2?['buck2','sp2']:['xfly2p','xfly4p','3lbuck','2sbuck','buck']);$$('[data-ratio]').forEach(v=>v.classList.toggle('active',v===b));picker();update()});
69
  $('#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()};
70
  $('#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')};
71
  $('#open-upload').onclick=()=>$('#upload-dialog').showModal();$('#close-upload').onclick=()=>$('#upload-dialog').close();
72
  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}
73
  $('#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])};
74
  $('#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>':''}`;
75
- if($('#confirm-model')){$('#confirm-model').onchange=e=>$('#apply-model').disabled=!e.target.checked;$('#apply-model').onclick=()=>{selected.add(d.candidate_id);picker();update();$('#upload-dialog').close()}}
76
  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)}
77
  $('#upload-status').textContent=d.configured?'Review required before using the reference equations.':'No inference token: image recognition has not been performed.';
78
  }catch(e){$('#upload-status').textContent=e.message}finally{$('#api-key').value='';b.disabled=false}};
@@ -89,7 +89,7 @@ const designFields=[
89
  ['vin','Input voltage (V)',3.3],['io','Load current (A)',2],['fs_mhz','Frequency (MHz)',10],
90
  ['budget_mode','Silicon budget','area','select',[['area','Die area + Ron × area'],['width','Total FET width']]],
91
  ['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],
92
- ['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],['max_drop_percent','Maximum estimated droop (%)',10],
93
  ['objective','Priority','loss','select',[['loss','Lowest modeled loss'],['capacitors','Fewest capacitors, then loss'],['magnetics','Fewest power windings, then loss']]]
94
  ];
95
  $('#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('');
@@ -99,18 +99,18 @@ function showBudgetFields(){const mode=$('#design-budget_mode').value;for(const
99
  showBudgetFields();$('#design-budget_mode').onchange=showBudgetFields;
100
  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'})}
101
  function renderRecommendation(){if(!catalog.length)return;try{recommendationReport=ThinkPowerRecommendation.recommend(designParameters(),{catalog},ThinkPowerEngine,ThinkPowerTechnology);$('#design-error').textContent='';$('#recommend-design').textContent='Find topology →';$('#export-recommendation').disabled=false;const t=recommendationReport,p=t.parameters,w=t.winner,native=t.native_models;
102
- $('#family-context').textContent=native?`${ratio}:1 design family · ${native} library models sized at this ratio. Other supported circuits are included as off-reference alternatives.`:`${ratio}:1 design space · no native higher-order loss model yet. The shortlist evaluates supported existing circuits at this ratio; it does not establish a ${ratio}:1 extension optimum.`;
103
  const priority={loss:'Lowest modeled loss',capacitors:'Fewest capacitors, then loss',magnetics:'Fewest windings, then loss'}[p.objective];
104
- $('#recommendation-output').innerHTML=w?`<div class="recommendation-hero"><div class="section-kicker">RECOMMENDED STARTING POINT · CONDITIONAL</div><h2>${esc(w.name)}</h2><p class="winner-explanation">${esc(priority)} among ${t.eligible.length} candidates passing the entered count and droop limits. ${w.reference_match?'Matches this family’s sizing reference.':esc(w.reference_note)}</p><div class="winner-metrics"><div><strong>${fmt(w.loss*1e3,1)} <small>mW</small></strong><span>Modeled conduction + gate</span></div><div><strong>${fmt(w.req_pu)} <small>p.u.</small></strong><span>Req / RS,budget · common base</span></div><div><strong>${w.used_die_mm2!=null?fmt(w.used_die_mm2):fmt(w.width_mm)} <small>${w.used_die_mm2!=null?'mm²':'mm'}</small></strong><span>${w.used_die_mm2!=null?'FET area used':'Total FET width used'}</span></div><div><strong>${w.capacitors} / ${w.windings}</strong><span>Flying/clamp caps · windings</span></div></div><p class="winner-budget">${fmt(w.width_mm,1)} / ${fmt(t.available_width_mm,1)} mm equivalent FET width · ${fmt(w.drop_percent,1)}% estimated open-loop droop · nominal output ${fmt(t.nominal_vout)} V</p><button class="primary" data-inspect-design="${w.id}">Inspect this topology →</button><p class="recommendation-scope">Ranking excludes unquantified Coss, ripple, core loss, and control/headroom limits. It is a modeled starting point, not a completed design validation.</p></div>`:`<div class="recommendation-hero empty"><div class="section-kicker">NO MODELED CANDIDATE PASSES</div><h2>${t.calibrated?'Revise the constraints or extend the model.':'Enter a positive Ron × area value.'}</h2><p>The candidate panels below give the reason for each exclusion. A missing model is not evidence that a topology cannot work.</p></div>`;
105
  const candidatePanel=r=>{
106
  const supported=!!ThinkPowerRecommendation.specs[r.id],eligible=r.status==='eligible';
107
  if(!supported)return `<p class="unmodeled-candidate"><b>${esc(r.short)}</b> · ${r.reasons.map(esc).join('; ')}</p>`;
108
  const image=r.asset.replace('.svg','-candidate.svg');
109
- 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 ${r.reference_match?'reference family':'off-reference'}</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.req_pu)} p.u.</strong><span>Req / RS,budget</span></div></div><p class="candidate-resistances">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</p><button data-inspect-design="${r.id}">Inspect circuit and die allocation →</button>`:`<p class="candidate-reason">${r.reasons.map(esc).join('; ')}</p>`}</article>`;
110
  };
111
- $('#shortlist-results').innerHTML=`<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><details class="excluded-list"><summary>Excluded or unmodeled candidates (${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>`;
112
  $$('[data-inspect-design]').forEach(b=>b.onclick=()=>inspectRecommendation(b.dataset.inspectDesign));
113
  }catch(e){recommendationReport=null;$('#design-error').textContent=e.message;$('#recommendation-output').innerHTML='<div class="recommendation-hero empty"><h2>Check the design inputs.</h2><p>Use valid nonnegative component budgets and a positive operating point.</p></div>';$('#shortlist-results').innerHTML=''}}
114
  $('#design-fields').addEventListener('input',()=>{$('#design-error').textContent='Inputs changed — update the recommendation.';$('#recommend-design').textContent='Update recommendation →';$('#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')};
115
  let resizeTimer;window.addEventListener('resize',()=>{clearTimeout(resizeTimer);resizeTimer=setTimeout(()=>{if($('#sweep-section').open)drawSweep()},200)});
116
- (async()=>{try{catalog=await api('/api/catalog');picker();await update()}catch(e){toast(e.message)}})();
 
38
  $('#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('');
39
  }
40
  function picker(){
41
+ const ids=ThinkPowerRecommendation.familyIds(ratio),groups=[[`${ratio}:1 coupled-inductor cancellation family`,catalog.filter(c=>ids.includes(c.id))]];
42
  $('#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('');
43
  $$('[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()});
44
  }
45
+ 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)}}
46
  function chart(id,series,{xlabel='',ylabel='',logx=false,logy=false,xrange,yrange,marker=null,hline=null}={}){
47
  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));
48
  if(!all.length){host.innerHTML='<p class="muted">No supported numerical model selected.</p>';return}
 
65
  }
66
  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('')}
67
  $('#sweep-section').addEventListener('toggle',()=>{if($('#sweep-section').open)drawSweep()});
68
+ $$('[data-ratio]').forEach(b=>b.onclick=()=>{ratio=Number(b.dataset.ratio);selected=new Set(ThinkPowerRecommendation.familyIds(ratio));$$('[data-ratio]').forEach(v=>v.classList.toggle('active',v===b));picker();update()});
69
  $('#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()};
70
  $('#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')};
71
  $('#open-upload').onclick=()=>$('#upload-dialog').showModal();$('#close-upload').onclick=()=>$('#upload-dialog').close();
72
  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}
73
  $('#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])};
74
  $('#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>':''}`;
75
+ 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()}}
76
  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)}
77
  $('#upload-status').textContent=d.configured?'Review required before using the reference equations.':'No inference token: image recognition has not been performed.';
78
  }catch(e){$('#upload-status').textContent=e.message}finally{$('#api-key').value='';b.disabled=false}};
 
89
  ['vin','Input voltage (V)',3.3],['io','Load current (A)',2],['fs_mhz','Frequency (MHz)',10],
90
  ['budget_mode','Silicon budget','area','select',[['area','Die area + Ron × area'],['width','Total FET width']]],
91
  ['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],
92
+ ['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],
93
  ['objective','Priority','loss','select',[['loss','Lowest modeled loss'],['capacitors','Fewest capacitors, then loss'],['magnetics','Fewest power windings, then loss']]]
94
  ];
95
  $('#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('');
 
99
  showBudgetFields();$('#design-budget_mode').onchange=showBudgetFields;
100
  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'})}
101
  function renderRecommendation(){if(!catalog.length)return;try{recommendationReport=ThinkPowerRecommendation.recommend(designParameters(),{catalog},ThinkPowerEngine,ThinkPowerTechnology);$('#design-error').textContent='';$('#recommend-design').textContent='Find topology →';$('#export-recommendation').disabled=false;const t=recommendationReport,p=t.parameters,w=t.winner,native=t.native_models;
102
+ $('#family-context').textContent=native?`${ratio}:1 cancellation family · ${native} coupled-inductor candidates. Only complementary 50% effective winding excitation 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.`;
103
  const priority={loss:'Lowest modeled loss',capacitors:'Fewest capacitors, then loss',magnetics:'Fewest windings, then loss'}[p.objective];
104
+ $('#recommendation-output').innerHTML=w?`<div class="recommendation-hero"><div class="section-kicker">RECOMMENDED STARTING POINT · CONDITIONAL</div><h2>${esc(w.name)}</h2><p class="winner-explanation">${esc(priority)} among ${t.eligible.length} candidates passing the entered count and droop limits. ${w.reference_match?'Operates at this family’s nominal ripple-cancellation point.':esc(w.reference_note)}</p><div class="winner-metrics"><div><strong>${fmt(w.loss*1e3,1)} <small>mW</small></strong><span>Modeled conduction + gate</span></div><div><strong>${fmt(w.req_pu)} <small>p.u.</small></strong><span>Req / RS,budget · common base</span></div><div><strong>${w.used_die_mm2!=null?fmt(w.used_die_mm2):fmt(w.width_mm)} <small>${w.used_die_mm2!=null?'mm²':'mm'}</small></strong><span>${w.used_die_mm2!=null?'FET area used':'Total FET width used'}</span></div><div><strong>${w.capacitors} / ${w.windings}</strong><span>Flying/clamp caps · windings</span></div></div><p class="winner-budget">${fmt(w.width_mm,1)} / ${fmt(t.available_width_mm,1)} mm equivalent FET width · ${fmt(w.phase_ripple_percent,2)}% estimated phase-current ripple pp · ${fmt(w.drop_percent,1)}% estimated open-loop droop · nominal output ${fmt(t.nominal_vout)} V</p><button class="primary" data-inspect-design="${w.id}">Inspect this topology →</button><p class="recommendation-scope">Ripple estimate assumes balanced capacitors, inverse coupling and matched timing. Ranking excludes ripple-loss corrections, Coss, core loss and control/headroom limits. It is a modeled starting point, not a completed design validation.</p></div>`:`<div class="recommendation-hero empty"><div class="section-kicker">NO MODELED CANDIDATE PASSES</div><h2>${!native?'No qualified cancellation-point model yet.':t.calibrated?'Revise the magnetic or resource constraints.':'Enter a positive Ron × area value.'}</h2><p>Only coupled-inductor cancellation-point candidates are considered. The panels below explain resource or ripple exclusions; off-duty circuits and pure SC options are not listed.</p></div>`;
105
  const candidatePanel=r=>{
106
  const supported=!!ThinkPowerRecommendation.specs[r.id],eligible=r.status==='eligible';
107
  if(!supported)return `<p class="unmodeled-candidate"><b>${esc(r.short)}</b> · ${r.reasons.map(esc).join('; ')}</p>`;
108
  const image=r.asset.replace('.svg','-candidate.svg');
109
+ 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.req_pu)} p.u.</strong><span>Req / RS,budget</span></div></div><p class="candidate-resistances">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><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>`}</article>`;
110
  };
111
+ $('#shortlist-results').innerHTML=`<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><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>`;
112
  $$('[data-inspect-design]').forEach(b=>b.onclick=()=>inspectRecommendation(b.dataset.inspectDesign));
113
  }catch(e){recommendationReport=null;$('#design-error').textContent=e.message;$('#recommendation-output').innerHTML='<div class="recommendation-hero empty"><h2>Check the design inputs.</h2><p>Use valid nonnegative component budgets and a positive operating point.</p></div>';$('#shortlist-results').innerHTML=''}}
114
  $('#design-fields').addEventListener('input',()=>{$('#design-error').textContent='Inputs changed — update the recommendation.';$('#recommend-design').textContent='Update recommendation →';$('#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')};
115
  let resizeTimer;window.addEventListener('resize',()=>{clearTimeout(resizeTimer);resizeTimer=setTimeout(()=>{if($('#sweep-section').open)drawSweep()},200)});
116
+ (async()=>{try{catalog=await api('/api/catalog');selected=new Set(ThinkPowerRecommendation.familyIds(ratio));picker();await update()}catch(e){toast(e.message)}})();
static/index.html CHANGED
@@ -1,8 +1,8 @@
1
  <!doctype html>
2
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="Power converter topologies and their ideal conversion ratio plus effective output resistance."><title>ThinkPower — Choose Your Converter</title><link rel="stylesheet" href="./style.css"></head><body>
3
  <header><a class="brand" href="./index.html"><span>╳</span>ThinkPower</a><div>Constraints → topology recommendation</div><a href="https://huggingface.co/spaces/minjiechen/XFLY" target="_blank" rel="noopener">NGSpice ↗</a></header>
4
- <main><div class="intro"><div><h1>Find the right converter for your design.</h1><p>Choose a conversion ratio, set your silicon and passive budgets, and compare the best modeled fits.</p></div><button id="open-upload">+ Upload topology</button></div>
5
- <section class="family-navigation" aria-label="Conversion ratio families"><div class="ratio-control"><label>1 · Target conversion ratio</label><div id="ratios"><button data-ratio="2"><strong>2:1</strong><small>Buck & series-parallel SC</small></button><button data-ratio="4" class="active"><strong>4:1</strong><small>XFLY & multilevel cells</small></button><button data-ratio="6"><strong>6:1</strong><small>Scaled design space</small></button><button data-ratio="8"><strong>8:1</strong><small>Scaled design space</small></button><button data-ratio="16"><strong>16:1</strong><small>Scaled design space</small></button></div></div></section><p id="family-context" class="family-context"></p><section class="design-workspace"><div class="design-inputs"><div class="section-kicker">2 · DESIGN CONSTRAINTS</div><h2>Your available resources</h2><div class="design-fields" id="design-fields"></div><p class="input-scope">Ron × area defaults to an illustrative 1 mΩ·mm², not a characterized TSMC layout value. Capacitor budget covers flying/clamp caps; winding limits count power windings. Driver area and Cin/Cout are outside these budgets.</p><button id="recommend-design" class="primary">Find topology →</button><p id="design-error" role="status"></p></div><div id="recommendation-output" aria-live="polite"></div></section><section id="shortlist-section" class="shortlist-section"><div class="shortlist-heading"><div><div class="section-kicker">3 · COMPARE THE SHORTLIST</div><h2>Topology candidates</h2></div><button id="export-recommendation">↓ Design JSON</button></div><div id="shortlist-results"></div><details class="selection-method"><summary>How the recommendation is made</summary><p>We screen the supported duty range, power-winding count, flying/clamp capacitor count, capacitor budget, and estimated open-loop droop. Within each feasible topology we search total transistor width under the silicon budget, minimizing modeled conduction plus gate-drive loss while holding the library’s relative die allocation fixed. Silicon is a maximum budget; spending all of it need not minimize gate-drive plus conduction loss.</p><p>Die-area mode uses RΣ = (Ron × area)/(die area × usable transistor fraction). The supplied 180 nm Ron·Qg FOM gives gate power; the Ron × area default is a separate, editable layout assumption. Capacitors share their total budget equally within each cell’s stated model.</p><p>Results are a conditional analytical shortlist at nominal M = 1/ratio. Winding count and DCR are screened; inductance, ripple, saturation, magnetic volume/core loss, control/headroom, device voltage rating, and layout/interconnects still require verification. Shortlist per-unit resistances share RS,budget = 12 (Ron × area)/(usable transistor area); physical loss determines the ranking. Coss is not quantified from Qoss alone. Gate-drive ranking assumes one full gate-charge event per device per period; actual four-pulse event counts and clamp recharge require further derivation.</p><p>Ratio groups reflect the library’s sizing-reference/design families, not a universal optimum. Native models for 6:1, 8:1 and 16:1 are not yet derived: those tabs show supported off-reference evaluations and identify this gap instead of assigning invented higher-order coefficients.</p></details></section><details id="analysis-workbench" class="analysis-workbench"><summary>Inspect schematics, die allocation, and loss derivations</summary><p id="inspection-context">Reference drawings use normalized resistances. Inspect a shortlisted design to load its loss weights.</p><div class="advanced-toolbar"><details class="weights"><summary>Per-unit loss weights</summary><div><label>R<sub>C</sub> / R<sub>S</sub><input id="rho_c" type="number" value="1" min="0" step="0.1"></label><label>R<sub>L</sub> / R<sub>S</sub><input id="rho_l" type="number" value="1" min="0" step="0.1"></label><label>1 / (C<sub>F</sub> f<sub>s</sub> R<sub>S</sub>)<input id="rho_q" type="number" value="20" min="0" step="1"></label><button id="apply-weights">Apply</button><button id="reset">Reset</button></div></details><button id="export-csv" class="plain">↓ CSV</button></div>
6
  <details class="secondary-panel" id="technology-panel"><summary>Separate 180 nm device reference example · physical losses and RC limits</summary><p>User-supplied device example from XFLY_Power_Analysis.md; not independently verified foundry data. FOM<sub>g</sub> = 1.51102 Ω·pC; FOM<sub>oss</sub> = 0.67424 Ω·pC. First-order width scaling; same device technology for all FETs. Device voltage rating and PVT limits require a PDK check.</p><div class="tech-settings" id="tech-settings"></div><p>Optional Eoss entry: dissipated Coss energy in pJ per 1 mm of total FET width per cycle, averaged over the actual device transitions after recovery. Leave blank when unknown. Qoss is not converted to Eoss.</p><button id="apply-technology">Update example</button> <button id="export-technology">↓ Technology JSON</button><p id="technology-status" role="status"></p><div class="technology-table" id="technology-results"></div><details><summary>Derivation and model scope</summary><p>RΣ is the resistance of all available FET width in parallel. With the existing twelve-unit area budget, RΣ = RS/12. A device assigned fraction α has width αWtot and on-resistance RΣ/α. FOMg = Ron·Qg and FOMoss = Ron·Qoss are width independent under the supplied scaling.</p><div class="equation">Pg = VGS fs ng FOMg / RΣ; Rg = Vx² RΣ / (VGS fs ng FOMg)</div><p>Vx = M Vin is the ideal secondary voltage, ahead of the series loss resistances. Both loss shunts use Vx, rather than the loaded Vout. Gate power is a separate supply demand unless the driver is explicitly powered from the main input. The shunts are accounting equivalents; their current does not enter the conduction-loss calculations.</p><div class="equation">Poss = fs Σ νi Eoss,diss,i; Ross = Vx² / Poss</div><p>ng is the width-weighted number of gate-charge events per period, assumed uniform in this example. Actual four-pulse sequences require event counts for each physical device. No exact Eoss follows from FOMoss alone: Q(V), Eoss(V), switching swings, and recovery are needed. The optional aggregate Eoss input must already include these effects.</p><p>The numerical table uses matched flat winding currents for inductive converters. The added SP-SC uses an exact linear periodic RC model, with no power winding. Width allocations remain fixed at each topology’s reference ratio (2:1 for the added cells; 4:1 for the paper cells). These allocations are not automatically reoptimized at another sizing duty. The 4 μF budget covers flying and clamp capacitors only; Cin and Cout are excluded. Adopted allocation: equal main capacitors for two-capacitor cells; equal main and clamp capacitances in four-capacitor cells, consistent with the existing 2SBUCK model. This is a disclosed comparison assumption, not a capacitor-allocation optimum. Additional XFLY4P clamp recharge is not derived. Turn-on/off overlap, dead time, core loss, interconnects and ripple corrections remain outside these estimates.</p><p>RFET, RCAP and RIND use the existing closed-form duty expressions below. The charging increment uses the paper's asymptotic interpolation for the paper cells. The added SP-SC has its own exact linear periodic RC model. Unknown Coss loss is excluded from the displayed partial loss, so no total efficiency is claimed.</p></details><details><summary>Finite-RC charge-event check</summary><p>For a single linear RC charging event lasting d/fs, let q = a Iout/fs be the required transferred charge. Integrating i²R for an exponential current and eliminating its initial amplitude gives:</p><div class="equation">Revent = a²/[2 C fs] coth[d/(2 fs Rpath C)]</div><div class="equation">RSSL = a²/(2 C fs); RFSL = a² Rpath/d</div><p>Here C is the effective capacitance seen by that event. The exact result approaches both limits; they must not be added to another RMS model of the same event. It assumes a fixed linear path, settled initial conditions specified by the event, and a driving step chosen to transfer q. Each converter needs its own event capacitance, duration, charge multiplier, and periodic initial conditions before this expression can replace the existing interpolation.</p><div id="rc-limit-chart"></div></details></details>
7
  <div id="topology-picker" class="picker" aria-label="Topologies to compare"></div><div id="status" role="status" class="status">Loading topology models…</div>
8
  <div class="column-labels"><span>CONVERTER TOPOLOGY</span><span>AVERAGED DC EQUIVALENT CIRCUIT</span></div><section id="circuits" aria-label="Topology and equivalent circuit comparison"></section>
 
1
  <!doctype html>
2
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="description" content="Power converter topologies and their ideal conversion ratio plus effective output resistance."><title>ThinkPower — Choose Your Converter</title><link rel="stylesheet" href="./style.css"></head><body>
3
  <header><a class="brand" href="./index.html"><span>╳</span>ThinkPower</a><div>Constraints → topology recommendation</div><a href="https://huggingface.co/spaces/minjiechen/XFLY" target="_blank" rel="noopener">NGSpice ↗</a></header>
4
+ <main><div class="intro"><div><h1>Find the right converter for your design.</h1><p>Choose a conversion ratio and compare coupled-inductor cells at their nominal ripple-cancellation points.</p></div><button id="open-upload">+ Upload topology</button></div>
5
+ <section class="family-navigation" aria-label="Conversion ratio families"><div class="ratio-control"><label>1 · Target conversion ratio</label><div id="ratios"><button data-ratio="2"><strong>2:1</strong><small>Coupled buck cells</small></button><button data-ratio="4" class="active"><strong>4:1</strong><small>Coupled hybrid cells</small></button><button data-ratio="6"><strong>6:1</strong><small>Model pending</small></button><button data-ratio="8"><strong>8:1</strong><small>Model pending</small></button><button data-ratio="16"><strong>16:1</strong><small>Model pending</small></button></div></div></section><p id="family-context" class="family-context"></p><section class="design-workspace"><div class="design-inputs"><div class="section-kicker">2 · DESIGN CONSTRAINTS</div><h2>Your available resources</h2><div class="design-fields" id="design-fields"></div><p class="input-scope">Ron × area defaults to an illustrative 1 mΩ·mm², not a characterized TSMC layout value. Capacitor budget covers flying/clamp caps; winding limits count power windings. Driver area and Cin/Cout are outside these budgets. Lk = 50 nH and Lm = 1 μH are editable illustrative defaults, not characterized TSMC magnetics.</p><button id="recommend-design" class="primary">Find topology →</button><p id="design-error" role="status"></p></div><div id="recommendation-output" aria-live="polite"></div></section><section id="shortlist-section" class="shortlist-section"><div class="shortlist-heading"><div><div class="section-kicker">3 · COMPARE THE SHORTLIST</div><h2>Topology candidates</h2></div><button id="export-recommendation">↓ Design JSON</button></div><div id="shortlist-results"></div><details class="selection-method"><summary>Ripple-cancellation criterion and recommendation scope</summary><p>Only coupled-inductor cells with a verified nominal two-level excitation pattern at this ratio are listed. The admitted pattern has matched winding inputs at 50% effective duty and complementary phase timing. A two-phase buck reaches this at ideal 2:1; balanced half-input hybrid cells reach it at ideal 4:1. A four-pulse or three-level sequence must preserve the complementary winding-input pattern; arbitrary pulse permutations are not admitted by this estimate.</p><div class="equation">Lself = Lk + Lm; M = −Lm; LDM = Lk + 2Lm</div><div class="equation">Δiphase,pp ≈ Vstep / (4 feff LDM)</div><p>Vstep is Vin for buck cells and Vin/2 for the admitted hybrid cells. feff is fs for the two-command cells, and 2fs for the specified four-pulse / three-level excitation. Phase ripple percentage is Δiphase,pp divided by Iout/2. The symmetric common-mode switching excitation cancels ideally; individual phase ripple is finite and approaches zero only with sufficiently large differential-mode inductance. This is not a measured zero-ripple claim.</p><p>We screen the entered phase-ripple threshold, winding/capacitor counts, capacitance budget and estimated open-loop droop. Total FET width is searched under the silicon budget with each model’s relative allocation held fixed. Die-area mode uses RΣ = (Ron × area)/(usable transistor area); the 1 mΩ·mm² default is an illustrative editable layout assumption. Shortlist resistances share the full-budget RS base. Loss ranking remains the flat-current model plus gate drive; ripple-loss corrections and Coss energy are not inferred.</p><p>Ripple estimates assume equal winding turns, inverse polarity, balanced capacitor voltages, stiff ideal switching levels and matched timing. Capacitor ripple, imbalance, dead time, resistive voltage errors and control action can spoil cancellation. Correcting loaded output voltage by duty adjustment can move away from the nominal cancellation point. Saturation, core loss and magnetic implementation need separate verification.</p><p>The current library establishes only the 2:1 and 4:1 cancellation-point families. The 6:1, 8:1 and 16:1 tabs remain empty until a higher-order switching and magnetic model is available. Off-duty buck comparisons and the nonmagnetic SC option are omitted. The stacked buck is grouped at its electrical 2:1 cancellation point while retaining its existing 4:1 loss-sizing allocation.</p><p>For coupled-inductor modal behavior, see <a href="https://www.analog.com/en/resources/analog-dialogue/articles/output-current-and-volt-ripple-in-multiphase-buck.html" target="_blank" rel="noopener">ADI’s phase- and output-ripple analysis</a>. The formulas above follow directly from the stated symmetric inductance matrix.</p></details></section><details id="analysis-workbench" class="analysis-workbench"><summary>Inspect schematics, die allocation, and loss derivations</summary><p id="inspection-context">Reference drawings use normalized resistances. Inspect a shortlisted design to load its loss weights.</p><div class="advanced-toolbar"><details class="weights"><summary>Per-unit loss weights</summary><div><label>R<sub>C</sub> / R<sub>S</sub><input id="rho_c" type="number" value="1" min="0" step="0.1"></label><label>R<sub>L</sub> / R<sub>S</sub><input id="rho_l" type="number" value="1" min="0" step="0.1"></label><label>1 / (C<sub>F</sub> f<sub>s</sub> R<sub>S</sub>)<input id="rho_q" type="number" value="20" min="0" step="1"></label><button id="apply-weights">Apply</button><button id="reset">Reset</button></div></details><button id="export-csv" class="plain">↓ CSV</button></div>
6
  <details class="secondary-panel" id="technology-panel"><summary>Separate 180 nm device reference example · physical losses and RC limits</summary><p>User-supplied device example from XFLY_Power_Analysis.md; not independently verified foundry data. FOM<sub>g</sub> = 1.51102 Ω·pC; FOM<sub>oss</sub> = 0.67424 Ω·pC. First-order width scaling; same device technology for all FETs. Device voltage rating and PVT limits require a PDK check.</p><div class="tech-settings" id="tech-settings"></div><p>Optional Eoss entry: dissipated Coss energy in pJ per 1 mm of total FET width per cycle, averaged over the actual device transitions after recovery. Leave blank when unknown. Qoss is not converted to Eoss.</p><button id="apply-technology">Update example</button> <button id="export-technology">↓ Technology JSON</button><p id="technology-status" role="status"></p><div class="technology-table" id="technology-results"></div><details><summary>Derivation and model scope</summary><p>RΣ is the resistance of all available FET width in parallel. With the existing twelve-unit area budget, RΣ = RS/12. A device assigned fraction α has width αWtot and on-resistance RΣ/α. FOMg = Ron·Qg and FOMoss = Ron·Qoss are width independent under the supplied scaling.</p><div class="equation">Pg = VGS fs ng FOMg / RΣ; Rg = Vx² RΣ / (VGS fs ng FOMg)</div><p>Vx = M Vin is the ideal secondary voltage, ahead of the series loss resistances. Both loss shunts use Vx, rather than the loaded Vout. Gate power is a separate supply demand unless the driver is explicitly powered from the main input. The shunts are accounting equivalents; their current does not enter the conduction-loss calculations.</p><div class="equation">Poss = fs Σ νi Eoss,diss,i; Ross = Vx² / Poss</div><p>ng is the width-weighted number of gate-charge events per period, assumed uniform in this example. Actual four-pulse sequences require event counts for each physical device. No exact Eoss follows from FOMoss alone: Q(V), Eoss(V), switching swings, and recovery are needed. The optional aggregate Eoss input must already include these effects.</p><p>The numerical table uses matched flat winding currents for inductive converters. The added SP-SC uses an exact linear periodic RC model, with no power winding. Width allocations remain fixed at each topology’s reference ratio (2:1 for the added cells; 4:1 for the paper cells). These allocations are not automatically reoptimized at another sizing duty. The 4 μF budget covers flying and clamp capacitors only; Cin and Cout are excluded. Adopted allocation: equal main capacitors for two-capacitor cells; equal main and clamp capacitances in four-capacitor cells, consistent with the existing 2SBUCK model. This is a disclosed comparison assumption, not a capacitor-allocation optimum. Additional XFLY4P clamp recharge is not derived. Turn-on/off overlap, dead time, core loss, interconnects and ripple corrections remain outside these estimates.</p><p>RFET, RCAP and RIND use the existing closed-form duty expressions below. The charging increment uses the paper's asymptotic interpolation for the paper cells. The added SP-SC has its own exact linear periodic RC model. Unknown Coss loss is excluded from the displayed partial loss, so no total efficiency is claimed.</p></details><details><summary>Finite-RC charge-event check</summary><p>For a single linear RC charging event lasting d/fs, let q = a Iout/fs be the required transferred charge. Integrating i²R for an exponential current and eliminating its initial amplitude gives:</p><div class="equation">Revent = a²/[2 C fs] coth[d/(2 fs Rpath C)]</div><div class="equation">RSSL = a²/(2 C fs); RFSL = a² Rpath/d</div><p>Here C is the effective capacitance seen by that event. The exact result approaches both limits; they must not be added to another RMS model of the same event. It assumes a fixed linear path, settled initial conditions specified by the event, and a driving step chosen to transfer q. Each converter needs its own event capacitance, duration, charge multiplier, and periodic initial conditions before this expression can replace the existing interpolation.</p><div id="rc-limit-chart"></div></details></details>
7
  <div id="topology-picker" class="picker" aria-label="Topologies to compare"></div><div id="status" role="status" class="status">Loading topology models…</div>
8
  <div class="column-labels"><span>CONVERTER TOPOLOGY</span><span>AVERAGED DC EQUIVALENT CIRCUIT</span></div><section id="circuits" aria-label="Topology and equivalent circuit comparison"></section>
static/recommend.js CHANGED
@@ -1,11 +1,14 @@
1
  /* Constraint screening and width optimization within the verified analytical library. */
2
  (function(root){'use strict';
3
- const specs=Object.freeze({buck2:{ratio:2,caps:0,windings:2,magnetics:'inverse-coupled'},sp2:{ratio:2,caps:2,windings:0,magnetics:'none'},xfly2p:{ratio:4,caps:2,windings:2,magnetics:'coupled'},xfly4p:{ratio:4,caps:4,windings:2,magnetics:'coupled'},'3lbuck':{ratio:4,caps:2,windings:2,magnetics:'coupled'},'2sbuck':{ratio:4,caps:4,windings:2,magnetics:'coupled'},buck:{ratio:4,caps:0,windings:2,magnetics:'coupled'}});
4
- const defaults={ratio:4,vin:3.3,io:2,fs_mhz:10,vgs:3.3,budget_mode:'area',width_mm:360,die_mm2:1,utilization:.5,ron_area_mohm_mm2:1,cap_uf:4,max_caps:4,max_windings:2,rc_mohm:20,rl_mohm:38,max_drop_percent:10,objective:'loss'};
5
- function recommend(input,data,engine,technology){const p={...defaults,...input};for(const k of ['ratio','vin','io','fs_mhz','vgs','width_mm','die_mm2'])if(!Number.isFinite(p[k])||p[k]<=0)throw Error(k+' must be positive');for(const k of ['cap_uf','max_caps','max_windings','rc_mohm','rl_mohm','max_drop_percent'])if(!Number.isFinite(p[k])||p[k]<0)throw Error(k+' must be nonnegative');if(![2,4,6,8,16].includes(p.ratio))throw Error('Choose a supported ratio');if(!['width','area'].includes(p.budget_mode)||!['loss','capacitors','magnetics'].includes(p.objective))throw Error('Choose a budget mode and objective');if(!Number.isInteger(p.max_caps)||!Number.isInteger(p.max_windings))throw Error('Component limits must be integers');if(!Number.isFinite(p.utilization)||p.utilization<=0||p.utilization>1)throw Error('Usable die fraction must be in (0,1]');
 
 
 
6
  const calibrated=p.budget_mode==='width'||Number.isFinite(p.ron_area_mohm_mm2)&&p.ron_area_mohm_mm2>0,Wmax=p.budget_mode==='width'?p.width_mm:calibrated?technology.reference.ron*p.die_mm2*p.utilization/(p.ron_area_mohm_mm2*1e-3):null,fs=p.fs_mhz*1e6,m=1/p.ratio,vo=p.vin*m;
7
  if(calibrated&&(!Number.isFinite(Wmax)||Wmax<=0))throw Error('Invalid area/width budget');
8
- const rows=data.catalog.map(c=>{const s=specs[c.id],r={id:c.id,name:c.name,short:c.short,native_ratio:s?.ratio??null,reference_match:s?.ratio===p.ratio,asset:c.asset,status:'excluded',reasons:[]};if(!s){r.status='unmodeled';r.reasons=['No verified loss model for recommendation'];return r}Object.assign(r,{capacitors:s.caps,windings:s.windings,magnetics:s.magnetics});if(!engine.valid(c.id,m))r.reasons.push(c.id==='sp2'?'Fixed 2:1 conversion only':'Outside the verified duty range');if(s.windings>p.max_windings)r.reasons.push('Requires '+s.windings+' power windings; limit is '+p.max_windings);if(s.caps>p.max_caps)r.reasons.push('Requires '+s.caps+' flying/clamp capacitors; limit is '+p.max_caps);if(s.caps&&p.cap_uf<=0)r.reasons.push('A positive flying/clamp capacitor budget is required');if(!calibrated)r.reasons.push('Enter positive Ron × area (mΩ·mm²)');if(r.reasons.length)return r;
9
  const cf=s.caps?p.cap_uf*1e-6/s.caps:null;
10
  function at(width){const rs=technology.reference.ron*12/width,v=engine.evaluate(c.id,m,{rs,rc:p.rc_mohm/1000,rl:p.rl_mohm/1000,cf:cf??1,fs}),gate=p.vgs*fs*technology.fom.gate*width/technology.reference.ron,loss=p.io*p.io*v.total+gate;return {width_mm:width,rs,req:v.total,req_pu:v.total/(technology.reference.ron*12/Wmax),req_used_width_pu:v.total/rs,conduction_power:p.io*p.io*v.total,gate_power:gate,loss,drop_percent:100*p.io*v.total/vo,estimated_open_loop_vout:vo-p.io*v.total,cf,parts:v}}
11
  // Search total width, not individual device ratios; include both boundaries.
@@ -13,7 +16,7 @@ let best=null,bestIndex=0;const grid=Array.from({length:65},(_,i)=>Wmax*10**(-4+
13
  let lo=Math.log(grid[Math.max(0,bestIndex-1)]),hi=Math.log(grid[Math.min(64,bestIndex+1)]);for(let i=0;i<50;i++){const a=lo+(hi-lo)/3,b=hi-(hi-lo)/3,va=at(Math.exp(a)),vb=at(Math.exp(b));if(va.loss<best.loss)best=va;if(vb.loss<best.loss)best=vb;if(va.loss<vb.loss)hi=b;else lo=a}
14
  // Droop is a hard screen. A loss-minimizing width can fail it although Wmax passes.
15
  if(best.drop_percent>p.max_drop_percent){const full=at(Wmax);if(full.drop_percent<=p.max_drop_percent){let a=best.width_mm,b=Wmax;for(let i=0;i<60;i++){const mid=(a+b)/2;if(at(mid).drop_percent>p.max_drop_percent)a=mid;else b=mid}best=at(b)}else r.reasons.push('Estimated open-loop droop exceeds '+p.max_drop_percent+'% even at full FET budget')}
16
- Object.assign(r,best,{used_die_mm2:p.budget_mode==='area'?best.width_mm*p.ron_area_mohm_mm2*1e-3/technology.reference.ron:null,available_width_mm:Wmax,reference_note:s.ratio===p.ratio?'Sizing-reference match':'Existing '+s.ratio+':1 allocation evaluated at '+p.ratio+':1; not a new native-ratio design'});r.status=r.reasons.length?'excluded':'eligible';return r});
17
- const eligible=rows.filter(r=>r.status==='eligible');eligible.sort((a,b)=>{if(p.objective==='capacitors'&&a.capacitors!==b.capacitors)return a.capacitors-b.capacitors;if(p.objective==='magnetics'&&a.windings!==b.windings)return a.windings-b.windings;return a.loss-b.loss});eligible.forEach((r,i)=>r.rank=i+1);return {parameters:p,available_width_mm:Wmax,rs_budget:calibrated?technology.reference.ron*12/Wmax:null,calibrated,nominal_vout:vo,eligible,rows,winner:eligible[0]??null,native_models:rows.filter(r=>r.reference_match).length,scope:'Conditional shortlist: modeled conduction + gate-drive loss at nominal M=1/ratio. Coss, ripple/core loss, saturation, layout, startup and control/headroom are not qualified. Fixed per-device allocations; total width optimized. One gate-charge event per device per period assumed. Budgets cover power FETs, flying/clamp capacitors and power windings; drivers/Cin/Cout are outside these budgets.'};}
18
- const api={recommend,specs,defaults};root.ThinkPowerRecommendation=api;if(typeof module!=='undefined')module.exports=api;
19
  })(typeof window!=='undefined'?window:globalThis);
 
1
  /* Constraint screening and width optimization within the verified analytical library. */
2
  (function(root){'use strict';
3
+ const specs=Object.freeze({buck2:{ratio:2,caps:0,windings:2,magnetics:'inverse-coupled'},sp2:{ratio:2,caps:2,windings:0,magnetics:'none'},xfly2p:{ratio:4,caps:2,windings:2,magnetics:'coupled'},xfly4p:{ratio:4,caps:4,windings:2,magnetics:'coupled'},'3lbuck':{ratio:4,caps:2,windings:2,magnetics:'coupled'},'2sbuck':{ratio:4,caps:4,windings:2,magnetics:'coupled'},buck:{ratio:2,caps:0,windings:2,magnetics:'coupled'}});
4
+ const excitation=Object.freeze({buck2:{level:1,pulses:1},buck:{level:1,pulses:1},xfly2p:{level:.5,pulses:1},xfly4p:{level:.5,pulses:2},'3lbuck':{level:.5,pulses:2},'2sbuck':{level:.5,pulses:1}});
5
+ function familyIds(ratio){return Object.keys(excitation).filter(id=>specs[id].ratio===ratio)}
6
+ function ripplePoint(id,p){const e=excitation[id],ldm=p.lk_nh*1e-9+2*p.lm_uh*1e-6,pp=p.vin*e.level/(4*p.fs_mhz*1e6*e.pulses*ldm);return {phase_ripple_pp:pp,phase_ripple_percent:100*pp/(p.io/2),effective_duty:.5,effective_frequency:p.fs_mhz*1e6*e.pulses,ldm,condition:'Balanced 0/Vstep winding inputs, complementary 50% effective duty, matched inverse coupling; first-order phase-current ripple, not measured zero ripple.'}}
7
+ const defaults={ratio:4,vin:3.3,io:2,fs_mhz:10,vgs:3.3,budget_mode:'area',width_mm:360,die_mm2:1,utilization:.5,ron_area_mohm_mm2:1,cap_uf:4,max_caps:4,max_windings:2,rc_mohm:20,rl_mohm:38,max_drop_percent:10,lk_nh:50,lm_uh:1,max_phase_ripple_percent:5,objective:'loss'};
8
+ function recommend(input,data,engine,technology){const p={...defaults,...input};for(const k of ['ratio','vin','io','fs_mhz','vgs','width_mm','die_mm2','lk_nh','lm_uh'])if(!Number.isFinite(p[k])||p[k]<=0)throw Error(k+' must be positive');for(const k of ['cap_uf','max_caps','max_windings','rc_mohm','rl_mohm','max_drop_percent','max_phase_ripple_percent'])if(!Number.isFinite(p[k])||p[k]<0)throw Error(k+' must be nonnegative');if(![2,4,6,8,16].includes(p.ratio))throw Error('Choose a supported ratio');if(!['width','area'].includes(p.budget_mode)||!['loss','capacitors','magnetics'].includes(p.objective))throw Error('Choose a budget mode and objective');if(!Number.isInteger(p.max_caps)||!Number.isInteger(p.max_windings))throw Error('Component limits must be integers');if(!Number.isFinite(p.utilization)||p.utilization<=0||p.utilization>1)throw Error('Usable die fraction must be in (0,1]');
9
  const calibrated=p.budget_mode==='width'||Number.isFinite(p.ron_area_mohm_mm2)&&p.ron_area_mohm_mm2>0,Wmax=p.budget_mode==='width'?p.width_mm:calibrated?technology.reference.ron*p.die_mm2*p.utilization/(p.ron_area_mohm_mm2*1e-3):null,fs=p.fs_mhz*1e6,m=1/p.ratio,vo=p.vin*m;
10
  if(calibrated&&(!Number.isFinite(Wmax)||Wmax<=0))throw Error('Invalid area/width budget');
11
+ const rows=data.catalog.filter(c=>familyIds(p.ratio).includes(c.id)).map(c=>{const s=specs[c.id],r={id:c.id,name:c.name,short:c.short,native_ratio:s?.ratio??null,reference_match:s?.ratio===p.ratio,asset:c.asset,allocation_reference_ratio:['buck2','sp2'].includes(c.id)?2:4,status:'excluded',reasons:[]};if(!s){r.status='unmodeled';r.reasons=['No verified loss model for recommendation'];return r}Object.assign(r,{capacitors:s.caps,windings:s.windings,magnetics:s.magnetics},ripplePoint(c.id,p));if(r.phase_ripple_percent>=200)r.reasons.push('Predicted phase-current ripple leaves the assumed CCM region');if(r.phase_ripple_percent>p.max_phase_ripple_percent)r.reasons.push('Predicted phase ripple exceeds '+p.max_phase_ripple_percent+'% of average phase current');if(!engine.valid(c.id,m))r.reasons.push(c.id==='sp2'?'Fixed 2:1 conversion only':'Outside the verified duty range');if(s.windings>p.max_windings)r.reasons.push('Requires '+s.windings+' power windings; limit is '+p.max_windings);if(s.caps>p.max_caps)r.reasons.push('Requires '+s.caps+' flying/clamp capacitors; limit is '+p.max_caps);if(s.caps&&p.cap_uf<=0)r.reasons.push('A positive flying/clamp capacitor budget is required');if(!calibrated)r.reasons.push('Enter positive Ron × area (mΩ·mm²)');if(r.reasons.length)return r;
12
  const cf=s.caps?p.cap_uf*1e-6/s.caps:null;
13
  function at(width){const rs=technology.reference.ron*12/width,v=engine.evaluate(c.id,m,{rs,rc:p.rc_mohm/1000,rl:p.rl_mohm/1000,cf:cf??1,fs}),gate=p.vgs*fs*technology.fom.gate*width/technology.reference.ron,loss=p.io*p.io*v.total+gate;return {width_mm:width,rs,req:v.total,req_pu:v.total/(technology.reference.ron*12/Wmax),req_used_width_pu:v.total/rs,conduction_power:p.io*p.io*v.total,gate_power:gate,loss,drop_percent:100*p.io*v.total/vo,estimated_open_loop_vout:vo-p.io*v.total,cf,parts:v}}
14
  // Search total width, not individual device ratios; include both boundaries.
 
16
  let lo=Math.log(grid[Math.max(0,bestIndex-1)]),hi=Math.log(grid[Math.min(64,bestIndex+1)]);for(let i=0;i<50;i++){const a=lo+(hi-lo)/3,b=hi-(hi-lo)/3,va=at(Math.exp(a)),vb=at(Math.exp(b));if(va.loss<best.loss)best=va;if(vb.loss<best.loss)best=vb;if(va.loss<vb.loss)hi=b;else lo=a}
17
  // Droop is a hard screen. A loss-minimizing width can fail it although Wmax passes.
18
  if(best.drop_percent>p.max_drop_percent){const full=at(Wmax);if(full.drop_percent<=p.max_drop_percent){let a=best.width_mm,b=Wmax;for(let i=0;i<60;i++){const mid=(a+b)/2;if(at(mid).drop_percent>p.max_drop_percent)a=mid;else b=mid}best=at(b)}else r.reasons.push('Estimated open-loop droop exceeds '+p.max_drop_percent+'% even at full FET budget')}
19
+ Object.assign(r,best,{used_die_mm2:p.budget_mode==='area'?best.width_mm*p.ron_area_mohm_mm2*1e-3/technology.reference.ron:null,available_width_mm:Wmax,reference_note:'Nominal coupled-inductor cancellation point at '+s.ratio+':1; loss allocation remains fixed at '+(['buck2','sp2'].includes(c.id)?2:4)+':1'});r.status=r.reasons.length?'excluded':'eligible';return r});
20
+ const eligible=rows.filter(r=>r.status==='eligible');eligible.sort((a,b)=>{if(p.objective==='capacitors'&&a.capacitors!==b.capacitors)return a.capacitors-b.capacitors;if(p.objective==='magnetics'&&a.windings!==b.windings)return a.windings-b.windings;return a.loss-b.loss});eligible.forEach((r,i)=>r.rank=i+1);return {parameters:p,available_width_mm:Wmax,rs_budget:calibrated?technology.reference.ron*12/Wmax:null,calibrated,nominal_vout:vo,eligible,rows,winner:eligible[0]??null,native_models:rows.filter(r=>r.reference_match).length,scope:'Coupled-inductor cancellation-point shortlist only. First-order phase ripple is screened with Ldm=Lk+2Lm, balanced complementary 50% effective excitation. Finite capacitor ripple, mismatch, losses and timing errors can break ideal cancellation. Loss ranking remains flat-current FSL/SSL plus gate drive; Coss, ripple-loss corrections, core loss, saturation, layout, startup and control/headroom are not qualified. Fixed per-device allocations; total width optimized. One gate-charge event per device per period assumed. Budgets cover power FETs, flying/clamp capacitors and power windings; drivers/Cin/Cout are outside these budgets.'};}
21
+ const api={recommend,specs,defaults,excitation,familyIds,ripplePoint};root.ThinkPowerRecommendation=api;if(typeof module!=='undefined')module.exports=api;
22
  })(typeof window!=='undefined'?window:globalThis);
test_recommendation.py CHANGED
@@ -8,7 +8,7 @@ def run(p):
8
  return json.loads(subprocess.check_output(['node','-e',js],cwd=ROOT,input=json.dumps(p).encode()))
9
  class RecommendationTest(unittest.TestCase):
10
  def test_area_calibration_and_analytic_buck_width_optimum(self):
11
- r=run({});self.assertAlmostEqual(r['available_width_mm'],.602*.5/.001)
12
  buck=next(x for x in r['eligible'] if x['id']=='buck2')
13
  k=2**2*(1/6)*.602*12;g=3.3*1e7*1.51102e-12/.602
14
  optimum=math.sqrt(k/g)
@@ -17,21 +17,21 @@ class RecommendationTest(unittest.TestCase):
17
  self.assertAlmostEqual(buck['used_die_mm2'],optimum*.001/.602)
18
  self.assertLessEqual(buck['used_die_mm2'],.5)
19
  def test_width_budget_is_a_maximum(self):
20
- a=run(dict(budget_mode='width',width_mm=100,io=.02,max_drop_percent=100))
21
- b=run(dict(budget_mode='width',width_mm=1000,io=.02,max_drop_percent=100))
22
  ra=next(x for x in a['eligible'] if x['id']=='buck2');rb=next(x for x in b['eligible'] if x['id']=='buck2')
23
  self.assertLess(ra['width_mm'],100)
24
  self.assertAlmostEqual(ra['width_mm'],rb['width_mm'],places=5)
25
  self.assertAlmostEqual(ra['loss'],rb['loss'])
26
  def test_component_exclusions(self):
27
- r=run(dict(ratio=2,max_windings=0));self.assertEqual([x['id'] for x in r['eligible']],['sp2'])
28
  r=run(dict(ratio=4,max_windings=0));self.assertIsNone(r['winner'])
29
- r=run(dict(max_caps=0,cap_uf=0));self.assertTrue(r['eligible'])
30
  self.assertTrue(all(x['capacitors']==0 for x in r['eligible']))
31
  def test_ratios_not_invented(self):
32
  for ratio in [6,8,16]:
33
  r=run(dict(ratio=ratio,max_drop_percent=100))
34
- self.assertEqual(r['native_models'],0);self.assertTrue(r['eligible'])
35
  self.assertTrue(all(not x['reference_match'] for x in r['eligible']))
36
  self.assertTrue(all(x['id']!='sp2' for x in r['eligible']))
37
  r=run(dict(ratio=2));self.assertEqual(r['native_models'],2)
@@ -45,14 +45,26 @@ class RecommendationTest(unittest.TestCase):
45
  self.assertAlmostEqual(row['loss'],row['conduction_power']+row['gate_power'])
46
  if row['capacitors']:self.assertAlmostEqual(row['cf']*row['capacitors'],4e-6)
47
  def test_droop_constraint_can_require_larger_width(self):
48
- r=run(dict(rl_mohm=0,max_drop_percent=1.1))
49
  row=next(x for x in r['eligible'] if x['id']=='buck2')
50
- self.assertLessEqual(row['drop_percent'],1.1+1e-10)
51
  self.assertGreater(row['width_mm'],240)
52
  self.assertLessEqual(row['width_mm'],301)
53
  def test_objective_priority(self):
54
- r=run(dict(objective='capacitors'));self.assertEqual(r['winner']['capacitors'],0)
55
- r=run(dict(ratio=2,objective='magnetics'));self.assertEqual(r['winner']['windings'],0)
 
 
 
 
 
 
 
 
 
 
 
 
56
  def test_missing_calibration_and_invalid_inputs(self):
57
  r=run(dict(ron_area_mohm_mm2=0));self.assertFalse(r['calibrated']);self.assertIsNone(r['winner'])
58
  for p in [dict(io=-1),dict(utilization=2),dict(max_caps=1.5),dict(objective='anything'),dict(cap_uf=-1)]:self.assertIn('error',run(p))
 
8
  return json.loads(subprocess.check_output(['node','-e',js],cwd=ROOT,input=json.dumps(p).encode()))
9
  class RecommendationTest(unittest.TestCase):
10
  def test_area_calibration_and_analytic_buck_width_optimum(self):
11
+ r=run(dict(ratio=2));self.assertAlmostEqual(r['available_width_mm'],.602*.5/.001)
12
  buck=next(x for x in r['eligible'] if x['id']=='buck2')
13
  k=2**2*(1/6)*.602*12;g=3.3*1e7*1.51102e-12/.602
14
  optimum=math.sqrt(k/g)
 
17
  self.assertAlmostEqual(buck['used_die_mm2'],optimum*.001/.602)
18
  self.assertLessEqual(buck['used_die_mm2'],.5)
19
  def test_width_budget_is_a_maximum(self):
20
+ a=run(dict(budget_mode='width',width_mm=100,io=.02,ratio=2,lm_uh=100,max_drop_percent=100))
21
+ b=run(dict(budget_mode='width',width_mm=1000,io=.02,ratio=2,lm_uh=100,max_drop_percent=100))
22
  ra=next(x for x in a['eligible'] if x['id']=='buck2');rb=next(x for x in b['eligible'] if x['id']=='buck2')
23
  self.assertLess(ra['width_mm'],100)
24
  self.assertAlmostEqual(ra['width_mm'],rb['width_mm'],places=5)
25
  self.assertAlmostEqual(ra['loss'],rb['loss'])
26
  def test_component_exclusions(self):
27
+ r=run(dict(ratio=2,max_windings=0));self.assertIsNone(r['winner'])
28
  r=run(dict(ratio=4,max_windings=0));self.assertIsNone(r['winner'])
29
+ r=run(dict(ratio=2,max_caps=0,cap_uf=0));self.assertTrue(r['eligible'])
30
  self.assertTrue(all(x['capacitors']==0 for x in r['eligible']))
31
  def test_ratios_not_invented(self):
32
  for ratio in [6,8,16]:
33
  r=run(dict(ratio=ratio,max_drop_percent=100))
34
+ self.assertEqual(r['native_models'],0);self.assertFalse(r['eligible']);self.assertFalse(r['rows'])
35
  self.assertTrue(all(not x['reference_match'] for x in r['eligible']))
36
  self.assertTrue(all(x['id']!='sp2' for x in r['eligible']))
37
  r=run(dict(ratio=2));self.assertEqual(r['native_models'],2)
 
45
  self.assertAlmostEqual(row['loss'],row['conduction_power']+row['gate_power'])
46
  if row['capacitors']:self.assertAlmostEqual(row['cf']*row['capacitors'],4e-6)
47
  def test_droop_constraint_can_require_larger_width(self):
48
+ r=run(dict(ratio=2,rl_mohm=0,max_drop_percent=.55))
49
  row=next(x for x in r['eligible'] if x['id']=='buck2')
50
+ self.assertLessEqual(row['drop_percent'],.55+1e-10)
51
  self.assertGreater(row['width_mm'],240)
52
  self.assertLessEqual(row['width_mm'],301)
53
  def test_objective_priority(self):
54
+ r=run(dict(ratio=2,objective='capacitors'));self.assertEqual(r['winner']['capacitors'],0)
55
+ r=run(dict(ratio=2,objective='magnetics'));self.assertEqual(r['winner']['windings'],2)
56
+ def test_only_cancellation_families_and_phase_ripple(self):
57
+ two=run(dict(ratio=2));self.assertEqual({r['id'] for r in two['rows']},{'buck2','buck'})
58
+ four=run(dict(ratio=4));self.assertEqual({r['id'] for r in four['rows']},{'xfly2p','xfly4p','3lbuck','2sbuck'})
59
+ r=next(r for r in two['eligible'] if r['id']=='buck2')
60
+ lself=50e-9+1e-6;mutual=-1e-6;v1=3.3/2;v2=-v1
61
+ slope=(lself*v1-mutual*v2)/(lself*lself-mutual*mutual)
62
+ self.assertAlmostEqual(r['phase_ripple_pp'],slope/(2*1e7))
63
+ self.assertGreater(r['phase_ripple_pp'],0)
64
+ self.assertAlmostEqual(r['phase_ripple_percent'],100*r['phase_ripple_pp'])
65
+ weak=run(dict(ratio=2,lm_uh=.001));self.assertFalse(weak['eligible'])
66
+ self.assertTrue(all(any('phase ripple' in reason for reason in row['reasons']) for row in weak['rows']))
67
+ self.assertTrue(all(r['phase_ripple_percent']<=5 for r in four['eligible']))
68
  def test_missing_calibration_and_invalid_inputs(self):
69
  r=run(dict(ron_area_mohm_mm2=0));self.assertFalse(r['calibrated']);self.assertIsNone(r['winner'])
70
  for p in [dict(io=-1),dict(utilization=2),dict(max_caps=1.5),dict(objective='anything'),dict(cap_uf=-1)]:self.assertIn('error',run(p))