"""Example 09. Run with Nengo 4.1.0 and NumPy 2.5.4 to regenerate the recordings.""" from itertools import combinations_with_replacement from pathlib import Path import json import nengo import numpy as np DT = .001 SAMPLE = .005 SEED = 49 ACTIONS = ("kind", "colour", "finish") class Trial: """Environment, exact feature comparison, utility readout and cue receiver.""" def reset(self, masks): # Bit 1 = same kind as target; bit 2 = same colour. Slot 0 is the target. self.matches = np.array([[bool(mask & bit) for mask in (3, *masks)] for bit in (1, 2)]) self.present = np.ones(4, dtype=bool) self.delivery = np.zeros(3) self.pending = None self.remove = np.zeros(4, dtype=bool) self.ended = False self.events = [] def update(self, t, x): # Hysteresis reads out the four recurrent cortical populations. self.present[x[:4] > .35] = True self.present[x[:4] < -.35] = False counts = np.count_nonzero(self.present & ~self.matches, axis=1) # Common offset and scale keep the BG in its operating range. # Exact, informative ties receive a small fixed preference for kind. drives = .35 + .30 * counts.astype(float) if counts[0] == counts[1] and counts[0] > 0: drives[0] += .18 utilities = np.r_[drives, 1.15 if not counts.any() else .25] write = np.zeros(4) if t < .060: write[:] = 1.1 # the single, common scene-loading pulse elif self.pending is not None: # Sustain the erase command until the cortical readout confirms it. write[self.remove] = -1.5 if not np.any(self.present & self.remove): self.events.append(dict(t=round(t, 3), event="memory", action=self.pending, alive=self.present.tolist())) self.pending = None self.remove[:] = False elif not self.ended: # A cue arrives only when its thalamic channel drives the receiver. # The receiver needs sustained exclusive drive, not a scheduled cue time. active = x[4:] > .60 if np.count_nonzero(active) != 1: active[:] = False self.delivery += (active.astype(float) - self.delivery) * DT / .040 for channel in np.flatnonzero(self.delivery > .83): channel = int(channel) self.delivery[:] = 0 self.events.append(dict(t=round(t, 3), event="received", action=channel, alive=self.present.tolist())) if channel == 2: self.ended = True else: self.pending = channel self.remove = self.present & ~self.matches[channel] return np.r_[write, utilities, self.present.astype(float)] def build(trial): with nengo.Network(seed=SEED, label="Describe the target") as model: controller = nengo.Node(trial.update, size_in=7, size_out=11) memory = [] for slot in range(4): pop = nengo.Ensemble(160, 1, radius=1.2, label=f"Candidate slot {slot}") nengo.Connection(pop, pop, function=lambda x: .82*np.tanh(3*x), synapse=.025) nengo.Connection(controller[slot], pop, synapse=.005) nengo.Connection(pop, controller[slot], synapse=.012) memory.append(nengo.Probe(pop, synapse=.012, sample_every=SAMPLE)) bg = nengo.networks.BasalGanglia(3, n_neurons_per_ensemble=100) th = nengo.networks.Thalamus(3, n_neurons_per_ensemble=90) nengo.Connection(controller[4:7], bg.input, synapse=.008) nengo.Connection(bg.output, th.input, synapse=.008) nengo.Connection(th.output, controller[4:], synapse=.012) probes = [nengo.Probe(p, synapse=.012, sample_every=SAMPLE) for p in (bg.input, bg.output, th.output)] mask_probe = nengo.Probe(controller[7:11], sample_every=SAMPLE) return model, memory, probes, mask_probe def verify(masks, events): alive = np.ones(4, dtype=bool) matches = np.array([[bool(v & b) for v in (3,*masks)] for b in (1,2)]) sent = [e["action"] for e in events if e["event"] == "received"] assert sent and sent[-1] == 2, (masks, events) for ch in sent: gain = np.sum(alive & ~matches, axis=1) if ch == 2: assert max(gain) == 0 else: assert gain[ch] == max(gain) and gain[ch] > 0, (masks,events,gain) if gain[0] == gain[1]: assert ch == 0 alive &= matches[ch] updates = [e for e in events if e["event"] == "memory"] assert len(updates) == len(sent)-1 and alive.tolist() == events[-1]["alive"] for e in updates: assert e["alive"][0] return sent def main(): trial = Trial() trial.reset((0, 1, 2)) model, memory, probes, mask_probe = build(trial) result = dict(dt=DT, sample=SAMPLE, seed=SEED, neurons=sum(e.n_neurons for e in model.all_ensembles), cases={}) with nengo.Simulator(model, dt=DT, progress_bar=False) as sim: for masks in combinations_with_replacement(range(4), 3): sim.reset(seed=SEED) trial.reset(masks) for _ in range(35): sim.run_steps(40) if trial.ended: sim.run_steps(30) break order = verify(masks, trial.events) signals = np.column_stack([sim.data[p] for p in memory+probes]) result["cases"]["".join(map(str,masks))] = dict( events=trial.events, alive=(sim.data[mask_probe].astype(int) @ [1,2,4,8]).tolist(), samples=np.round(signals, 3).tolist()) print(masks, order, round(sim.time,3), flush=True) out = Path(__file__).with_name("description-recordings.json") out.write_text(json.dumps(result, separators=(",", ":"))) if __name__ == "__main__": main()