#!/usr/bin/env python3 """Input dependence of existing 64-sample coefficient-control approximations.""" from analyze import * from analyze_eq_interpolation import interpolated from analyze_control import render_interpolated FREQUENCIES=[80,1000,8000,18000] METHODS=['eq-df1','eq-tdf2','eq-svf','phaser-lattice'] def main(): plan={'rates':[48000,96000],'lfo_hz':[.5,3.],'input_tones_hz':FREQUENCIES,'other_inputs':['bandlimited20-20000Hz noise RMS0.1','unit clicks at2.125,3.125,4.125,5.125s'],'seconds':6,'preparation_seconds':2,'future_guard_samples':64,'coefficient_step_samples':64,'modes':['hold','linear'],'methods':METHODS,'seed':511057} plan.update(eq_fixed_bands=[{'kind':'low shelf','frequency_hz':120,'gain_db':6,'q':2**-.5},{'kind':'high shelf','frequency_hz':7000,'gain_db':4,'q':2**-.5}],eq_automated_bell={'frequency_hz':[250,4000],'gain_db':[-9,9],'gain_phase_offset_radians':.3,'q':1.2},phaser={'stages':6,'spread_octaves':2,'center_hz':[80,4000],'feedback':.7,'mix':.5,'stereo_lfo_phase_degrees':90}) save_json('control-input-plan.json',plan);rows=[];traces={};rng=np.random.default_rng(plan['seed']) for rate in plan['rates']: n=6*rate;guard=64;t=np.arange(n+guard)/rate;mono=rng.standard_normal(n+guard);s=np.fft.rfft(mono);f=np.fft.rfftfreq(len(mono),1/rate);s[(f<20)|(f>20000)]=0;mono=np.fft.irfft(s,len(mono));mono*=.1/np.sqrt(np.mean(mono[:n]**2));sources={f'tone-{freq}':np.column_stack([.25*np.sin(2*np.pi*freq*t+.3)]*2)for freq in FREQUENCIES};sources['noise']=np.column_stack([mono,mono]);clicks=np.zeros((n+guard,2));clicks[(np.array([2.125,3.125,4.125,5.125])*rate).astype(int)]=1.;sources['clicks']=clicks for lfo in plan['lfo_hz']: phase=2*np.pi*lfo*t;profile=np.array([(1,120,6,2**-.5),(0,1200,-8,1.2),(2,7000,4,2**-.5)]);ec=np.broadcast_to(profile,(len(t),3,4)).copy();ec[:,1,1]=1000*2**(2*np.sin(phase));ec[:,1,2]=9*np.sin(phase+.3) pc=np.broadcast_to(np.array([1000.,2,6,1,.7,.5]),(len(t),2,6)).copy() for ch in [0,1]:pc[:,ch,0]=np.sqrt(80*4000)*np.exp(.5*np.log(4000/80)*np.sin(phase+ch*np.pi/2)) for method in METHODS: family,form=method.split('-');control=ec if family=='eq'else pc for name,x in sources.items(): reference=render('eq'if family=='eq'else'phaser',form,rate,x,control);sl=slice(2*rate,n);rms=float(np.sqrt(np.mean(reference[sl]**2))) for mode in ['hold','linear']: if mode=='hold':y=render('eq'if family=='eq'else'phaser',form,rate,x,control[np.arange(len(t))//64*64]) elif family=='eq':y=interpolated(form,rate,64,x,control) else:y=render_interpolated(form,rate,x,control,64) d=y[sl]-reference[sl];error=float(np.sqrt(np.mean(d*d)));row=dict(method=method,rate=rate,lfo_hz=lfo,input=name,mode=mode,step_samples=64,step_ms=64000/rate,reference_rms=rms,rms_error=error,rms_error_relative_db=float(20*np.log10(max(error/rms,1e-30))),max_absolute_error=float(np.max(abs(d))),reference_peak=float(np.max(abs(reference[sl]))),output_peak=float(np.max(abs(y[sl]))));rows.append(row) if name=='noise': # Preserve a short deterministic window, not large duplicated audio files. key=f'{method}-{rate}-{lfo}';start=3*rate;traces[key+'-reference']=reference[start:start+1024];traces[key+'-linear']=y[start:start+1024] print(f'completed {rate}Hz LFO{lfo}',flush=True) save_json('control-input-dependence.json',rows);np.savez_compressed(ROOT/'data/control-input-windows.npz',**traces) fig,axes=plt.subplots(2,2,figsize=(12,8),sharex=True) for li,lfo in enumerate(plan['lfo_hz']): for mi,method in enumerate(METHODS): ax=axes[int(method.startswith('phaser')),li] for rate in plan['rates']: selected=[next(r for r in rows if r['method']==method and r['rate']==rate and r['lfo_hz']==lfo and r['input']==f'tone-{f}'and r['mode']=='linear')for f in FREQUENCIES] ax.semilogx(FREQUENCIES,[r['rms_error_relative_db']for r in selected],marker='o',ls='-'if rate==48000 else'--',color=COLORS[mi],label=f'{method.removeprefix("eq-")} {rate//1000}kHz') for ri in [0,1]: axes[ri,li].set(title=f'{"EQ Tone3"if ri==0 else"Phaser6"}: LFO{lfo:g}Hz',xlabel='Input sine frequency (Hz)',ylabel='RMS difference / reference RMS (dB)',xticks=FREQUENCIES,xticklabels=['80','1k','8k','18k']);axes[ri,li].legend(fontsize=8,ncol=2 if ri==0 else 1);axes[ri,li].grid(alpha=.25) fig.suptitle('Known LFO: 64-sample linear coefficient interpolation versus per-sample design\nSine peak0.25; 2s prepare+4s observe; 64-sample future guard excluded; f64');fig.tight_layout();fig.savefig(ROOT/'figures/control-input-dependence.png');plt.close(fig) fig,axes=plt.subplots(1,2,figsize=(12,5),sharey=True) for ax,name in zip(axes,['clicks','noise']): for li,lfo in enumerate(plan['lfo_hz']): for ri,rate in enumerate(plan['rates']): selected=[next(r for r in rows if r['method']==m and r['rate']==rate and r['lfo_hz']==lfo and r['input']==name and r['mode']=='linear')for m in METHODS];ax.plot(np.arange(4),[r['rms_error_relative_db']for r in selected],marker='o',ls='-'if rate==48000 else'--',color=COLORS[li],label=f'LFO{lfo:g}Hz / {rate//1000}kHz') ax.set(xticks=np.arange(4),xticklabels=['DF1','TDF2','SVF','Lattice'],title=name,ylabel='RMS difference / reference RMS (dB)');ax.legend(fontsize=8);ax.grid(alpha=.25) fig.suptitle('64-sample coefficient interpolation: sparse impulses and broadband input\nClicks1.0 at2.125/3.125/4.125/5.125s; noise20–20kHz RMS0.1; same2–6s observation');fig.tight_layout();fig.savefig(ROOT/'figures/control-input-transients.png');plt.close(fig) print('rows',len(rows)) if __name__=='__main__':main()