"""Isolated /ba/-inspired teaching circuit: one oscillator, two fixed gesture paths. Run: python oscillator_gestures.py Redraw saved data only: python oscillator_gestures.py --figures-only Nengo 4.1.0; no articulatory plant, lexical selection, or syllable sequencing. """ from pathlib import Path import hashlib,json,math,sys import numpy as np import nengo HERE=Path(__file__).resolve().parent OUT=HERE/'figures' FREQUENCY=1.5 TAU_OSC=.025 TAU_RAMP=.005 DT=.001 DURATION=1.6 WINDOWS={'lip':(.15,.431707317073,1.),'vowel':(.292682926829,.715243902439,.95)} VELOCITIES={'lip':.2,'vowel':.05} COLORS={'lip':'#245b78','vowel':'#ac572b'} def phase_drive(x,window): if np.dot(x,x)<.09: return 0. phase=math.atan2(x[1],x[0])/(2*math.pi)+.5 return window[2] if window[0]<=phase7.5/8*math.pi else x def build(): with nengo.Network(seed=11,label='One syllable, two fixed gesture paths') as model: kick=nengo.Node(lambda t:.5 if .15<=t<.20 else 0.) oscillator=nengo.Ensemble(2500,2,intercepts=nengo.dists.Uniform(.3,1),label='Syllable oscillator') nengo.Connection(kick,oscillator,transform=[[-1],[0]],synapse=.005) omega=2*math.pi*FREQUENCY nengo.Connection(oscillator,oscillator,function=cutoff, transform=[[1,-TAU_OSC*omega],[TAU_OSC*omega,1]],synapse=TAU_OSC) probes={'kick':nengo.Probe(kick), 'oscillator':nengo.Probe(oscillator,synapse=.01), 'oscillator_spikes':nengo.Probe(oscillator.neurons)} conns={} for name,window in WINDOWS.items(): pulse=nengo.Ensemble(200,1,intercepts=nengo.dists.Uniform(.02,1),label=name+' phase drive') conns[name]=nengo.Connection(oscillator,pulse, function=lambda x,w=window:phase_drive(x,w),synapse=.005) ramp=nengo.Ensemble(1000,1,label=name+' gesture activation') k=VELOCITIES[name] nengo.Connection(pulse,ramp,transform=k,synapse=TAU_RAMP) nengo.Connection(ramp,ramp,transform=1-k, function=lambda x:min(.9,x[0]),synapse=TAU_RAMP) probes[name+'_pulse']=nengo.Probe(pulse,synapse=.01) probes[name+'_ramp']=nengo.Probe(ramp,synapse=.01) probes[name+'_pulse_spikes']=nengo.Probe(pulse.neurons) probes[name+'_ramp_spikes']=nengo.Probe(ramp.neurons) return model,oscillator,probes,conns def crossings(t,xy): radius=np.linalg.norm(xy,axis=1) phase=np.arctan2(xy[:,1],xy[:,0])/(2*np.pi)+.5 result={} for name,window in WINDOWS.items(): result[name]={} for kind,value in zip(['start','end'],window[:2]): idx=np.flatnonzero((phase[:-1]=value)&(radius[:-1]>=.3)&(radius[1:]>=.3)&(t[:-1]>.2)) if not len(idx):raise AssertionError((name,kind,'no crossing')) j=int(idx[0]);result[name][kind]=float(t[j]+(value-phase[j])/(phase[j+1]-phase[j])*(t[j+1]-t[j])) return result def first_sustained(t,x,threshold,after,above=True,dwell=20): condition=(x>threshold) if above else (x=after)&condition): if i+dwell<=len(t) and np.all(condition[i:i+dwell]):return float(t[i]) return None def run(): from nengo.utils.ensemble import tuning_curves nengo.rc.set('decoder_cache','enabled','False') model,osc,probes,conns=build() with nengo.Simulator(model,dt=DT,progress_bar=False) as sim: sim.run(DURATION,progress_bar=False) d={k:sim.data[p].copy() for k,p in probes.items()};d['time']=sim.trange() phases=np.linspace(0,1,721) d['fit_phase']=phases for radius in [.75,.15]: points=radius*np.column_stack([np.cos((phases-.5)*2*np.pi),np.sin((phases-.5)*2*np.pi)]) rates=tuning_curves(osc,sim,points)[1] for name in WINDOWS: weights=sim.data[conns[name]].weights d[f'{name}_fit_r{int(radius*100)}']=(rates@weights.T).ravel() np.savez_compressed(OUT/'oscillator-gestures-data.npz',**d) boundaries=crossings(d['time'],d['oscillator']) observations={} t=d['time'] for name in WINDOWS: p=d[name+'_pulse'][:,0];a=d[name+'_ramp'][:,0] po=first_sustained(t,p,.2,.2) pe=first_sustained(t,p,.2,po+.05,False) ao=first_sustained(t,a,.2,.2) ae=first_sustained(t,a,.2,pe,False) observations[name]={'phase_crossings_s':boundaries[name], 'pulse_above_0_2_s':po,'pulse_below_0_2_s':pe, 'activation_above_0_2_s':ao,'activation_below_0_2_s':ae, 'peak_activation':float(a.max()),'activation_peak_s':float(t[np.argmax(a)]), 'pulse_spikes':int((d[name+'_pulse_spikes']>0).sum()), 'ramp_spikes':int((d[name+'_ramp_spikes']>0).sum())} assert po is not None and ao is not None and ae is not None assert a.max()>.6 and abs(a[t>=1.3].mean())<.1 both=(d['lip_ramp'][:,0]>.2)&(d['vowel_ramp'][:,0]>.2) active=np.linalg.norm(d['oscillator'],axis=1)>.3 report={'nengo':nengo.__version__,'numpy':np.__version__,'seed':11,'neurons':sum(e.n_neurons for e in model.all_ensembles), 'dt_s':DT,'duration_s':DURATION,'frequency_hz':FREQUENCY,'tau_oscillator_s':TAU_OSC,'tau_ramp_s':TAU_RAMP, 'probe_filter_s':.01,'connection_filter_s':.005,'kick_s':[.15,.20],'kick_amplitude':.5, 'phase_windows':{k:list(v) for k,v in WINDOWS.items()},'velocity':VELOCITIES, 'phase_convention':'atan2(x1,x0)/(2*pi)+0.5; zero at left, increases counterclockwise through lower half', 'cutoff_phase':.96875,'radial_drive_threshold':.3,'observations':observations, 'oscillator_radius_above_0_3_first_s':float(t[np.flatnonzero(active)[0]]), 'oscillator_radius_above_0_3_last_s':float(t[np.flatnonzero(active)[-1]]), 'joint_activation_above_0_2_ms':int(both.sum()), 'threshold_dwell_ms':20, 'scope':'Isolated teaching diagnostic using archived oscillator/phase/ramp rules. One fixed /ba/-inspired pair: lip closure and vowel activation. No voicing, articulatory movement, perception, lexical retrieval, competing routes or next-syllable control.', 'source_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'data_sha256':hashlib.sha256((OUT/'oscillator-gestures-data.npz').read_bytes()).hexdigest()} assert report['neurons']==4900 assert report['joint_activation_above_0_2_ms']>20 assert report['oscillator_radius_above_0_3_last_s']<1.2 report['checks_passed']=['Both phase drives and gesture activations present','Gesture activation overlaps','Both activations return near zero','Oscillator returns below radius threshold'] (OUT/'observations.json').write_text(json.dumps(report,indent=2)+'\n') print(json.dumps(report,indent=2)) def plot(): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import Arc plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,'axes.spines.right':False,'pdf.fonttype':42}) d=np.load(OUT/'oscillator-gestures-data.npz');t=d['time'];report=json.loads((OUT/'observations.json').read_text()) # Geometric phase reference and a recorded trajectory, with correct phase convention. fig,axs=plt.subplots(1,2,figsize=(10,4.1),gridspec_kw={'width_ratios':[1,1.2]}) ax=axs[0];theta=np.linspace(0,2*np.pi,361);ax.plot(np.cos(theta),np.sin(theta),color='#c6d0c7',lw=.8) for name,w in WINDOWS.items(): rr=1.05 if name=='lip' else 1.16 angles=np.linspace((w[0]-.5)*2*np.pi,(w[1]-.5)*2*np.pi,100) ax.plot(rr*np.cos(angles),rr*np.sin(angles),color=COLORS[name],lw=3,label=name+' drive window') for q,marker in [(w[0],'o'),(w[1],'s')]:ax.plot(rr*np.cos((q-.5)*2*np.pi),rr*np.sin((q-.5)*2*np.pi),marker,color=COLORS[name],ms=5) angles=np.linspace(.9375*np.pi,np.pi,30);ax.fill(np.r_[0,1.25*np.cos(angles),0],np.r_[0,1.25*np.sin(angles),0],color='#944a35',alpha=.17) ax.plot(d['oscillator'][:,0],d['oscillator'][:,1],color='#20303a',lw=.7,label='recorded state') for x,y,s in [(-1.36,0,'0° / 360°'),(0,-1.38,'90°'),(1.31,0,'180°'),(0,1.36,'270°')]:ax.text(x,y,s,ha='center',va='center',fontsize=8) ax.annotate('',xy=(-.82,-.55),xytext=(-.96,-.2),arrowprops={'arrowstyle':'->','color':'#53636c'}) ax.set(xlim=(-1.75,1.6),ylim=(-1.55,1.55),xlabel='$x_0$',ylabel='$x_1$',aspect='equal');ax.set_title('A One decoded oscillator cycle',loc='left',fontsize=11) ax.legend(loc='upper center',bbox_to_anchor=(.5,-.18),fontsize=8,frameon=False) ax=axs[1];ax.plot(t,d['oscillator'][:,0],label='$x_0$',color='#245b78');ax.plot(t,d['oscillator'][:,1],label='$x_1$',color='#ac572b');ax.plot(t,np.linalg.norm(d['oscillator'],axis=1),label='radius',color='#53636c',lw=.8) ax.axvspan(.15,.20,color='#805c9a',alpha=.15,label='start input');ax.set(xlabel='Time (s)',ylabel='Decoded value',xlim=(0,1.6));ax.set_title('B Start, oscillation and decay',loc='left',fontsize=11);ax.legend(frameon=False,fontsize=8,ncol=2) fig.tight_layout();fig.savefig(OUT/'cycle.pdf',bbox_inches='tight');fig.savefig(OUT/'cycle.png',dpi=150,bbox_inches='tight');plt.close(fig) fig,axs=plt.subplots(3,1,figsize=(10,6.8),sharex=True) axs[0].plot(t,d['kick'],color='#805c9a',lw=1.4);axs[0].set_ylabel('Start input');axs[0].set_title('A One externally supplied start impulse',loc='left',fontsize=11) for name in WINDOWS: color=COLORS[name];axs[1].plot(t,d[name+'_pulse'][:,0],color=color,label=name+' phase drive');axs[2].plot(t,d[name+'_ramp'][:,0],color=color,label=name+' activation') for kind,ls in [('start','--'),('end',':')]: x=report['observations'][name]['phase_crossings_s'][kind] for ax in axs[1:]:ax.axvline(x,color=color,ls=ls,lw=.8,alpha=.65) axs[1].set_title('B Neural phase-drive populations',loc='left',fontsize=11);axs[2].set_title('C Separate recurrent gesture activations',loc='left',fontsize=11) for ax in axs[1:]:ax.set_ylabel('Decoded value');ax.legend(frameon=False,loc='upper right');ax.set_ylim(-.1,1.2) axs[2].set_xlabel('Time (s)');axs[2].set_xlim(0,1.6);fig.tight_layout();fig.savefig(OUT/'drives-ramps.pdf',bbox_inches='tight');fig.savefig(OUT/'drives-ramps.png',dpi=150,bbox_inches='tight');plt.close(fig) fig,axs=plt.subplots(5,1,figsize=(10,7.0),sharex=True) for ax,key,label in zip(axs,['oscillator','lip_pulse','lip_ramp','vowel_pulse','vowel_ramp'],['Oscillator','Lip phase drive','Lip activation','Vowel phase drive','Vowel activation']): sp=d[key+'_spikes'][:,:20];color='#53636c' if key=='oscillator' else COLORS[key.split('_')[0]] for n in range(20):ax.vlines(t[sp[:,n]>0],n+.1,n+.9,color=color,lw=.4) ax.set_title(label+' · first 20 cells',loc='left',fontsize=10);ax.set(yticks=[0,19],yticklabels=['1','20'],ylim=(-1,21),ylabel='Cell') axs[-1].set(xlabel='Time (s)',xlim=(0,1.6));fig.tight_layout(h_pad=.8);fig.savefig(OUT/'spikes.pdf',bbox_inches='tight');fig.savefig(OUT/'spikes.png',dpi=150,bbox_inches='tight');plt.close(fig) fig,axs=plt.subplots(2,1,figsize=(10,4.7),sharex=True) for ax,name in zip(axs,WINDOWS): phase=d['fit_phase'];w=WINDOWS[name];target=np.where((phase>=w[0])&(phase