Spaces:
Running
Running
Download models.py from minjiechen/ThinkPower: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/spaces/minjiechen/ThinkPower/resolve/main/models.py
- Command line
-
hf download hf://spaces/minjiechen/ThinkPower/models.py
-
curl -L -o models.py https://huggingface.co/spaces/minjiechen/ThinkPower/resolve/main/models.py
15.7 kB
| """Traceable limiting models transcribed from XFLY-IEEE Table I. | |
| Numerical outputs are estimates, never a substitute for a verified switched graph. | |
| """ | |
| import math | |
| import numpy as np | |
| CATALOG = [ | |
| dict(id='xfly2p',name='XFLY6S · 2P',short='XFLY2P',family='Cross-linked',switches=6,color='#168276',gain='M = D/2',range='0 < M < 0.5',status='Paper model',ratio=[1,1,1,3],asset='xfly6s.svg',note='Paper XFLY2P coefficients use the effective six-switch current model with the physical split-middle 1:1:1:3 area allocation. A true six-device area budget requires a separate normalization. Clamp recharge is excluded.'), | |
| dict(id='xfly4p',name='XFLY8S · 4P',short='XFLY4P',family='Cross-linked',switches=8,color='#cf7b30',gain='M = D/2; gate pulse d = D/2',range='0 < M ≤ 0.25',status='Paper model · limited',ratio=[1,1,1,math.sqrt(5)],asset='xfly4p.svg',note='Split-middle four-pulse realization only. Additional clamp recharge is excluded; this is not a loss model for every eight-switch control sequence.'), | |
| dict(id='3lbuck',name='Three-level buck',short='3LBUCK',family='Flying capacitor',switches=8,color='#5c70b8',gain='M = D/2; gate duty = M',range='0 < M ≤ 0.5',status='Paper model',ratio=[1,1,math.sqrt(3),math.sqrt(3)],asset='3lbuck.svg',note='Two phases, local flying capacitors, lower-half-input operating region.'), | |
| dict(id='2sbuck',name='Capacitor-clamped buck',short='2SBUCK',family='Clamped',switches=8,color='#ad5c88',gain='M = D/2',range='0 < M < 0.5',status='Paper model',ratio=[1,1,1,3],asset='2sbuck.svg',note='Equal main and clamp capacitance; clamp ESR = 0. Recharge still contributes to switch current and SSL loss.'), | |
| dict(id='buck',name='Stacked synchronous buck',short='BUCK',family='Benchmark',switches=8,color='#48535f',gain='M = gate duty; comparison D = 2M',range='0 < M ≤ 0.5',status='Paper model',ratio=[1,1,math.sqrt(3),math.sqrt(3)],asset='buck.svg',note='Two phases, two series devices in each switch position. Nominal voltage sharing requires suitable drive/balancing.'), | |
| dict(id='buck2',name='Two-phase synchronous buck',short='BUCK2Φ',family='2:1 family · four MOSFETs',switches=4,color='#a06a22',gain='M = gate duty Db',range='0 < M < 1; sized at M = 0.5',status='Derived flat-current model',ratio=[1,1],asset='buck2.svg',note='Two 180-degree interleaved phases, one upper and one lower MOSFET each; two inverse-coupled windings. Equal widths at the 2:1 sizing point, total 12 A0. RFET = Rs/6; RIND = Rl/2. Flat equal winding currents; winding DCR is unchanged by coupling. Mutual inductance affects ripple and dynamics, which are not quantified here.'), | |
| dict(id='sp2',name='2:1 series-parallel SC',short='SP-SC 2:1',family='2:1 family · two SC phases',switches=8,color='#8c6caf',gain='Fixed ideal M = 1/2; 50% two-state clock',range='M = 0.5 only; finite output droop',status='Derived periodic RC model',ratio=[1,1,1,1],asset='sp2.svg',note='Two interleaved four-switch series-parallel cells; two equal flying capacitors, no power inductor. Identical switches Rs×2/3, stiff ports, 50% states, dead time omitted. Exact linear periodic RC: Req = RSSL coth(RSSL/RFSL), RFSL = 2Rs/3 + Rc/2, RSSL = 1/(8 Cf fs), Cf per phase. Fixed 2:1 topology; not a continuously variable ratio.'), | |
| dict(id='boost',name='XFLY-Boost',short='XFLY-Boost',family='Step-up',switches=2,color='#3a849b',gain='Vhigh/Vlow = 2/(1−Db)',range='Balanced CCM branch: Db ≥ 0.5',status='Topology only',ratio=[],asset='boost.svg',note='Two low-side MOSFETs and four diodes. Buck loss coefficients cannot be reused for this graph. No numeric loss model is assigned.'), | |
| dict(id='ns',name='XFLY-NS',short='XFLY-NS',family='Scalable',switches=8,color='#887553',gain='Sequence and level dependent',range='Requires state-table derivation',status='Topology only',ratio=[],asset='ns.svg',note='Use the state-table workspace to derive coefficients for a specified extension and switching sequence.'), | |
| ] | |
| INDEX={x['id']:x for x in CATALOG} | |
| FORMULAS={ | |
| 'buck2':['Rs/6 (equal fixed widths; Db=M)','0','Rl/2','0'], | |
| 'sp2':['2 Rs/3','Rc/2','0','1/(8 Cf fs); Req = RSSL coth[RSSL/(2Rs/3 + Rc/2)]'], | |
| 'xfly2p':['(2+5D) Rs /12, D≤0.5; (5D²−2D+2) Rs /[12(1−D)], D>0.5','D Rc /4, D≤0.5; D² Rc /[4(1−D)], D>0.5','Rl /2','max(2D−1,0)² / (8 Cf fs)'], | |
| 'xfly4p':['(3+√5)[3D+(2+D)/√5] Rs /24','D Rc /2','Rl /2','0 (specified sequence)'], | |
| '3lbuck':['(1+√3)[D+(2−D)/√3] Rs /6','D Rc /2','Rl /2','0 (specified sequence)'], | |
| '2sbuck':['(2+D−D²) Rs /[12(1−D)]','D Rc /[8(1−D)]','Rl /2','D² / (8 Cf fs)'], | |
| 'buck':['(1+√3)[D+(2−D)/√3] Rs /6','0','Rl /2','0'], | |
| } | |
| def number(p,key,default,lo,hi): | |
| try:v=float(p.get(key,default)) | |
| except (ValueError,TypeError):raise ValueError(f'{key} must be a number') | |
| if not math.isfinite(v) or not lo<=v<=hi:raise ValueError(f'{key} must be between {lo} and {hi}') | |
| return v | |
| def coefficients(key,D): | |
| if key=='buck2':return (1/6,0,0) | |
| if key=='sp2':return (2/3,.5,1/8) | |
| if key=='xfly2p': | |
| return ((2+5*D)/12,D/4,0) if D<=.5 else ((5*D*D-2*D+2)/(12*(1-D)),D*D/(4*(1-D)),max(2*D-1,0)**2/8) | |
| if key=='xfly4p':return ((3+math.sqrt(5))/24*(3*D+(2+D)/math.sqrt(5)),D/2,0) | |
| if key in ('3lbuck','buck'):return ((1+math.sqrt(3))/6*(D+(2-D)/math.sqrt(3)), D/2 if key=='3lbuck' else 0,0) | |
| if key=='2sbuck':return ((2+D-D*D)/(12*(1-D)),D/(8*(1-D)),D*D/8) | |
| raise ValueError('This topology has no verified numeric loss model') | |
| def valid(key,M): | |
| if key not in FORMULAS:return False | |
| if key=='sp2':return abs(M-.5)<1e-12 | |
| if key=='buck2':return 0<M<1 | |
| return M>0 and (M<=.25+1e-12 if key=='xfly4p' else M<.5 if key in ('xfly2p','2sbuck') else M<=.5) | |
| def charging_resistance(key,net,ssl): | |
| if key=='sp2':return ssl/math.tanh(ssl/net) if net and ssl else net+ssl | |
| return math.hypot(net,ssl) | |
| def evaluate(key,M,p): | |
| if not valid(key,M):return None | |
| D=2*M; a,b,c=coefficients(key,D) | |
| fet=a*p['rs'];cap=b*p['rc'];ind=(0 if key=='sp2' else .5)*p['rl'];ssl=c/(p['cf']*p['fs']) | |
| total=ind+charging_resistance(key,fet+cap,ssl) | |
| return dict(fet=fet,cap=cap,ind=ind,ssl=ssl,fsl=fet+cap+ind,total=total,coefficients=[a,b,0 if key=='sp2' else .5,c],D=D,gate_duty=M if key=='buck2' else .5 if key=='sp2' else None) | |
| def allocation(key): | |
| # Figure 18 uses the physical split-middle layout for XFLY2P. | |
| if key=='xfly2p':weights=[1,1,1,3]; per_phase=6 | |
| else:weights=INDEX[key]['ratio'];per_phase=6 | |
| s=sum(weights);areas=[per_phase*x/s for x in weights] | |
| return dict(relative=weights,areas=areas,area_fractions=[x/12 for x in areas],labels=[f'S{i+1}' for i in range(len(areas))],total_area=12,reference_ratio=2 if key in ('buck2','sp2') else 4) | |
| def analyze(payload): | |
| p=dict(rs=number(payload,'rs_mohm',20,0,1e5)/1000,rc=number(payload,'rc_mohm',20,0,1e5)/1000, | |
| rl=number(payload,'rl_mohm',20,0,1e5)/1000,cf=number(payload,'cf_nf',50,.001,1e9)*1e-9, | |
| fs=number(payload,'fs_mhz',50,.000001,1e4)*1e6) | |
| ratio=number(payload,'ratio',4,1.01,256); M=1/ratio;io=number(payload,'iout',10,.001,1e6);vin=number(payload,'vin',16,.001,1e6) | |
| selected=payload.get('topologies',['xfly2p','xfly4p','3lbuck','2sbuck','buck']) | |
| if not isinstance(selected,list) or not selected or any(k not in INDEX for k in selected):raise ValueError('Select known topologies') | |
| rows=[] | |
| for key in dict.fromkeys(selected): | |
| r=evaluate(key,M,p);meta=INDEX[key] | |
| row=dict(id=key,name=meta['name'],short=meta['short'],color=meta['color'],note=meta['note'],formulas=FORMULAS.get(key),allocation=allocation(key) if key in FORMULAS else None,valid=r is not None,domain=meta['range']) | |
| if r: | |
| loss=io*io*r['total'];pout=vin*M*io | |
| row.update(r);row.update(loss_w=loss,conduction_efficiency=100*pout/(pout+loss),droop_estimate_v=io*r['total']) | |
| rows.append(row) | |
| xs=np.unique(np.r_[np.linspace(.0005,.4995,500),.25,.5,M]) | |
| curves=[] | |
| for key in dict.fromkeys(selected): | |
| pts=[] | |
| for x in xs: | |
| r=evaluate(key,float(x),p) | |
| if r:pts.append([float(x),r['total']*1000]) | |
| if pts:curves.append(dict(id=key,name=INDEX[key]['short'],color=INDEX[key]['color'],points=pts)) | |
| return dict(ratio=ratio,M=M,vin=vin,iout=io,parameters=p,rows=rows,curves=curves, | |
| provenance='XFLY-IEEE Section V-F, Table I; Figures 18–20. Equations transcribed from the current working manuscript.', | |
| assumptions=['Fixed transistor allocations: 4:1 for paper cells, 2:1 for BUCK2Φ and SP-SC; total area 12 A₀ and identical device technology.', | |
| 'Matched average phase currents; flat-current FSL for inductive cells, periodic linear RC for SP-SC; zero clamp-capacitor ESR.', | |
| 'Paper cells: Rout = RIND + √((RFET + RCAP)² + RSSL²). SP-SC: exact periodic RC coth relation. FSL and SSL are asymptotes, not additive losses.', | |
| 'Switching transitions, gate drive, core loss, winding ripple, dead time and interconnect loss are excluded.', | |
| 'An operating ratio change is not a newly derived higher-order topology. Additional levels need their own graph and state model.', | |
| 'Conduction efficiency uses nominal output power and modeled conduction loss; it is not a measured or total converter efficiency.']) | |
| def state_model(p): | |
| """Evaluate user-reviewed normalized state currents, with periodic charge balance.""" | |
| states=p.get('states',[]);budget=number(p,'area_budget',12,.001,1e6) | |
| if not isinstance(states,list) or not 1<=len(states)<=64:raise ValueError('Provide 1–64 switching states') | |
| def vector(v): | |
| if not isinstance(v,list) or len(v)>256:raise ValueError('State currents must be arrays with at most 256 entries') | |
| a=np.asarray(v,dtype=float) | |
| if not np.isfinite(a).all() or (abs(a)>1e6).any():raise ValueError('Invalid normalized current') | |
| return a | |
| durations=np.array([number(s,'fraction',0,0,1) for s in states]) | |
| if abs(durations.sum()-1)>1e-7:raise ValueError('State fractions must sum to 1') | |
| out={};weights={} | |
| for field in ['switch','capacitor','inductor']: | |
| vs=[vector(s.get(field+'_currents',[])) for s in states] | |
| if len({len(a) for a in vs})!=1:raise ValueError(f'{field} current dimensions must match in every state') | |
| matrix=np.array(vs);weights[field]=(durations[:,None]*matrix**2).sum(axis=0) | |
| if field=='capacitor': | |
| charge=(durations[:,None]*matrix).sum(axis=0) | |
| if np.any(abs(charge)>1e-7):raise ValueError('Capacitor charge balance failed: '+str(charge.tolist())) | |
| out['capacitor_charge_residuals']=charge.tolist() | |
| roots=np.sqrt(weights['switch']);den=roots.sum() | |
| if den<=0:raise ValueError('At least one switch must carry current') | |
| areas=budget*roots/den | |
| rs=number(p,'rs_mohm',20,0,1e5)/1000 | |
| rc=number(p,'rc_mohm',20,0,1e5)/1000 | |
| rl=number(p,'rl_mohm',20,0,1e5)/1000 | |
| out.update(switch_weights=weights['switch'].tolist(),capacitor_weights=weights['capacitor'].tolist(),inductor_weights=weights['inductor'].tolist(),optimal_areas=areas.tolist(),rfet=rs*den**2/budget,rcap=rc*weights['capacitor'].sum(),rind=rl*weights['inductor'].sum(),status='Conditional FSL result: charge balance checked; KCL, gate legality, voltage balance and graph consistency must be independently verified. SSL is not inferred from these currents.') | |
| return out | |
| def control(p): | |
| # Separate verification operating point: not silently tied to 50 MHz loss example. | |
| vin=number(p,'vin',16,.01,1e4);D=number(p,'duty',.4,.001,.5);io=number(p,'iout',10,.001,1e5) | |
| cf=number(p,'cf_uf',2,.001,1e6)*1e-6;co=number(p,'co_uf',10,.001,1e6)*1e-6 | |
| rl=number(p,'rl_mohm',20,.001,1e4)/1000;lk=number(p,'lk_nh',200,.01,1e9)*1e-9;lm=number(p,'lm_uh',2,0,1e6)*1e-6 | |
| fs=number(p,'fs_khz',500,.1,1e6)*1e3;fc=number(p,'fc_khz',5,.001,fs/1e3/4)*1e3;fp=min(fc*10,fs/3) | |
| vo=D*vin/2-rl*io/2 | |
| if vo<=0:raise ValueError('The requested load exceeds the positive-output equilibrium of this model') | |
| load=vo/io;ldm=lk+2*lm;f=np.logspace(1,np.log10(fs/2),1000);s=2j*np.pi*f | |
| def plant(z):return vin/((lk*z+rl)*(co*z+1/load)+2) | |
| z=2j*np.pi*fc;ki=abs(z*(1+z/(2*np.pi*fp)))/abs(plant(z)) | |
| loop=plant(s)*ki/(s*(1+s/(2*np.pi*fp)))*np.exp(-s/fs) | |
| phase=np.unwrap(np.angle(loop))*180/np.pi | |
| gc=vin/((lk*s+rl)*(co*s+1/load)+2) | |
| gd=-(io*(ldm*s+rl)+D*vin)/(2*(ldm*cf*s*s+rl*cf*s+D*D)) | |
| ph_fc=float((np.angle(plant(z))-np.pi/2-np.arctan(fc/fp)-2*np.pi*fc/fs)*180/np.pi) | |
| crosses=np.where(np.diff(np.sign(np.log(abs(loop))))!=0)[0] | |
| return dict(frequency=f.tolist(),loop_db=(20*np.log10(abs(loop))).tolist(),loop_phase=phase.tolist(),gcm_db=(20*np.log10(abs(gc))).tolist(),gdm_db=(20*np.log10(abs(gd))).tolist(),fc=fc,f_dm=D/(2*np.pi*np.sqrt(ldm*cf)),f_cm=np.sqrt((2+rl/load)/(lk*co))/(2*np.pi),phase_margin=180+ph_fc,unity_crossings=len(crosses),ki=ki,fp=fp,vo=vo, | |
| note='XFLY6S symmetric nonoverlap CCM example only. Unity feedback/PWM gain, resistive load, stiff source, one-period delay. The voltage loop does not damp an unobservable differential mode; input-filter interaction requires an impedance model.') | |
| def analyze_pu(payload): | |
| """Compare dimensionless coefficients using Rs as the shared resistance base.""" | |
| rho_c=number(payload,'rho_c',1,0,1e6) | |
| rho_l=number(payload,'rho_l',1,0,1e6) | |
| rho_q=number(payload,'rho_q',20,0,1e9) | |
| ratio=number(payload,'ratio',4,1.01,256);M=1/ratio | |
| selected=payload.get('topologies',['xfly2p','xfly4p','3lbuck','2sbuck','buck']) | |
| if not isinstance(selected,list) or not selected or any(k not in INDEX for k in selected):raise ValueError('Select known topologies') | |
| def result(key,m): | |
| if not valid(key,m):return None | |
| a,b,c=coefficients(key,2*m) | |
| fet=a;cap=b*rho_c;ind=(0 if key=='sp2' else .5)*rho_l;ssl=c*rho_q | |
| net=fet+cap | |
| increment=(charging_resistance(key,net,ssl)-net) if key=='sp2' else ssl*ssl/(math.hypot(net,ssl)+net) if net or ssl else 0 | |
| return dict(fet=fet,cap=cap,ind=ind,ssl=ssl,ssl_series=increment,fsl=fet+cap+ind,total=ind+charging_resistance(key,net,ssl),coefficients=[a,b,0 if key=='sp2' else .5,c],D=2*m,gate_duty=m if key=='buck2' else .5 if key=='sp2' else None) | |
| rows=[] | |
| for key in dict.fromkeys(selected): | |
| r=result(key,M);meta=INDEX[key] | |
| row=dict(id=key,name=meta['name'],short=meta['short'],color=meta['color'],note=meta['note'],formulas=FORMULAS.get(key),allocation=allocation(key) if key in FORMULAS else None,valid=r is not None,domain=meta['range']) | |
| if r:row.update(r) | |
| rows.append(row) | |
| xs=np.unique(np.r_[np.linspace(.0005,.4995,500),.25,.5,M]);curves=[] | |
| for key in dict.fromkeys(selected): | |
| pts=[] | |
| for m in xs: | |
| r=result(key,float(m)) | |
| if r:pts.append([float(m),r['total']]) | |
| if pts:curves.append(dict(id=key,name=INDEX[key]['short'],color=INDEX[key]['color'],points=pts)) | |
| assumptions=analyze({})['assumptions'] | |
| assumptions=[x for x in assumptions if not x.startswith('Conduction efficiency')] | |
| assumptions.insert(0,'Rs is the common resistance base. rho_C=Rc/Rs; rho_L=Rl/Rs; rho_Q=1/(Cf fs Rs). No absolute resistance, current or power is assigned.') | |
| assumptions.insert(1,'Table columns k_FET=RFET/Rs, k_CAP=RCAP/Rc, k_IND=RIND/Rl and k_SSL=RSSL Cf fs are independent coefficients. These columns are not directly additive. Coefficients remain defined when their corresponding loss scale is zero.') | |
| return dict(ratio=ratio,M=M,normalization=dict(base='R_S',rho_c=rho_c,rho_l=rho_l,rho_q=rho_q,component_unit='R/R_S',coefficient_bases=['R_S','R_C','R_L','1/(C_F f_s)']),rows=rows,curves=curves,provenance='XFLY-IEEE Section V-F, Table I; Figures 18–20. Dimensionless form of the current manuscript models.',assumptions=assumptions) | |
| def state_model_pu(payload): | |
| """Return coefficients from normalized state currents; no device values needed.""" | |
| out=state_model({**payload,'rs_mohm':1000,'rc_mohm':1000,'rl_mohm':1000}) | |
| return {k:v for k,v in out.items() if k not in ['rfet','rcap','rind']} | dict(k_fet=out['rfet'],k_cap=out['rcap'],k_ind=out['rind'],bases=dict(k_fet='R_S',k_cap='R_C',k_ind='R_L'),normalization='Currents / Iout; areas / A0; resistances as coefficients of Rs, Rc, Rl. SSL requires a separate charge-transfer model.') | |