"""Isolated teaching example: BG/thalamus select NAME, REPEAT or WAIT. Supplied cues and supplied word identities; neither lexical retrieval nor articulation is simulated. No learning. --figures-only redraws retained data. """ from pathlib import Path import hashlib import json import sys import warnings import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import nengo import nengo_spa as spa import numpy as np HERE = Path(__file__).resolve().parent OUT = HERE / "figures" COLORS = ["#245b78", "#ac572b", "#805c9a"] plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 9, "axes.spines.top": False, "axes.spines.right": False, "pdf.fonttype": 42, "legend.fontsize": 8}) def task(t): return "NAME" if t < .7 or t >= 2.1 else ("REPEAT" if t < 1.4 else "IDLE") def run(): control_vocab = spa.Vocabulary(32, pointer_gen=np.random.RandomState(251)) control_vocab.populate("NAME; REPEAT; IDLE") word_vocab = spa.Vocabulary(32, pointer_gen=np.random.RandomState(252)) word_vocab.populate("TASSE; KANNE") with spa.Network(seed=250, label="Task-dependent word routing") as model: model.config[spa.State].neurons_per_dimension = 30 model.config[spa.State].feedback = 0 control = spa.State(vocab=control_vocab, label="Task cue") lexical = spa.State(vocab=word_vocab, label="Naming path") heard = spa.State(vocab=word_vocab, label="Repetition path") candidate = spa.State(vocab=word_vocab, label="Candidate") spa.Transcode(task, output_vocab=control_vocab) >> control spa.Transcode("TASSE", output_vocab=word_vocab) >> lexical spa.Transcode("KANNE", output_vocab=word_vocab) >> heard # BEGIN PRINTED CORE with spa.ActionSelection() as actions: spa.ifmax("name", spa.dot(control, spa.sym.NAME), lexical >> candidate) spa.ifmax("repeat", spa.dot(control, spa.sym.REPEAT), heard >> candidate) spa.ifmax("wait", 0.5) # END PRINTED CORE probes = { "utilities": nengo.Probe(actions.bg.input, synapse=.01), "bg_output": nengo.Probe(actions.bg.output, synapse=.01), "thal_output": nengo.Probe(actions.thalamus.output, synapse=.01), "candidate": nengo.Probe(candidate.output, synapse=.01), "lexical": nengo.Probe(lexical.output, synapse=.01), "heard": nengo.Probe(heard.output, synapse=.01), } for i in range(3): probes[f"gpi_spikes_{i}"] = nengo.Probe(actions.bg.gpi.ensembles[i].neurons) probes[f"thal_spikes_{i}"] = nengo.Probe(actions.thalamus.actions.ensembles[i].neurons) for i in range(2): probes[f"gate_{i}"] = nengo.Probe(actions.thalamus.gates[i], synapse=.01) probes[f"gate_spikes_{i}"] = nengo.Probe(actions.thalamus.gates[i].neurons) ch = actions.thalamus.channels[i] for j, ens in enumerate(ch.state_ensembles.ensembles): probes[f"channel_{i}_{j}_spikes"] = nengo.Probe(ens.neurons) n_neurons = sum(e.n_neurons for e in model.all_ensembles) with nengo.Simulator(model, dt=.001, progress_bar=False) as sim: sim.run(2.8, progress_bar=False) data = {k: sim.data[p].copy() for k, p in probes.items()} data["time"] = sim.trange() data["word_vectors"] = np.stack([word_vocab[x].v for x in ["TASSE", "KANNE"]]) for name in ["candidate", "lexical", "heard"]: data[name+"_similarity"] = data[name] @ data["word_vectors"].T np.savez_compressed(OUT / "action-selection-data.npz", **data) summaries = [] for a,b,winner in [(.35,.6,0),(1.05,1.3,1),(1.75,2.,2),(2.45,2.7,0)]: mask = (data["time"] >= a) & (data["time"] < b) s = {"window_s":[a,b], "expected_action":winner} for key in ["utilities", "bg_output", "thal_output", "candidate_similarity", "lexical_similarity", "heard_similarity"]: s[key] = data[key][mask].mean(axis=0).tolist() s["gate_means"] = [float(data[f"gate_{i}"][mask].mean()) for i in range(2)] summaries.append(s) report = {"nengo":nengo.__version__, "nengo_spa":spa.__version__, "seed":250, "vocab_seeds":[251,252], "dimensions":32,"neurons":n_neurons, "dt_s":.001,"duration_s":2.8, "state_neurons_per_dimension":30, "state_feedback":0,"probe_filter_s":.01,"windows":summaries, "pointer_dot_product":float(data["word_vectors"][0] @ data["word_vectors"][1]), "scope":"Supplied task cues and two supplied phonological identities; no lexical retrieval, articulation, working-memory holding, or learning.", "solver_note":"SciPy absent: installed BG implementation uses global default LstsqL2 decoder solver; no claim of neuron-by-neuron sign constraints.", "script_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "data_sha256":hashlib.sha256((OUT/"action-selection-data.npz").read_bytes()).hexdigest()} (OUT/"action-selection-observations.json").write_text(json.dumps(report,indent=2)+"\n") # Prespecified qualitative checks of routing, not a performance study. for s in summaries: w=s["expected_action"] assert np.argmax(s["thal_output"]) == w, s assert s["lexical_similarity"][0] > .7 and s["heard_similarity"][1] > .7, s if w < 2: assert s["candidate_similarity"][w] > .65, s assert s["candidate_similarity"][w] - s["candidate_similarity"][1-w] > .5, s assert s["gate_means"][w] < .15 and s["gate_means"][1-w] > .65, s else: assert max(abs(v) for v in s["candidate_similarity"]) < .15, s assert min(s["gate_means"]) > .65, s report["checks_passed"] = ["Expected action dominates each settled window", "Both source identities remain active", "Selected route carries its identity", "Unselected route gates are active", "Wait suppresses both routes"] (OUT/"action-selection-observations.json").write_text(json.dumps(report,indent=2)+"\n") print(json.dumps({"neurons":n_neurons,"windows":summaries,"checks_passed":report["checks_passed"]},indent=2)) def plot(): d = np.load(OUT/"action-selection-data.npz") t = d["time"] fig, ax = plt.subplots(6,1,figsize=(9.0,8.4),sharex=True, gridspec_kw={"height_ratios":[1,1,1,.9,.9,1.15]}) labels = ["name", "repeat", "wait"] for row,key in enumerate(["utilities", "bg_output", "thal_output"]): for i in range(3): ax[row].plot(t,d[key][:,i],color=COLORS[i],lw=.85,label=labels[i]) ax[row].legend(loc="upper right",ncol=3,frameon=False) ax[0].set_title("A Utilities arriving at the selection circuit",loc="left",fontsize=10) ax[1].set_title("B Decoded basal-ganglia output: selected channel approaches zero",loc="left",fontsize=10) ax[2].set_title("C Thalamic action activity: selected channel rises",loc="left",fontsize=10) ax[0].set_ylabel("Utility");ax[1].set_ylabel("Output");ax[2].set_ylabel("Activity") # Consecutive cells, chosen independently of observed spike rates. for i in range(2): spikes=d[f"gate_spikes_{i}"][:,:12] for n in range(12): ax[3].vlines(t[spikes[:,n]>0],i*14+n+.1,i*14+n+.9,color=COLORS[i],lw=.35) spikes=d[f"channel_{i}_0_spikes"][:,:12] for n in range(12): ax[4].vlines(t[spikes[:,n]>0],i*14+n+.1,i*14+n+.9,color=COLORS[i],lw=.35) for r in [3,4]: ax[r].set_yticks([6,20],["name", "repeat"]);ax[r].set_ylim(-1,27) ax[3].set_title("D Blocking-gate spikes (12 cells per gate): active gate closes its route",loc="left",fontsize=10) ax[4].set_title("E Content-channel spikes (12 cells from each first subensemble)",loc="left",fontsize=10) for i,lab in enumerate(["TASSE", "KANNE"]): ax[5].plot(t,d["candidate_similarity"][:,i],color=COLORS[i],lw=.9,label=lab) ax[5].set_title("F Candidate content decoded after neural routing",loc="left",fontsize=10) ax[5].set_ylabel("Dot product");ax[5].set_xlabel("Time (s)");ax[5].legend(loc="upper right",ncol=2,frameon=False) for a in ax: for x in [.7,1.4,2.1]:a.axvline(x,color="#888888",lw=.6,ls="--") a.axvspan(1.4,2.1,color=COLORS[2],alpha=.05) a.set_xlim(0,2.8) for x,lab in [(.35,"NAME cue"),(1.05,"REPEAT cue"),(1.75,"IDLE cue"),(2.45,"NAME cue")]: ax[0].text(x,1.03,lab,transform=ax[0].get_xaxis_transform(),ha="center",fontsize=8) fig.tight_layout(h_pad=.75) fig.savefig(OUT/"action-selection.pdf",bbox_inches="tight") fig.savefig(OUT/"action-selection.png",dpi=160,bbox_inches="tight") plt.close(fig) if __name__ == "__main__": OUT.mkdir(exist_ok=True) if "--figures-only" not in sys.argv:run() plot()