def test_build_node_function_of_time(self, period): """Test that building a function of time Node creates a new operator. """ with nengo.Network() as net: a = nengo.Node(lambda t: [t, t**2], size_in=0) # Mark the Node as a function of time add_spinnaker_params(net.config) net.config[a].function_of_time = True if period is not None: net.config[a].function_of_time_period = period # Create the model model = Model() model.config = net.config # Build the Node nioc = NodeIOController() nioc.build_node(model, a) # Assert that this added a new operator to the model assert model.object_operators[a].function is a.output if period is not None: assert model.object_operators[a].period == period else: assert model.object_operators[a].period is None assert model.extra_operators == list()
def test_probe_ensemble_spikes(): with nengo.Network("Test Network") as network: a = nengo.Node(lambda t: -1.0 if t > 1.0 else 1.0) # Create a 2 neuron ensemble with opposing encoders b = nengo.Ensemble(2, 1) b.encoders = [[-1.0], [1.0]] b.max_rates = [100, 100] b.intercepts = [0.1, -0.1] nengo.Connection(a, b, synapse=None) # Probe the spikes p_n0 = nengo.Probe(b.neurons[0]) p_n1 = nengo.Probe(b.neurons[1], sample_every=0.002) p_spikes = nengo.Probe(b.neurons) # Mark the input Node as a function of time nengo_spinnaker.add_spinnaker_params(network.config) network.config[a].function_of_time = True # Create the simulator and run for 2 s sim = nengo_spinnaker.Simulator(network) with sim: sim.run(2.0) # Check that the neurons spiked as expected assert not np.any(sim.data[p_n0][:1.0/sim.dt]) # Neuron 0 assert np.any(sim.data[p_n1][:1.0/p_n1.sample_every]) # Neuron 1 assert np.any(sim.data[p_n0][1.0/sim.dt:]) assert not np.any(sim.data[p_n1][1.0/p_n1.sample_every:])
def test_build_node_function_of_time_off(self, recwarn): """Test that building a function of time Node is exactly the same as building a regular Node if function of time Nodes are disabled (but that a warning is raised). """ with nengo.Network() as net: a = nengo.Node(lambda t: t, size_in=0, size_out=1, label="Stim") # Mark the Node as a function of time add_spinnaker_params(net.config) net.config[a].function_of_time = True # Create the model model = Model() model.config = net.config # Build the Node nioc = NodeIOController(function_of_time_nodes=False) nioc.build_node(model, a) # Assert that no new operators were created assert model.object_operators == dict() assert model.extra_operators == list() # This should have raised a warning w = recwarn.pop() assert "disabled" in str(w.message) assert "Stim" in str(w.message)
def test_probe_ensemble_spikes(): with nengo.Network("Test Network") as network: a = nengo.Node(lambda t: -1.0 if t > 1.0 else 1.0) # Create a 2 neuron ensemble with opposing encoders b = nengo.Ensemble(2, 1) b.encoders = [[-1.0], [1.0]] b.max_rates = [100, 100] b.intercepts = [0.1, -0.1] nengo.Connection(a, b, synapse=None) # Probe the spikes p_n0 = nengo.Probe(b.neurons[0]) p_n1 = nengo.Probe(b.neurons[1], sample_every=0.002) p_spikes = nengo.Probe(b.neurons) # Mark the input Node as a function of time nengo_spinnaker.add_spinnaker_params(network.config) network.config[a].function_of_time = True # Create the simulator and run for 2 s sim = nengo_spinnaker.Simulator(network) with sim: sim.run(2.0) # Check that the neurons spiked as expected assert not np.any(sim.data[p_n0][:1.0 / sim.dt]) # Neuron 0 assert np.any(sim.data[p_n1][:1.0 / p_n1.sample_every]) # Neuron 1 assert np.any(sim.data[p_n0][1.0 / sim.dt:]) assert not np.any(sim.data[p_n1][1.0 / p_n1.sample_every:])
def test_white_signal(): model = nengo.Network() with model: # Create communication channel pre = nengo.Ensemble(60, dimensions=2) post = nengo.Ensemble(60, dimensions=2) nengo.Connection(pre, post) inp = nengo.Node(WhiteSignal(60, high=5), size_out=2) nengo.Connection(inp, pre) # Probe signal and ensemble at end of channel inp_p = nengo.Probe(pre, synapse=0.01) post_p = nengo.Probe(post, synapse=0.01) nengo_spinnaker.add_spinnaker_params(model.config) model.config[inp].function_of_time = True sim = nengo_spinnaker.Simulator(model) with sim: sim.run(2.0) # Read data in_data = sim.data[inp_p] post_data = sim.data[post_p] # Calculate RMSD error = np.power(in_data - post_data, 2.0) # Assert it's less than arbitrary limit assert math.sqrt(np.mean(error)) < 0.1
def test_time_scaling(timescale, f_of_t): """Test that for various time-scales the model results in the same behaviour but takes different times to compute. """ # Create a model to test with nengo.Network() as model: inp = nengo.Node(lambda t: -0.75 if t < 1.0 else .25) ens = nengo.Ensemble(100, 1) nengo.Connection(inp, ens) p = nengo.Probe(ens, synapse=0.01) # Mark function of time Node if necessary if f_of_t: nengo_spinnaker.add_spinnaker_params(model.config) model.config[inp].function_of_time = True # Perform the simulation runtime = 2.0 sim = nengo_spinnaker.Simulator(model, timescale=timescale) with sim: start = time.time() sim.run(runtime) duration = time.time() - start # Assert that the output is reasonable assert np.allclose(sim.data[p][100:900], -0.75, atol=1e-1) assert np.allclose(sim.data[p][1500:1900], +0.25, atol=1e-1) # Assert that the simulation took a reasonable amount of time assert 0.8 <= (timescale * duration) / runtime <= 1.2
def test_get_node_source_f_of_t(self): """Test that calling the NodeIOController for a f_of_t->xx connection doesn't ask for a SpiNNaker sorce and instead returns the value source that was associated with the Node. """ with nengo.Network() as net: a = nengo.Node(lambda t: t) b = nengo.Ensemble(100, 1) a_b = nengo.Connection(a, b) # Mark the Node as being a function of time add_spinnaker_params(net.config) net.config[a].function_of_time = True # Create a model and build the Node model = Model() model.config = net.config nioc = NodeIOController() nioc.build_node(model, a) # Get the source and ensure that the appropriate object is returned with mock.patch.object(nioc, "get_spinnaker_source_for_node") as gssfn: spec = nioc.get_node_source(model, a_b) assert spec.target.obj is model.object_operators[a] assert spec.target.port is OutputPort.standard # Assert this _didn't_ call `get_spinnaker_source_for_node` assert not gssfn.called # There should be nothing in the host network assert nioc.host_network.all_nodes == list() assert nioc.host_network.all_connections == list()
def test_add_spinnaker_params(): """Test adding SpiNNaker specific parameters to a configuration object.""" # Create a network with nengo.Network() as net: n_ft = nengo.Node(lambda t: [t, t**2]) ptn = nengo.Node(size_in=2) # Setting SpiNNaker-specific options before calling `add_spinnaker_params` # should fail. for param, value in [ ("function_of_time", True), ("function_of_time_period", 0.5), ]: with pytest.raises(AttributeError) as excinfo: setattr(net.config[n_ft], param, value) assert param in str(excinfo.value) for param, value in [ ("n_cores_per_chip", 16), ("n_chips", 4), ("optimize_out", False), ]: with pytest.raises(AttributeError) as excinfo: setattr(net.config[ptn], param, value) for param, value in [ ("placer", lambda r, n, m, c: None), ("placer_kwargs", {}), ("allocater", lambda r, n, m, c, p: None), ("allocater_kwargs", {}), ("router", lambda r, n, m, c, p, a: None), ("router_kwargs", {}), ("node_io", None), ("node_io_kwargs", {}), ]: with pytest.raises(KeyError) as excinfo: setattr(net.config[Simulator], param, value) assert "Simulator" in str(excinfo.value) # Adding the SpiNNaker parameters should allow all of these to pass add_spinnaker_params(net.config) assert net.config[nengo.Node].function_of_time is False assert net.config[nengo.Node].function_of_time_period is None assert net.config[nengo.Node].optimize_out is None assert net.config[nengo.Node].n_cores_per_chip is None assert net.config[nengo.Node].n_chips is None assert net.config[Simulator].placer is par.place assert net.config[Simulator].placer_kwargs == {} assert net.config[Simulator].allocater is par.allocate assert net.config[Simulator].allocater_kwargs == {} assert net.config[Simulator].router is par.route assert net.config[Simulator].router_kwargs == {} assert net.config[Simulator].node_io is node_io.Ethernet assert net.config[Simulator].node_io_kwargs == {}
def model(self, p): model = spa.SPA() with model: model.vision = spa.Buffer(dimensions=p.D) model.phrase = spa.Buffer(dimensions=p.D) model.motor = spa.Buffer(dimensions=p.D) model.noun = spa.Memory(dimensions=p.D, synapse=0.1) model.verb = spa.Memory(dimensions=p.D, synapse=0.1) model.bg = spa.BasalGanglia( spa.Actions( 'dot(vision, WRITE) --> verb=vision', 'dot(vision, ONE+TWO+THREE) --> noun=vision', '0.5*(dot(vision, NONE-WRITE-ONE-TWO-THREE) + ' 'dot(phrase, WRITE*VERB))' '--> motor=phrase*~NOUN', )) model.thal = spa.Thalamus(model.bg) model.cortical = spa.Cortical( spa.Actions( 'phrase=noun*NOUN', 'phrase=verb*VERB', )) def vision_input(t): index = int(t / p.time_per_word) % 3 return ['WRITE', 'ONE', 'NONE'][index] model.input = spa.Input(vision=vision_input) self.motor_vocab = model.get_output_vocab('motor') self.p_thal = nengo.Probe(model.thal.actions.output, synapse=0.03) self.p_motor = nengo.Probe(model.motor.state.output, synapse=0.03) split.split_input_nodes(model, max_dim=64) self.replaced = split.split_passthrough(model, max_dim=p.split_max_dim) if p.pass_ensembles > 0: split.pass_ensembles(model, max_dim=p.pass_ensembles) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if node.output is None: if node.size_in > p.pf_max_dim: print 'limiting', node model.config[node].n_cores_per_chip = p.pf_cores model.config[node].n_chips = p.pf_n_chips model.config[nengo_spinnaker.Simulator].placer_kwargs = dict( effort=0.1) if p.fixed_seed: for ens in model.all_ensembles: ens.seed = 1 return model
def run_experiment(model, spinnaker, n_symbols, time_per_symbol): """Run the experiment and return the results in a dictionary.""" # Add a probe for the output of the network with model: p_out = nengo.Probe(model.out.output, synapse=0.03) # Create the simulator if not spinnaker: sim = nengo.Simulator(model) else: # Configure all the Nodes as function of time Nodes nengo_spinnaker.add_spinnaker_params(model.config) for n in model.all_nodes: if n.output is not None: model.config[n].function_of_time = True sim = nengo_spinnaker.Simulator(model, use_spalloc=True) # Get the current number of dropped packets dropped = sum( sim.controller.get_router_diagnostics(x, y).dropped_multicast for (x, y) in sim.controller.get_machine() ) # Run the simulation sim.run(2*(n_symbols + 1)*time_per_symbol) # Prepare the results for later analysis results = dict() vocab = model.get_output_vocab("out") mem_out = np.array(sim.data[p_out]) # Get an ordered representation of the keys m_vocab = np.zeros((n_symbols*2, vocab.dimensions)) for n in range(n_symbols): m_vocab[n] = vocab["K{}".format(n)].v m_vocab[n + n_symbols] = vocab["V{}".format(n)].v results["output"] = np.dot(m_vocab, mem_out.T).T results["times"] = sim.trange() # Tidy up SpiNNaker and get the count of dropped packets if spinnaker: # Count the number of packets dropped during the simulation results["dropped_multicast"] = sum( sim.controller.get_router_diagnostics(x, y).dropped_multicast for (x, y) in sim.controller.get_machine() ) - dropped print("> Dropped %d" % results["dropped_multicast"]) sim.close() return results
def model(self, p): model = spa.SPA() with model: model.vision = spa.Buffer(dimensions=p.D) model.phrase = spa.Buffer(dimensions=p.D) model.motor = spa.Buffer(dimensions=p.D) model.noun = spa.Memory(dimensions=p.D, synapse=0.1) model.verb = spa.Memory(dimensions=p.D, synapse=0.1) model.bg = spa.BasalGanglia(spa.Actions( 'dot(vision, WRITE) --> verb=vision', 'dot(vision, ONE+TWO+THREE) --> noun=vision', '0.5*(dot(vision, NONE-WRITE-ONE-TWO-THREE) + ' 'dot(phrase, WRITE*VERB))' '--> motor=phrase*~NOUN', )) model.thal = spa.Thalamus(model.bg) model.cortical = spa.Cortical(spa.Actions( 'phrase=noun*NOUN', 'phrase=verb*VERB', )) def vision_input(t): index = int(t / p.time_per_word) % 3 return ['WRITE', 'ONE', 'NONE'][index] model.input = spa.Input(vision=vision_input) self.motor_vocab = model.get_output_vocab('motor') self.p_thal = nengo.Probe(model.thal.actions.output, synapse=0.03) self.p_motor = nengo.Probe(model.motor.state.output, synapse=0.03) split.split_input_nodes(model, max_dim=64) self.replaced = split.split_passthrough(model, max_dim=p.split_max_dim) if p.pass_ensembles > 0: split.pass_ensembles(model, max_dim=p.pass_ensembles) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if node.output is None: if node.size_in > p.pf_max_dim: print 'limiting', node model.config[node].n_cores_per_chip = p.pf_cores model.config[node].n_chips = p.pf_n_chips model.config[ nengo_spinnaker.Simulator].placer_kwargs = dict(effort=0.1) if p.fixed_seed: for ens in model.all_ensembles: ens.seed = 1 return model
def model(self, p): model = spa.SPA() with model: model.word = spa.State(dimensions=p.D) model.marker = spa.State(dimensions=p.D) model.memory = spa.State(dimensions=p.D, feedback=1) model.cortical = spa.Cortical(spa.Actions( 'memory = word * marker', )) def word(t): index = t / p.time_per_symbol if index < p.n_symbols: return 'S%d' % index return '0' def marker(t): index = t / p.time_per_symbol if index < p.n_symbols: return 'M%d' % index return '0' model.input = spa.Input(word=word, marker=marker) self.p_memory = nengo.Probe(model.memory.output, synapse=0.03) self.vocab = model.get_output_vocab('memory') split.split_input_nodes(model, max_dim=16) self.replaced = split.split_passthrough(model, max_dim=p.split_max_dim) if p.pass_ensembles > 0: split.pass_ensembles(model, max_dim=p.pass_ensembles) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if node.output is None: if node.size_in > p.pf_max_dim: print 'limiting', node model.config[node].n_cores_per_chip = p.pf_cores model.config[node].n_chips = p.pf_n_chips model.config[ nengo_spinnaker.Simulator].placer_kwargs = dict(effort=0.1) split.remove_outputless_passthrough(model) if p.fixed_seed: for ens in model.all_ensembles: ens.seed = 1 return model
def test_global_inhibition(source): with nengo.Network("Test Network") as network: # Create a 2-d ensemble representing a constant value input_value = nengo.Node([0.25, -0.3]) ens = nengo.Ensemble(200, 2) nengo.Connection(input_value, ens) p_ens = nengo.Probe(ens, synapse=0.05) # The gate should be open initially and then closed after 1s gate_control = nengo.Node(lambda t: 0.0 if t < 1.0 else 1.0) if source == "ensemble": # Create another ensemble which will act to gate `ens` gate_driver = nengo.Ensemble(100, 1) gate_driver.intercepts = [0.3] * gate_driver.n_neurons gate_driver.encoders = [[1.0]] * gate_driver.n_neurons nengo.Connection(gate_control, gate_driver) nengo.Connection(gate_driver, ens.neurons, transform=[[-10.0]] * ens.n_neurons) elif source == "node" or source == "f_of_t_node": nengo.Connection(gate_control, ens.neurons, transform=[[-10.0]] * ens.n_neurons) # Mark appropriate Nodes as functions of time if desired if source != "node": nengo_spinnaker.add_spinnaker_params(network.config) network.config[gate_control].function_of_time = True # Create the simulate and simulate sim = nengo_spinnaker.Simulator(network) # Run the simulation for long enough to ensure that the decoded value is # with +/-20% of the input value. with sim: sim.run(2.0) # Check that the values are decoded as expected index10 = int(p_ens.synapse.tau * 4 / sim.dt) index11 = 1.0 / sim.dt index20 = index11 + int(p_ens.synapse.tau * 4 / sim.dt) data = sim.data[p_ens] assert (np.all(+0.20 <= data[index10:index11, 0]) and np.all(+0.30 >= data[index10:index11, 0]) and np.all(+0.05 >= data[index20:, 0]) and np.all(-0.05 <= data[index20:, 0])) assert (np.all(-0.36 <= data[index10:index11, 1]) and np.all(-0.24 >= data[index10:index11, 1]) and np.all(+0.05 >= data[index20:, 1]) and np.all(-0.05 <= data[index20:, 1]))
def model(self, p): model = spa.SPA() with model: model.word = spa.State(dimensions=p.D) model.marker = spa.State(dimensions=p.D) model.memory = spa.State(dimensions=p.D, feedback=1) model.cortical = spa.Cortical( spa.Actions('memory = word * marker', )) def word(t): index = t / p.time_per_symbol if index < p.n_symbols: return 'S%d' % index return '0' def marker(t): index = t / p.time_per_symbol if index < p.n_symbols: return 'M%d' % index return '0' model.input = spa.Input(word=word, marker=marker) self.p_memory = nengo.Probe(model.memory.output, synapse=0.03) self.vocab = model.get_output_vocab('memory') split.split_input_nodes(model, max_dim=16) self.replaced = split.split_passthrough(model, max_dim=p.split_max_dim) if p.pass_ensembles > 0: split.pass_ensembles(model, max_dim=p.pass_ensembles) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if node.output is None: if node.size_in > p.pf_max_dim: print 'limiting', node model.config[node].n_cores_per_chip = p.pf_cores model.config[node].n_chips = p.pf_n_chips model.config[nengo_spinnaker.Simulator].placer_kwargs = dict( effort=0.1) split.remove_outputless_passthrough(model) if p.fixed_seed: for ens in model.all_ensembles: ens.seed = 1 return model
def run_experiment(model, spinnaker): """Run the experiment and return the results in a dictionary.""" # Add probes for the output of the network with model: p_c = nengo.Probe(model.c.output, synapse=0.01) # Create the simulator if not spinnaker: sim = nengo.Simulator(model) else: # Configure all the Nodes as function of time Nodes nengo_spinnaker.add_spinnaker_params(model.config) for n in model.all_nodes: if n.output is not None: model.config[n].function_of_time = True sim = nengo_spinnaker.Simulator(model, use_spalloc=True) # Get the current number of dropped packets dropped = sum( sim.controller.get_router_diagnostics(x, y).dropped_multicast for (x, y) in sim.controller.get_machine() ) # Run the simulation sim.run(0.5) # Get the vocabulary vocab = model.get_output_vocab("c") AB = vocab.parse("A * B").v # Prepare the results for later analysis, recording the magnitude of the # error vector results = dict() results["output"] = np.sqrt(np.sum(np.square(AB - sim.data[p_c]), axis=1)) results["times"] = sim.trange() # Tidy up SpiNNaker and get the count of dropped packets if spinnaker: # Count the number of packets dropped during the simulation results["dropped_multicast"] = sum( sim.controller.get_router_diagnostics(x, y).dropped_multicast for (x, y) in sim.controller.get_machine() ) - dropped sim.close() return results
def run_test(nengo_network, nodes_as_function_of_time, nodes_as_function_of_time_time_period): # build via gfe nengo_spinnaker_gfe spinnaker seed = 11111 timer_period = 10 app_graph_builder = NengoApplicationGraphBuilder() (app_graph, host_network, nengo_to_app_graph_map, random_number_generator) = app_graph_builder( nengo_network=nengo_network, machine_time_step=1.0, nengo_random_number_generator_seed=seed, decoder_cache=NoDecoderCache(), utilise_extra_core_for_probes=True, nengo_nodes_as_function_of_time=nodes_as_function_of_time, function_of_time_nodes_time_period=( nodes_as_function_of_time_time_period)) interposer_installer = NengoUtiliseInterposers() app_graph = interposer_installer( app_graph, nengo_to_app_graph_map, random_number_generator, seed) machine_graph, graph_mapper = NengoPartitioner(app_graph) # build via nengo_spinnaker_gfe - spinnaker nengo_spinnaker.add_spinnaker_params(nengo_network.config) for nengo_node in nodes_as_function_of_time: nengo_network.config[nengo_node].function_of_time = True for nengo_node in nodes_as_function_of_time_time_period: nengo_network.config[nengo_node].function_of_time_period = \ nodes_as_function_of_time_time_period[nengo_node] io_controller = Ethernet() builder_kwargs = io_controller.builder_kwargs nengo_spinnaker_network_builder = Model() nengo_spinnaker_network_builder.build(nengo_network, **builder_kwargs) nengo_spinnaker_network_builder.add_interposers() nengo_spinnaker_network_builder.make_netlist(timer_period) nengo_operators = dict() nengo_operators.update( nengo_spinnaker_network_builder.object_operators) nengo_operators.update(io_controller._sdp_receivers) nengo_operators.update(io_controller._sdp_transmitters) match = compare_against_the_nengo_spinnaker_and_gfe_impls( nengo_operators, nengo_to_app_graph_map, nengo_spinnaker_network_builder.connection_map, app_graph, nengo_spinnaker_network_builder) if not match: raise Exception("didnt match")
def test_global_inhibition_from_optimised_out_passthrough_node(): with nengo.Network("Test Network") as network: # Create a 2-d ensemble representing a constant value input_value = nengo.Node([0.25, -0.3]) ens = nengo.Ensemble(200, 2) nengo.Connection(input_value, ens) p_ens = nengo.Probe(ens, synapse=0.05) # The gate should be open initially and then closed after 1s gate_control = nengo.Node(lambda t: 0.0 if t < 1.0 else 1.0) # Add the passthrough Node gate_ptn = nengo.Node(size_in=ens.n_neurons) nengo.Connection(gate_ptn, ens.neurons) # Create the control and nengo.Connection(gate_control, gate_ptn, transform=[[-10.0]] * ens.n_neurons) # Mark appropriate Nodes as functions of time nengo_spinnaker.add_spinnaker_params(network.config) network.config[gate_control].function_of_time = True # Create the simulate and simulate sim = nengo_spinnaker.Simulator(network) # Run the simulation for long enough to ensure that the decoded value is # with +/-20% of the input value. with sim: sim.run(2.0) # Check that the values are decoded as expected index10 = int(p_ens.synapse.tau * 4 / sim.dt) index11 = 1.0 / sim.dt index20 = index11 + int(p_ens.synapse.tau * 4 / sim.dt) data = sim.data[p_ens] assert (np.all(+0.20 <= data[index10:index11, 0]) and np.all(+0.30 >= data[index10:index11, 0]) and np.all(+0.05 >= data[index20:, 0]) and np.all(-0.05 <= data[index20:, 0])) assert (np.all(-0.36 <= data[index10:index11, 1]) and np.all(-0.24 >= data[index10:index11, 1]) and np.all(+0.05 >= data[index20:, 1]) and np.all(-0.05 <= data[index20:, 1]))
def test_getconfig(): # Create a network, DON'T add nengo_spinnaker configuration with nengo.Network() as net: n = nengo.Node(lambda t: [t, t+2]) # Use getconfig to get configuration options that don't exist get placer = mock.Mock() assert getconfig(net.config, Simulator, "placer", placer) is placer assert not getconfig(net.config, n, "function_of_time", False) # Now add the config add_spinnaker_params(net.config) net.config[n].function_of_time = True # Use getconfig to get configuration options from the config assert getconfig(net.config, Simulator, "placer", placer) is not placer assert getconfig(net.config, n, "function_of_time", False)
def test_function_of_time_node(): # Test that function of time can't be marked on Nodes unless they have size # in == 0 with nengo.Network() as net: not_f_of_t = nengo.Node(lambda t, x: t**2, size_in=1) f_of_t = nengo.Node(lambda t: t) # Modify the config add_spinnaker_params(net.config) net.config[f_of_t].function_of_time = True with pytest.raises(ValueError): net.config[not_f_of_t].function_of_time = True # Check the settings are valid assert not net.config[not_f_of_t].function_of_time assert net.config[f_of_t].function_of_time
def test_nodes_sliced(f_of_t): # Create a model with a single function of time node which returns a 4D # vector, apply preslicing on some connections from it and ensure that this # slicing plays nicely with the functions attached to the connections. def out_fun_1(val): assert val.size == 2 return val * 2 with nengo.Network() as model: # Create the input node and an ensemble in_node = nengo.Node(lambda t: [0.1, 1.0, 0.2, -1.0], size_out=4) in_node_2 = nengo.Node(0.25) ens = nengo.Ensemble(400, 4) ens2 = nengo.Ensemble(200, 2) # Create the connections nengo.Connection(in_node[::2], ens[[1, 3]], transform=.5, function=out_fun_1) nengo.Connection(in_node_2[[0, 0]], ens2) # Probe the ensemble to ensure that the values are correct p = nengo.Probe(ens, synapse=0.05) p2 = nengo.Probe(ens2, synapse=0.05) # Mark the input as being a function of time if desired if f_of_t: nengo_spinnaker.add_spinnaker_params(model.config) model.config[in_node].function_of_time = True # Run the simulator for 1.0 s and check that the last probed values are in # range sim = nengo_spinnaker.Simulator(model) with sim: sim.run(1.0) # Check the final values assert -0.05 < sim.data[p][-1, 0] < 0.05 assert 0.05 < sim.data[p][-1, 1] < 0.15 assert -0.05 < sim.data[p][-1, 2] < 0.05 assert 0.15 < sim.data[p][-1, 3] < 0.25 assert 0.20 < sim.data[p2][-1, 0] < 0.30 assert 0.20 < sim.data[p2][-1, 1] < 0.30
def run_experiment(model, spinnaker): """Run the experiment and return the results in a dictionary.""" # Add probes for the output of the network with model: p_actions = nengo.Probe(model.thal.actions.output, synapse=0.01) p_utility = nengo.Probe(model.bg.input, synapse=0.01) # Create the simulator if not spinnaker: sim = nengo.Simulator(model) else: # Configure all the Nodes as function of time Nodes nengo_spinnaker.add_spinnaker_params(model.config) for n in model.all_nodes: if n.output is not None: model.config[n].function_of_time = True sim = nengo_spinnaker.Simulator(model) # Get the current number of dropped packets dropped = sum( sim.controller.get_router_diagnostics(x, y).dropped_multicast for (x, y) in sim.controller.get_machine() ) # Run the simulation sim.run(0.5) # Prepare the results for later analysis results = dict() results["actions"] = sim.data[p_actions] results["utility"] = sim.data[p_utility] results["times"] = sim.trange() # Tidy up SpiNNaker and get the count of dropped packets if spinnaker: sim.close() # Count the number of packets dropped during the simulation results["dropped_multicast"] = sum( sim.controller.get_router_diagnostics(x, y).dropped_multicast for (x, y) in sim.controller.get_machine() ) - dropped return results
def test_white_signal(): model = nengo.Network() with model: inp = nengo.Node(WhiteSignal(60, high=5), size_out=2) inp_p = nengo.Probe(inp) nengo_spinnaker.add_spinnaker_params(model.config) model.config[inp].function_of_time = True sim = nengo_spinnaker.Simulator(model) with sim: sim.run(0.2) # Read data in_data = sim.data[inp_p] # Check that the input value actually changes assert np.any(in_data[5] != in_data[6:])
def model(self, p): model = spa.SPA() with model: model.vision = spa.Buffer(dimensions=p.D) model.state = spa.Memory(dimensions=p.D) actions = [ 'dot(state, S%d) --> state=S%d' % (i, (i + 1)) for i in range(p.n_actions - 1) ] actions.append('dot(state, S%d) --> state=vision' % (p.n_actions - 1)) model.bg = spa.BasalGanglia(actions=spa.Actions(*actions)) model.thal = spa.Thalamus(model.bg) model.input = spa.Input(vision='S%d' % p.start, state=lambda t: 'S%d' % p.start if t < 0.1 else '0') self.probe = nengo.Probe(model.thal.actions.output, synapse=0.03) split.split_passthrough(model, max_dim=p.split_max_dim) if p.pass_ensembles > 0: split.pass_ensembles(model, max_dim=p.pass_ensembles) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if node.output is None: if node.size_in > p.pf_max_dim: print 'limiting', node model.config[node].n_cores_per_chip = p.pf_cores model.config[node].n_chips = p.pf_n_chips model.config[nengo_spinnaker.Simulator].placer_kwargs = dict( effort=0.1) if p.fixed_seed: for ens in model.all_ensembles: ens.seed = 1 return model
def run_param_set(self, n_neurons, d, seed, trial): spaopt.optimization.SubvectorRadiusOptimizer.Simulator = \ nengo_spinnaker.Simulator rng = np.random.RandomState(seed) ctx = nengo.spa.SemanticPointer(d, rng) ctx.make_unitary() model = nengo.Network(seed=get_seed(rng)) with model: step = SignalGenerator(self.duration).make_step(0, d, .001, rng) in_a = nengo.Node(step, size_out=d) a = nengo.Node(size_in=d) b = nengo.Node(size_in=d) c = nengo.Node(size_in=d) nengo.Connection(in_a, a) nengo.Connection(a, b, synapse=None) nengo.Connection(b, c, synapse=None) old_repr = nengo.networks.EnsembleArray(n_neurons, d) nengo.Connection(in_a, old_repr.input) repr_ = spaopt.UnitEA(n_neurons, d, d) nengo.Connection(in_a, repr_.input) in_probe = nengo.Probe(c, synapse=0.005) old_probe = nengo.Probe(old_repr.output, synapse=0.005) probe = nengo.Probe(repr_.output, synapse=0.005) nengo_spinnaker.add_spinnaker_params(model.config) model.config[in_a].function_of_time = True sim = nengo_spinnaker.Simulator(model) sim.run(self.duration) sim.close() return { 't': sim.trange(), 'default': rmse(sim.data[old_probe], sim.data[in_probe], axis=1), 'optimized': rmse(sim.data[probe], sim.data[in_probe], axis=1) }
def model(self, p): model = spa.SPA() with model: model.vision = spa.Buffer(dimensions=p.D) model.state = spa.Memory(dimensions=p.D) actions = ['dot(state, S%d) --> state=S%d' % (i,(i+1)) for i in range(p.n_actions - 1)] actions.append('dot(state, S%d) --> state=vision' % (p.n_actions - 1)) model.bg = spa.BasalGanglia(actions=spa.Actions(*actions)) model.thal = spa.Thalamus(model.bg) model.input = spa.Input(vision='S%d' % p.start, state=lambda t: 'S%d' % p.start if t < 0.1 else '0') self.probe = nengo.Probe(model.thal.actions.output, synapse=0.03) split.split_passthrough(model, max_dim=p.split_max_dim) if p.pass_ensembles > 0: split.pass_ensembles(model, max_dim=p.pass_ensembles) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if node.output is None: if node.size_in > p.pf_max_dim: print 'limiting', node model.config[node].n_cores_per_chip = p.pf_cores model.config[node].n_chips = p.pf_n_chips model.config[nengo_spinnaker.Simulator].placer_kwargs = dict(effort=0.1) if p.fixed_seed: for ens in model.all_ensembles: ens.seed = 1 return model
def test_function_of_time_node(): with nengo.Network("Test Network") as network: a = nengo.Node(lambda t: 0.6 if t < 1.0 else -0.4) b = nengo.Ensemble(200, 1) p_a = nengo.Probe(a, synapse=0.05) p_b = nengo.Probe(b, synapse=0.05) c = nengo.Ensemble(200, 1) p_c = nengo.Probe(c, synapse=0.05) nengo.Connection(a, b) nengo.Connection(a, c, function=lambda x: x ** 2) # Mark `a` as a function of time Node nengo_spinnaker.add_spinnaker_params(network.config) network.config[a].function_of_time = True # Create the simulate and simulate sim = nengo_spinnaker.Simulator(network, period=1.0) # Run the simulation for long enough to ensure that the decoded value is # with +/-20% of the input value. with sim: sim.run(2.0) # Check that the values are decoded as expected index10 = int(p_b.synapse.tau * 3 / sim.dt) index11 = 1.0 / sim.dt index20 = index11 + int(p_b.synapse.tau * 3 / sim.dt) data = sim.data[p_b] assert ( np.all(+0.44 <= data[index10:index11, 0]) and np.all(+0.72 >= data[index10:index11, 0]) and np.all(-0.32 >= data[index20:, 0]) and np.all(-0.48 <= data[index20:, 0]) )
def test_function_of_time_node(): with nengo.Network("Test Network") as network: a = nengo.Node(lambda t: 0.6 if t < 1.0 else -0.4) b = nengo.Ensemble(200, 1) p_a = nengo.Probe(a, synapse=0.05) p_b = nengo.Probe(b, synapse=0.05) c = nengo.Ensemble(200, 1) p_c = nengo.Probe(c, synapse=0.05) nengo.Connection(a, b) nengo.Connection(a, c, function=lambda x: x**2) # Mark `a` as a function of time Node nengo_spinnaker.add_spinnaker_params(network.config) network.config[a].function_of_time = True # Create the simulate and simulate sim = nengo_spinnaker.Simulator(network, period=1.0) # Run the simulation for long enough to ensure that the decoded value is # with +/-20% of the input value. with sim: sim.run(2.0) # Check that the values are decoded as expected index10 = int(p_b.synapse.tau * 3 / sim.dt) index11 = 1.0 / sim.dt index20 = index11 + int(p_b.synapse.tau * 3 / sim.dt) data = sim.data[p_b] assert np.all(+0.44 <= data[index10:index11, 0]) assert np.all(+0.72 >= data[index10:index11, 0]) assert np.all(-0.32 >= data[index20:, 0]) assert np.all(-0.48 <= data[index20:, 0])
def test_controlledoscillator(Simulator, plt, rng, seed, outfile): f_max = 2 T = 2 # time to hold each input for stims = np.array([1, 0.5, 0, -0.5, -1]) # control signal tau = 0.1 with nengo.Network(seed=seed) as model: state = nengo.Ensemble(n_neurons=500, dimensions=3, radius=1.7) def feedback(x): x0, x1, f = x w = f * f_max * 2 * np.pi return x0 + w * tau * x1, x1 - w * tau * x0 nengo.Connection(state, state[:2], function=feedback, synapse=tau) freq = nengo.Ensemble(n_neurons=100, dimensions=1) nengo.Connection(freq, state[2], synapse=tau) kick = nengo.Node(lambda t: 1 if t < 0.08 else 0) nengo.Connection(kick, state[0]) control = piecewise({i * T: stim for i, stim in enumerate(stims)}) freq_control = nengo.Node(control) nengo.Connection(freq_control, freq) p_state = nengo.Probe(state, synapse=0.03) if 'spinnaker' in Simulator.__module__: nengo_spinnaker.add_spinnaker_params(model.config) model.config[kick].function_of_time = True model.config[freq_control].function_of_time = True sim = Simulator(model) sim.run(len(stims) * T) data = sim.data[p_state][:, 1] ideal_freqs = f_max * stims # target frequencies dt = 0.001 steps = int(T / dt) freqs = np.fft.fftfreq(steps, d=dt) # compute fft for each input data.shape = len(stims), steps fft = np.fft.fft(data, axis=1) # compute ideal fft for each input ideal_data = np.zeros_like(data) for i in range(len(stims)): ideal_data[i] = np.cos(2 * np.pi * ideal_freqs[i] * np.arange(steps) * dt) ideal_fft = np.fft.fft(ideal_data, axis=1) # only consider the magnitude fft = np.abs(fft) ideal_fft = np.abs(ideal_fft) # compute the normalized dot product between the actual and ideal ffts score = np.zeros(len(stims)) for i in range(len(stims)): score[i] = np.dot(fft[i] / np.linalg.norm(fft[i]), ideal_fft[i] / np.linalg.norm(ideal_fft[i])) outfile.write('"n_neurons": %d,\n' % sum(e.n_neurons for e in model.all_ensembles)) outfile.write('"simtime": %f,\n' % (len(stims) * T)) outfile.write('"score": %f,\n' % np.mean(score)) figsize = (onecolumn, 4.0) if horizontal else (onecolumn * 2, 4.0) setup(figsize=figsize) lines = [] if type(plt).__name__ != 'Mock': for i, y in enumerate(np.fft.fftshift(fft, axes=1)): lines.append(plt.stem(np.fft.fftshift(freqs), y)) marker, stem, base = lines[-1] marker.set_color(colors[i]) marker.set_markersize(10.0) for s in stem: s.set_color(colors[i]) s.set_linewidth(1.0) base.set_visible(False) plt.xlim(-f_max * 2, f_max * 2) plt.xlabel('Frequency (Hz)') plt.ylabel('Power of decoded value') plt.legend(lines, ['%gHz' % f for f in ideal_freqs], loc='best', prop={'size': 8}) sns.despine() plt.saveas = 'results-3.svg' if hasattr(sim, 'close'): sim.close()
def model(self, p): model = nengo.Network() if p.task == 'compare': self.exp = NumberExperiment(p=p) elif p.task == 'fingers': self.exp = FingerTouchExperiment(p=p) with model: input0 = nengo.Node(self.exp.input0) input1 = nengo.Node(self.exp.input1) if hasattr(self.exp, 'display'): display = nengo.Node(self.exp.display) pointer_source = nengo.Node(self.exp.pointer_source) pointer_target = nengo.Node(self.exp.pointer_target) report_finger = nengo.Node(self.exp.report_finger) report_compare = nengo.Node(self.exp.report_compare) memory_clear = nengo.Node(self.exp.memory_clear) # create neural models for the two input areas # (fingers and magnitude) area0 = nengo.Ensemble(p.N_input*p.pointer_count, p.pointer_count, radius=np.sqrt(p.pointer_count), label='area0') area1 = nengo.Ensemble(p.N_input, 1, label='area1') nengo.Connection(input0, area0) nengo.Connection(input1, area1) # define the connections to create the pointers def matrix(n,m,pre=None,post=None,value=1): m=[[0]*n for i in range(m)] if pre is None: pre=range(n) if post is None: post=range(m) for i in range(max(len(pre),len(post))): m[post[i%len(post)]][pre[i%len(pre)]]=value return m pointers = nengo.Network(label='pointers') with pointers: for i in range(p.pointer_count): nengo.Ensemble(p.N_pointer, dimensions = p.input_count*2+1, radius = np.sqrt(p.input_count*2+1), label='%d' % i) for i in range(p.pointer_count): pointer = pointers.ensembles[i] nengo.Connection(pointer_source, pointer, transform=matrix( p.input_count, p.input_count*2+1, post=[k*2 for k in range(p.input_count)])) nengo.Connection(pointer_target,pointer, transform=matrix(p.pointer_count, p.input_count*2+1, pre=[i], post=[p.input_count*2])) nengo.Connection(area0, pointer, transform=matrix(p.pointer_count, p.input_count*2+1, pre=[i],post=[1])) nengo.Connection(area1, pointer, transform=matrix(1,p.input_count*2+1, pre=[0],post=[3])) # define the connections to extract the current value # from the pointers def ref_func(x): if x[-1]<0.5: return 0 sum=0 for i in range(p.input_count): if x[2*i]>0.5: sum+=x[2*i+1] return sum basis=[] for i in range(p.pointer_count): b=[0]*p.pointer_count b[i]=1 basis.append(b) b=[0]*p.pointer_count b[i]=-1 basis.append(b) reference=nengo.Ensemble(p.N_reference,p.pointer_count, radius=np.sqrt(p.pointer_count), encoders=nengo.dists.Choice(basis), intercepts=nengo.dists.Uniform(0.1,0.9), label='reference') for i in range(p.pointer_count): matrix=[p.crosstalk]*p.pointer_count matrix[i]=1.0-p.crosstalk pointer = pointers.ensembles[i] nengo.Connection(pointer, reference, function=ref_func, transform=[[x] for x in matrix]) # add a memory to integrate the value referenced by the pointers memory = nengo.networks.EnsembleArray(p.N_memory, p.pointer_count, radius=1, label='memory') nengo.Connection(reference,memory.input,transform=1) nengo.Connection(memory.output, memory.input, transform=1, synapse=p.memory_synapse) # create a system to report which fingers were pressed report = nengo.networks.EnsembleArray(p.N_report,p.pointer_count, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform(0.3,0.9), radius=0.3, label='report') nengo.Connection(memory.output,report.input,transform=1) m=[[-10]*p.pointer_count for i in range(p.pointer_count)] for i in range(p.pointer_count): m[i][i]=0 nengo.Connection(report.output, report.input, transform=m, synapse=0.01) reported = nengo.networks.EnsembleArray(p.N_report, p.pointer_count, radius=1, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform(0.05,0.9), label='reported') nengo.Connection(report.output, reported.input, transform=1, synapse=0.2) nengo.Connection(reported.output, report.input, transform=-1) nengo.Connection(reported.output, reported.input, transform=1.2) # create a system to report whether the first # or second number is bigger compare = nengo.Ensemble(p.N_compare,1, label='compare', radius=1) nengo.Connection(memory.ensembles[0],compare[0],transform=p.evidence_scale) nengo.Connection(memory.ensembles[1],compare[0],transform=-p.evidence_scale) # create inhibitory gates to control the two reporting systems report_gate_f = nengo.Ensemble(50,1, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform(0.1,0.9), label='report gate f') report_gate_c=nengo.Ensemble(50,1, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform(0.1,0.9), label='report gate c') nengo.Connection(report_finger,report_gate_f,transform=-10) nengo.Connection(report_compare,report_gate_c,transform=-10) report_bias=nengo.Node([1], label='bias') nengo.Connection(report_bias,report_gate_f) nengo.Connection(report_bias,report_gate_c) nengo.Connection(report_gate_c, compare.neurons, transform=[[-100.0]]*p.N_compare, synapse=0.01) for i in range(p.pointer_count): nengo.Connection(report_gate_f, report.ensembles[i].neurons, transform=[[-100.0]]*p.N_report, synapse=0.01) nengo.Connection(report_gate_f, reported.ensembles[i].neurons, transform=[[-100.0]]*p.N_report, synapse=0.01) for ens in memory.all_ensembles + [compare]: nengo.Connection(memory_clear, ens.neurons, transform=[[-10]] * ens.n_neurons, synapse=0.01) self.p_report = nengo.Probe(report.output, synapse=0.01) self.p_compare = nengo.Probe(compare, synapse=0.01) self.p_memory = nengo.Probe(memory.output, synapse=0.01) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if callable(node.output): if not hasattr(node.output, '_nengo_html_'): model.config[node].function_of_time = True return model
net.ensembles.remove(ens) return model # replace passthrough Nodes with equivalent Nodes (so they're run on the PC, not SpiNNaker) def replace_passthrough(model): for node in model.all_nodes: if node.output is None: node.output = lambda t, x: x return model model = direct_nodes(model) model = replace_passthrough(model) nengo_spinnaker.add_spinnaker_params(model.config) if __name__ == '__main__': print("starting simulator...") before = time.time() sim = nengo_spinnaker.Simulator(model) after = time.time() print("time to build:") print(after - before) print("running simulator...") before = time.time()
def create_model(trial_info=('Target', 1, 'Short', 'METAL', 'SPARK'), hand='RIGHT',seedin=1): #print trial_info print '\n\n---- NEW MODEL ----' global model #word presented in current trial item1 = trial_info[3] item2 = trial_info[4] #returns images of current words def present_pair(t): im1 = get_image(item1) im2 = get_image(item2) return np.hstack((im1, im2)) #returns image 1 <100 ms, otherwise image 2 def present_item(t): if t < .1: return get_vector(item1) else: return get_vector(item2) def present_item2(t,output_attend): similarities = [np.dot(output_attend, vocab_attend['ITEM1'].v), np.dot(output_attend, vocab_attend['ITEM2'].v)] #print similarities ret_ima = np.zeros(1260) if similarities[0] > .5: ret_ima = get_image(item1) elif similarities[1] > .5: ret_ima = get_image(item2) return ret_ima model = spa.SPA(seed=seedin) if use_spinnaker: import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) with model: #display current stimulus pair (not part of model) #model.pair_input = nengo.Node(present_pair) #model.pair_display = nengo.Node(display_func, size_in=model.pair_input.size_out) # to show input #nengo.Connection(model.pair_input, model.pair_display, synapse=None) # control model.control_net = nengo.Network() with model.control_net: model.attend = spa.State(D, vocab=vocab_attend, feedback=.5) # vocab_attend model.goal = spa.State(D, vocab_goal, feedback=1) # current goal Dlow model.target_hand = spa.State(Dmid, vocab=vocab_motor, feedback=1) ### vision ### # set up network parameters n_vis = X_train.shape[1] # nr of pixels, dimensions of network n_hid = 1000 # nr of gabor encoders/neurons # random state to start rng = np.random.RandomState(9) encoders = Gabor().generate(n_hid, (11, 11), rng=rng) # gabor encoders, 11x11 apparently, why? encoders = Mask((14, 90)).populate(encoders, rng=rng, flatten=True) # use them on part of the image model.visual_net = nengo.Network() with model.visual_net: #represent currently attended item model.attended_item = nengo.Node(present_item, label='attended_item') if use_spinnaker: model.config[model.attended_item].function_of_time = True #model.attended_item = nengo.Node(present_item2,size_in=model.attend.output.size_out) #nengo.Connection(model.attend.output, model.attended_item) #model.vision_gabor = nengo.Ensemble(n_hid, n_vis, eval_points=X_train, # neuron_type=nengo.LIFRate(), # intercepts=nengo.dists.Choice([-0.5]), # max_rates=nengo.dists.Choice([100]), # encoders=encoders) model.visual_representation = spa.State(Dmid) #model.visual_representation = nengo.Ensemble(n_hid, dimensions=Dmid) nengo.Connection(model.attended_item, model.visual_representation.input, synapse=0.005) #model.visconn = nengo.Connection(model.vision_gabor, model.visual_representation, synapse=0.005, # eval_points=X_train, function=train_targets, # solver=nengo.solvers.LstsqL2(reg=0.01)) #nengo.Connection(model.attended_item, model.vision_gabor, synapse=None) # display attended item #model.display_attended = nengo.Node(display_func, size_in=model.attended_item.size_out) # to show input #nengo.Connection(model.attended_item, model.display_attended, synapse=None) # concepts model.concepts = spa.AssociativeMemory(vocab_concepts,wta_output=True,wta_inhibit_scale=1) nengo.Connection(model.visual_representation.output, model.concepts.input, transform=vision_mapping) # pair representation model.vis_pair = spa.State(D, vocab=vocab_concepts, feedback=2) model.dm_learned_words = spa.AssociativeMemory(vocab_learned_words) #familiarity should be continuous over all items, so no wta nengo.Connection(model.dm_learned_words.output,model.dm_learned_words.input,transform=.5,synapse=.01) model.familiarity = spa.State(1,feedback_synapse=.01) #no fb syn specified nengo.Connection(model.dm_learned_words.am.elem_output,model.familiarity.input, #am.element_output == all outputs, we sum transform=.8*np.ones((1,model.dm_learned_words.am.elem_output.size_out))) model.dm_pairs = spa.AssociativeMemory(vocab_learned_pairs, input_keys=list_of_pairs,wta_output=True) nengo.Connection(model.dm_pairs.output,model.dm_pairs.input,transform=.5) #this works: model.representation = spa.AssociativeMemory(vocab_learned_pairs, input_keys=list_of_pairs, wta_output=True) nengo.Connection(model.representation.output, model.representation.input, transform=2) model.rep_filled = spa.State(1,feedback_synapse=.005) #no fb syn specified nengo.Connection(model.representation.am.elem_output,model.rep_filled.input, #am.element_output == all outputs, we sum transform=.8*np.ones((1,model.representation.am.elem_output.size_out)),synapse=0.005) #this doesn't: #model.representation = spa.State(D,feedback=1) #model.rep_filled = spa.State(1,feedback_synapse=.005) #no fb syn specified #nengo.Connection(model.representation.output,model.rep_filled.input, #am.element_output == all outputs, we sum # transform=.8*np.ones((1,model.representation.output.size_out)),synapse=0) # this shouldn't really be fixed I think model.comparison = spa.Compare(D, vocab=vocab_concepts) #motor model.motor_net = nengo.Network() with model.motor_net: #input multiplier model.motor_input = spa.State(Dmid,vocab=vocab_motor) #higher motor area (SMA?) model.motor = spa.State(Dmid, vocab=vocab_motor,feedback=1) #connect input multiplier with higher motor area nengo.Connection(model.motor_input.output,model.motor.input,synapse=.1,transform=10) #finger area model.fingers = spa.AssociativeMemory(vocab_fingers, input_keys=['L1', 'L2', 'R1', 'R2'], wta_output=True) #conncetion between higher order area (hand, finger), to lower area nengo.Connection(model.motor.output, model.fingers.input, transform=.4*motor_mapping) #finger position (spinal?) model.finger_pos = nengo.networks.EnsembleArray(n_neurons=50, n_ensembles=4) nengo.Connection(model.finger_pos.output, model.finger_pos.input, synapse=0.1, transform=0.3) #feedback #connection between finger area and finger position nengo.Connection(model.fingers.am.elem_output, model.finger_pos.input, transform=np.diag([0.55, .53, .57, .55])) #fix these model.bg = spa.BasalGanglia( spa.Actions( 'dot(goal,DO_TASK)-.5 --> dm_learned_words=vis_pair, goal=RECOG, attend=ITEM1', 'dot(goal,RECOG)+dot(attend,ITEM1)+familiarity-2 --> goal=RECOG2, dm_learned_words=vis_pair, attend=ITEM2',#'vis_pair=ITEM1*concepts', 'dot(goal,RECOG)+dot(attend,ITEM1)+(1-familiarity)-2 --> goal=RECOG2, attend=ITEM2', #motor_input=1.5*target_hand+MIDDLE, 'dot(goal,RECOG2)+dot(attend,ITEM2)+familiarity-1.3 --> goal=RECOLLECTION,dm_pairs = 2*vis_pair, representation=3*dm_pairs',# vis_pair=ITEM2*concepts', 'dot(goal,RECOG2)+dot(attend,ITEM2)+(1-familiarity)-1.3 --> goal=RESPOND, motor_input=1.0*target_hand+MIDDLE', 'dot(goal,RECOLLECTION) - .5 --> goal=RECOLLECTION, representation=2*dm_pairs', 'dot(goal,RECOLLECTION) + 2*rep_filled - 1.3 --> goal=COMPARE_ITEM1, attend=ITEM1, comparison_A = 2*vis_pair,comparison_B = 2*representation*~attend', 'dot(goal,COMPARE_ITEM1) + rep_filled + comparison -1 --> goal=COMPARE_ITEM2, attend=ITEM2, comparison_A = 2*vis_pair',#comparison_B = 2*representation*~attend', 'dot(goal,COMPARE_ITEM1) + rep_filled + (1-comparison) -1 --> goal=RESPOND,motor_input=1.0*target_hand+MIDDLE',#comparison_A = 2*vis_pair,comparison_B = 2*representation*~attend', 'dot(goal,COMPARE_ITEM2) + rep_filled + comparison - 1 --> goal=RESPOND,motor_input=1.0*target_hand+INDEX',#comparison_A = 2*vis_pair,comparison_B = 2*representation*~attend', 'dot(goal,COMPARE_ITEM2) + rep_filled + (1-comparison) -1 --> goal=RESPOND,motor_input=1.0*target_hand+MIDDLE',#comparison_A = 2*vis_pair,comparison_B = 2*representation*~attend', 'dot(goal,RESPOND) + comparison - 1 --> goal=RESPOND, motor_input=1.0*target_hand+INDEX', #comparison_A = 2*vis_pair,comparison_B = 2*representation*~attend', 'dot(goal,RESPOND) + (1-comparison) - 1 --> goal=RESPOND, motor_input=1.0*target_hand+MIDDLE', #comparison_A = 2*vis_pair,comparison_B = 2*representation*~attend', # 'dot(goal,RECOLLECTION) + (1 - dot(representation,vis_pair)) - 1.3 --> goal=RESPOND, motor_input=1.0*target_hand+MIDDLE', 'dot(goal,RESPOND)+dot(motor,MIDDLE+INDEX)-1.0 --> goal=END', 'dot(goal,END) --> goal=END', #'.6 -->', #possible to match complete buffer, ie is representation filled? )) model.thalamus = spa.Thalamus(model.bg) model.cortical = spa.Cortical( # cortical connection: shorthand for doing everything with states and connections spa.Actions( # 'motor_input = .04*target_hand', #'dm_learned_words = .8*concepts', #.5 #'dm_pairs = 2*stimulus' 'vis_pair = 2*attend*concepts+concepts', 'comparison_A = 2*vis_pair', 'comparison_B = 2*representation*~attend', )) #probes #model.pr_goal = nengo.Probe(model.goal.output,synapse=.01) model.pr_motor_pos = nengo.Probe(model.finger_pos.output,synapse=.01) #raw vector (dimensions x time) model.pr_motor = nengo.Probe(model.fingers.output,synapse=.01) model.pr_motor1 = nengo.Probe(model.motor.output, synapse=.01) #model.pr_target = nengo.Probe(model.target_hand.output, synapse=.01) #model.pr_attend = nengo.Probe(model.attend.output, synapse=.01) #input model.input = spa.Input(goal=lambda t: 'DO_TASK' if t < 0.05 else '0', target_hand=hand, #attend=lambda t: 'ITEM1' if t < 0.1 else 'ITEM2', ) if use_spinnaker: for n in model.input.nodes: model.config[n].function_of_time = True
def _test_sequence(Simulator, plt, seed, outfile, prune_passthrough): dimensions = 32 subdimensions = 16 T = 4.0 seq_length = 6 with spa.SPA(seed=seed) as model: model.state = spa.Memory(dimensions=dimensions, subdimensions=subdimensions) seq_actions = [ 'dot(state,A%d) --> state=A%d' % (i, (i + 1) % seq_length) for i in range(seq_length) ] model.bg = spa.BasalGanglia(spa.Actions(*seq_actions)) model.thal = spa.Thalamus(model.bg) def stim_state(t): if t < 0.1: return 'A0' else: return '0' model.input = spa.Input(state=stim_state) p_state = nengo.Probe(model.state.state.output, synapse=0.01) if 'spinnaker' in Simulator.__module__: nengo_spinnaker.add_spinnaker_params(model.config) model.config[ model.input.input_nodes['state']].function_of_time = True vocab = model.get_input_vocab('state') if prune_passthrough: model = remove_passthrough_nodes(model) sim = Simulator(model) sim.run(T) t = sim.trange() data = sim.data[p_state] ideal = np.array([vocab.parse('A%d' % i).v for i in range(seq_length)]) dotp = np.dot(data, ideal.T) best = np.argmax(dotp, axis=1) delta = np.diff(best) indexes = np.where(delta != 0) # [:, 1:] ignores the first transition, which is meaningless delta_t = np.diff(indexes)[:, 1:] * 0.001 mean = np.mean(delta_t) std = np.std(delta_t) outfile.write('"n_neurons": %d,\n' % sum(e.n_neurons for e in model.all_ensembles)) outfile.write('"simtime": %f,\n' % T) outfile.write('"timing_mean": %f,\n' % mean) outfile.write('"timing_std": %f,\n' % std) figsize = (onecolumn, 4.0) if horizontal else (onecolumn * 2, 3.0) setup(figsize=figsize, palette_args={ 'palette': "cubehelix", 'n_colors': 6 }) plt.plot(t[t < 1.0], dotp[t < 1.0]) for transition in t[indexes[0]]: plt.axvline(transition, c='0.5', lw=1, ls=':') plt.ylabel('Similarity to item') plt.xlabel('Time (s)') plt.xlim(right=1.0) sns.despine() if prune_passthrough: plt.saveas = 'results-4.svg' else: plt.saveas = 'results-5.svg' if hasattr(sim, 'close'): sim.close()
# Create standard communication channel network with white noise input inp = nengo.Node(WhiteNoise(), label="inp") inp_p = nengo.Probe(inp) pre = nengo.Ensemble(ensemble_size, dimensions=dimensions, label="pre") pre_p = nengo.Probe(pre, synapse=0.01) nengo.Connection(inp, pre) post = nengo.Ensemble(ensemble_size, dimensions=dimensions, label="post") posts_p = nengo.Probe(post, synapse = 0.01) nengo.Connection(pre, post, function=lambda x: np.random.random(dimensions)) # Setup SpiNNaker-specific options to supply white noise from on # chip and profile the ensemble at the start of the channel nengo_spinnaker.add_spinnaker_params(model.config) model.config[inp].function_of_time = True model.config[pre].profile = True # Create a SpiNNaker simulator and run model sim = nengo_spinnaker.Simulator(model) with sim: sim.run(10.0) # Read profiler data profiler_data = sim.profiler_data[pre] # Open CSV file and create writer with open("profile_communication_channel.csv", "wb") as csv_file: csv_writer = csv.writer(csv_file)
def test_probe_passnodes(): """Test that pass nodes are left on SpiNNaker and that they may be probed. """ class ValueReceiver(object): def __init__(self): self.ts = list() self.values = list() def __call__(self, t, x): self.ts.append(t) self.values.append(x[:]) with nengo.Network("Test Network") as net: # Create an input Node which is a function of time only input_node = nengo.Node(lambda t: -0.33 if t < 1.0 else 0.10, label="my input") # 3D ensemble array to represent this value ens = nengo.networks.EnsembleArray(500, 3, label="reps") # Pipe the input to the array and probe the output of the array nengo.Connection(input_node, ens.input, transform=[[1.0], [0.0], [-1.0]]) p_ens = nengo.Probe(ens.output, synapse=0.05) # Also add a node connected to the end of the ensemble array to ensure # that multiple things correctly receive values from the filter. receiver = ValueReceiver() n_receiver = nengo.Node(receiver, size_in=3) nengo.Connection(ens.output, n_receiver, synapse=0.05) # Mark the input Node as being a function of time nengo_spinnaker.add_spinnaker_params(net.config) net.config[input_node].function_of_time = True # Create the simulate and simulate sim = nengo_spinnaker.Simulator(net) # Run the simulation for long enough to ensure that the decoded value is # with +/-20% of the input value. with sim: sim.run(2.0) # Check that the values are decoded as expected index10 = int(p_ens.synapse.tau * 3 / sim.dt) index11 = 1.0 / sim.dt index20 = index11 + index10 data = sim.data[p_ens] assert (np.all(-0.25 >= data[index10:index11, 0]) and np.all(-0.40 <= data[index10:index11, 0]) and np.all(+0.05 <= data[index20:, 0]) and np.all(+0.15 >= data[index20:, 0])) assert np.all(-0.05 <= data[:, 1]) and np.all(+0.05 >= data[:, 1]) assert (np.all(+0.25 <= data[index10:index11, 2]) and np.all(+0.40 >= data[index10:index11, 2]) and np.all(-0.05 >= data[index20:, 2]) and np.all(-0.15 <= data[index20:, 2])) # Check that values came into the node correctly assert +0.05 <= receiver.values[-1][0] <= +0.15 assert -0.05 >= receiver.values[-1][2] >= -0.15
def test_product(Simulator, plt, seed, outfile): hc = HilbertCurve(n=4) duration = 5. wait_duration = 0.5 def stimulus_fn(t): return np.squeeze(hc(t / duration).T * 2 - 1) model = nengo.Network(seed=seed) with model: stimulus = nengo.Node( output=lambda t: stimulus_fn(max(0., t - wait_duration)), size_out=2) product_net = nengo.networks.Product(100, 1) nengo.Connection(stimulus[0], product_net.A) nengo.Connection(stimulus[1], product_net.B) ens_direct = nengo.Node(output=lambda t, x: x[0] * x[1], size_in=2) nengo.Connection(stimulus, ens_direct) probe_inp = nengo.Probe(stimulus, synapse=0.005) probe_direct = nengo.Probe(ens_direct) probe_test = nengo.Probe(product_net.output, synapse=0.005) if 'spinnaker' in Simulator.__module__: nengo_spinnaker.add_spinnaker_params(model.config) model.config[stimulus].function_of_time = True sim = Simulator(model) sim.run(duration + wait_duration) after_wait = sim.trange() > wait_duration actual = sim.data[probe_test][after_wait] target = sim.data[probe_direct][after_wait] figsize = (onecolumn, 4.0) if horizontal else (onecolumn * 2, 4.0) setup(figsize=figsize) plt.subplot(2, 1, 1) y = sim.data[probe_inp][after_wait] plt.plot(sim.trange()[after_wait], y[:, 0], c=colors[2]) plt.plot(sim.trange()[after_wait], y[:, 1], c=colors[3]) plt.ylabel('Decoded input') plt.xlim(left=wait_duration, right=duration + wait_duration) plt.xticks(()) plt.subplot(2, 1, 2) plt.plot(sim.trange()[after_wait], actual, c=colors[4]) plt.plot(sim.trange()[after_wait], target, c='k', lw=1) plt.ylabel('Decoded product') plt.xlabel('Time (s)') plt.xlim(left=wait_duration, right=duration + wait_duration) sns.despine() plt.saveas = 'results-2.svg' outfile.write('"n_neurons": %d,\n' % sum(e.n_neurons for e in model.all_ensembles)) outfile.write('"simtime": %f,\n' % (duration + wait_duration)) outfile.write('"rmse": %f,\n' % (rmse(actual, target))) if hasattr(sim, 'close'): sim.close()
def run_test(nengo_network, nodes_as_function_of_time, nodes_as_function_of_time_time_period): seed = 11111 app_graph_builder = NengoApplicationGraphBuilder() (app_graph, host_network, nengo_to_app_graph_map, random_number_generator) = app_graph_builder( nengo_network=nengo_network, machine_time_step=1.0, nengo_random_number_generator_seed=1234, decoder_cache=NoDecoderCache(), utilise_extra_core_for_probes=True, nengo_nodes_as_function_of_time=nodes_as_function_of_time, function_of_time_nodes_time_period=( nodes_as_function_of_time_time_period)) interposer_installer = NengoUtiliseInterposers() app_graph = interposer_installer(app_graph, random_number_generator, seed) virtual_machine_generator = VirtualMachineGenerator() machine = virtual_machine_generator(width=16, height=16, virtual_has_wrap_arounds=False, version=5, n_cpus_per_chip=18, with_monitors=True, down_chips=None, down_cores=None, down_links=None, max_sdram_size=None) partitioner = NengoPartitioner() machine_graph, graph_mapper = partitioner(app_graph, machine, random_number_generator, pre_allocated_resources=None) # build via nengo_spinnaker_gfe - spinnaker nengo_spinnaker.add_spinnaker_params(nengo_network.config) for nengo_node in nodes_as_function_of_time: nengo_network.config[nengo_node].function_of_time = True for nengo_node in nodes_as_function_of_time_time_period: nengo_network.config[nengo_node].function_of_time_period = \ nodes_as_function_of_time_time_period[nengo_node] io_controller = Ethernet() builder_kwargs = io_controller.builder_kwargs nengo_spinnaker_network_builder = Model() nengo_spinnaker_network_builder.build(nengo_network, **builder_kwargs) net_list = nengo_spinnaker_network_builder.make_netlist(200) nengo_app_operators = dict() nengo_app_operators.update( nengo_spinnaker_network_builder.object_operators) nengo_app_operators.update(io_controller._sdp_receivers) nengo_app_operators.update(io_controller._sdp_transmitters) match = \ compare_against_the_nengo_spinnaker_and_gfe_impls_machine_graphs( # nengo bits nengo_app_operators, nengo_to_app_graph_map, nengo_spinnaker_network_builder.connection_map, net_list, # gfe bits machine_graph, graph_mapper, app_graph, nengo_spinnaker_network_builder) if not match: raise Exception("didnt match")
def run(self, **kwargs): p, fn = self.process_args(**kwargs) if p.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.ERROR) print("running %s" % fn) np.random.seed(p.seed) model = self.model(p) module = importlib.import_module(p.backend) Simulator = module.Simulator if p.backend == "nengo_spinnaker": import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if node.size_in == 0 and node.size_out > 0 and callable(node.output): model.config[node].function_of_time = True if not p.no_figs or p.show_figs: plt = matplotlib.pyplot else: plt = None sim = Simulator(model, dt=p.dt) self.start_time = time.time() self.sim_speed = None result = self.evaluate(p, sim, plt) if p.backend == "nengo_spinnaker": sim.close() if self.sim_speed is not None and "sim_speed" not in result: result["sim_speed"] = self.sim_speed text = [] for k, v in sorted(result.items()): text.append("%s = %s" % (k, repr(v))) if plt is not None: plt.suptitle(fn.replace("#", "\n") + "\n" + "\n".join(text), fontsize=8) plt.figtext(0.12, 0.12, "\n".join(self.args_text)) text = self.args_text + text text = "\n".join(text) if not os.path.exists(p.data_dir): os.mkdir(p.data_dir) fn = os.path.join(p.data_dir, fn) if not p.no_figs: plt.savefig(fn + ".png", dpi=300) with open(fn + ".txt", "w") as f: f.write(text) print(text) db = shelve.open(fn + ".db") db["trange"] = sim.trange() for k, v in inspect.getmembers(self): if isinstance(v, nengo.Probe): db[k] = sim.data[v] db.close() if p.show_figs: plt.show() return result
def run(self, **kwargs): p, fn = self.process_args(**kwargs) if p.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.ERROR) print('running %s' % fn) np.random.seed(p.seed) model = self.model(p) if p.gui: import nengo_gui nengo_gui.GUI(model=model, filename=self.__class__.__name__, locals=dict(model=model), interactive=False, allow_file_change=False).start() return module = importlib.import_module(p.backend) Simulator = module.Simulator if p.backend == 'nengo_spinnaker': try: _ = model.config[nengo.Node].function_of_time except AttributeError: import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if (node.size_in == 0 and node.size_out > 0 and callable(node.output)): model.config[node].function_of_time = True if p.save_figs or p.show_figs: plt = matplotlib.pyplot plt.figure() else: plt = None sim = Simulator(model, dt=p.dt) self.start_time = time.time() self.sim_speed = None result = self.evaluate(p, sim, plt) if p.backend == 'nengo_spinnaker': sim.close() if self.sim_speed is not None and 'sim_speed' not in result: result['sim_speed'] = self.sim_speed text = [] for k, v in sorted(result.items()): text.append('%s = %s' % (k, repr(v))) if plt is not None and not p.hide_overlay: plt.suptitle(fn +'\n' + '\n'.join(text), fontsize=8) plt.figtext(0.13,0.12,'\n'.join(self.args_text)) text = self.args_text + text text = '\n'.join(text) if not os.path.exists(p.data_dir): os.mkdir(p.data_dir) fn = os.path.join(p.data_dir, fn) if p.save_figs: plt.savefig(fn + '.png', dpi=300) with open(fn + '.txt', 'w') as f: f.write(text) print(text) if p.save_raw: db = shelve.open(fn + '.db') db['trange'] = sim.trange() for k, v in inspect.getmembers(self): if isinstance(v, nengo.Probe): db[k] = sim.data[v] db.close() if p.show_figs: plt.show() return result
def run(self, **kwargs): p, fn = self.process_args(**kwargs) if p.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.ERROR) print('running %s' % fn) np.random.seed(p.seed) model = self.model(p) if p.gui: import nengo_gui nengo_gui.GUI(model=model, filename=self.__class__.__name__, locals=dict(model=model), interactive=False, allow_file_change=False).start() return module = importlib.import_module(p.backend) Simulator = module.Simulator if p.backend == 'nengo_spinnaker': try: _ = model.config[nengo.Node].function_of_time except AttributeError: import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if (node.size_in == 0 and node.size_out > 0 and callable(node.output)): model.config[node].function_of_time = True if p.save_figs or p.show_figs: plt = matplotlib.pyplot plt.figure() else: plt = None sim = Simulator(model, dt=p.dt) self.start_time = time.time() self.sim_speed = None result = self.evaluate(p, sim, plt) if p.backend == 'nengo_spinnaker': sim.close() if self.sim_speed is not None and 'sim_speed' not in result: result['sim_speed'] = self.sim_speed text = [] for k, v in sorted(result.items()): text.append('%s = %s' % (k, repr(v))) if plt is not None and not p.hide_overlay: plt.suptitle(fn + '\n' + '\n'.join(text), fontsize=8) plt.figtext(0.13, 0.12, '\n'.join(self.args_text)) text = self.args_text + text text = '\n'.join(text) if not os.path.exists(p.data_dir): os.mkdir(p.data_dir) fn = os.path.join(p.data_dir, fn) if p.save_figs: plt.savefig(fn + '.png', dpi=300) with open(fn + '.txt', 'w') as f: f.write(text) print(text) if p.save_raw: db = shelve.open(fn + '.db') db['trange'] = sim.trange() for k, v in inspect.getmembers(self): if isinstance(v, nengo.Probe): db[k] = sim.data[v] db.close() if p.show_figs: plt.show() return result
def test_product(Simulator, plt, seed, outfile): hc = HilbertCurve(n=4) duration = 5. wait_duration = 0.5 def stimulus_fn(t): return np.squeeze(hc(t / duration).T * 2 - 1) model = nengo.Network(seed=seed) with model: stimulus = nengo.Node( output=lambda t: stimulus_fn(max(0., t - wait_duration)), size_out=2) product_net = nengo.networks.Product(100, 1) nengo.Connection(stimulus[0], product_net.A) nengo.Connection(stimulus[1], product_net.B) ens_direct = nengo.Node(output=lambda t, x: x[0] * x[1], size_in=2) nengo.Connection(stimulus, ens_direct) probe_inp = nengo.Probe(stimulus, synapse=0.005) probe_direct = nengo.Probe(ens_direct) probe_test = nengo.Probe(product_net.output, synapse=0.005) if 'spinnaker' in Simulator.__module__: nengo_spinnaker.add_spinnaker_params(model.config) model.config[stimulus].function_of_time = True sim = Simulator(model) sim.run(duration + wait_duration) after_wait = sim.trange() > wait_duration actual = sim.data[probe_test][after_wait] target = sim.data[probe_direct][after_wait] figsize = (onecolumn, 4.0) if horizontal else (onecolumn * 2, 4.0) setup(figsize=figsize) plt.subplot(2, 1, 1) y = sim.data[probe_inp][after_wait] plt.plot(sim.trange()[after_wait], y[:, 0], c=colors[2]) plt.plot(sim.trange()[after_wait], y[:, 1], c=colors[3]) plt.ylabel('Decoded input') plt.xlim(left=wait_duration, right=duration + wait_duration) plt.xticks(()) plt.subplot(2, 1, 2) plt.plot(sim.trange()[after_wait], actual, c=colors[4]) plt.plot(sim.trange()[after_wait], target, c='k', lw=1) plt.ylabel('Decoded product') plt.xlabel('Time (s)') plt.xlim(left=wait_duration, right=duration + wait_duration) sns.despine() plt.saveas = 'results-2.svg' outfile.write('"n_neurons": %d,\n' % sum( e.n_neurons for e in model.all_ensembles)) outfile.write('"simtime": %f,\n' % (duration + wait_duration)) outfile.write('"rmse": %f,\n' % (rmse(actual, target))) if hasattr(sim, 'close'): sim.close()
def _test_sequence(Simulator, plt, seed, outfile, prune_passthrough): dimensions = 32 subdimensions = 16 T = 4.0 seq_length = 6 with spa.SPA(seed=seed) as model: model.state = spa.Memory(dimensions=dimensions, subdimensions=subdimensions) seq_actions = ['dot(state,A%d) --> state=A%d' % (i, (i+1) % seq_length) for i in range(seq_length)] model.bg = spa.BasalGanglia(spa.Actions(*seq_actions)) model.thal = spa.Thalamus(model.bg) def stim_state(t): if t < 0.1: return 'A0' else: return '0' model.input = spa.Input(state=stim_state) p_state = nengo.Probe(model.state.state.output, synapse=0.01) if 'spinnaker' in Simulator.__module__: nengo_spinnaker.add_spinnaker_params(model.config) model.config[ model.input.input_nodes['state'] ].function_of_time = True vocab = model.get_input_vocab('state') if prune_passthrough: model = remove_passthrough_nodes(model) sim = Simulator(model) sim.run(T) t = sim.trange() data = sim.data[p_state] ideal = np.array([vocab.parse('A%d' % i).v for i in range(seq_length)]) dotp = np.dot(data, ideal.T) best = np.argmax(dotp, axis=1) delta = np.diff(best) indexes = np.where(delta != 0) # [:, 1:] ignores the first transition, which is meaningless delta_t = np.diff(indexes)[:, 1:] * 0.001 mean = np.mean(delta_t) std = np.std(delta_t) outfile.write('"n_neurons": %d,\n' % sum( e.n_neurons for e in model.all_ensembles)) outfile.write('"simtime": %f,\n' % T) outfile.write('"timing_mean": %f,\n' % mean) outfile.write('"timing_std": %f,\n' % std) figsize = (onecolumn, 4.0) if horizontal else (onecolumn * 2, 3.0) setup(figsize=figsize, palette_args={ 'palette': "cubehelix", 'n_colors': 6}) plt.plot(t[t < 1.0], dotp[t < 1.0]) for transition in t[indexes[0]]: plt.axvline(transition, c='0.5', lw=1, ls=':') plt.ylabel('Similarity to item') plt.xlabel('Time (s)') plt.xlim(right=1.0) sns.despine() if prune_passthrough: plt.saveas = 'results-4.svg' else: plt.saveas = 'results-5.svg' if hasattr(sim, 'close'): sim.close()
def test_controlledoscillator(Simulator, plt, rng, seed, outfile): f_max = 2 T = 2 # time to hold each input for stims = np.array([1, 0.5, 0, -0.5, -1]) # control signal tau = 0.1 with nengo.Network(seed=seed) as model: state = nengo.Ensemble(n_neurons=500, dimensions=3, radius=1.7) def feedback(x): x0, x1, f = x w = f * f_max * 2 * np.pi return x0 + w * tau * x1, x1 - w * tau * x0 nengo.Connection(state, state[:2], function=feedback, synapse=tau) freq = nengo.Ensemble(n_neurons=100, dimensions=1) nengo.Connection(freq, state[2], synapse=tau) kick = nengo.Node(lambda t: 1 if t < 0.08 else 0) nengo.Connection(kick, state[0]) control = piecewise({i * T: stim for i, stim in enumerate(stims)}) freq_control = nengo.Node(control) nengo.Connection(freq_control, freq) p_state = nengo.Probe(state, synapse=0.03) if 'spinnaker' in Simulator.__module__: nengo_spinnaker.add_spinnaker_params(model.config) model.config[kick].function_of_time = True model.config[freq_control].function_of_time = True sim = Simulator(model) sim.run(len(stims) * T) data = sim.data[p_state][:, 1] ideal_freqs = f_max * stims # target frequencies dt = 0.001 steps = int(T / dt) freqs = np.fft.fftfreq(steps, d=dt) # compute fft for each input data.shape = len(stims), steps fft = np.fft.fft(data, axis=1) # compute ideal fft for each input ideal_data = np.zeros_like(data) for i in range(len(stims)): ideal_data[i] = np.cos(2 * np.pi * ideal_freqs[i] * np.arange(steps) * dt) ideal_fft = np.fft.fft(ideal_data, axis=1) # only consider the magnitude fft = np.abs(fft) ideal_fft = np.abs(ideal_fft) # compute the normalized dot product between the actual and ideal ffts score = np.zeros(len(stims)) for i in range(len(stims)): score[i] = np.dot(fft[i] / np.linalg.norm(fft[i]), ideal_fft[i] / np.linalg.norm(ideal_fft[i])) outfile.write('"n_neurons": %d,\n' % sum( e.n_neurons for e in model.all_ensembles)) outfile.write('"simtime": %f,\n' % (len(stims) * T)) outfile.write('"score": %f,\n' % np.mean(score)) figsize = (onecolumn, 4.0) if horizontal else (onecolumn * 2, 4.0) setup(figsize=figsize) lines = [] if type(plt).__name__ != 'Mock': for i, y in enumerate(np.fft.fftshift(fft, axes=1)): lines.append(plt.stem(np.fft.fftshift(freqs), y)) marker, stem, base = lines[-1] marker.set_color(colors[i]) marker.set_markersize(10.0) for s in stem: s.set_color(colors[i]) s.set_linewidth(1.0) base.set_visible(False) plt.xlim(-f_max * 2, f_max * 2) plt.xlabel('Frequency (Hz)') plt.ylabel('Power of decoded value') plt.legend(lines, ['%gHz' % f for f in ideal_freqs], loc='best', prop={'size': 8}) sns.despine() plt.saveas = 'results-3.svg' if hasattr(sim, 'close'): sim.close()
def model(self, p): model = nengo.Network() if p.task == 'compare': self.exp = NumberExperiment(p=p) elif p.task == 'fingers': self.exp = FingerTouchExperiment(p=p) with model: input0 = nengo.Node(self.exp.input0) input1 = nengo.Node(self.exp.input1) if hasattr(self.exp, 'display'): display = nengo.Node(self.exp.display) pointer_source = nengo.Node(self.exp.pointer_source) pointer_target = nengo.Node(self.exp.pointer_target) report_finger = nengo.Node(self.exp.report_finger) report_compare = nengo.Node(self.exp.report_compare) memory_clear = nengo.Node(self.exp.memory_clear) # create neural models for the two input areas # (fingers and magnitude) area0 = nengo.Ensemble(p.N_input * p.pointer_count, p.pointer_count, radius=np.sqrt(p.pointer_count), label='area0') area1 = nengo.Ensemble(p.N_input, 1, label='area1') nengo.Connection(input0, area0) nengo.Connection(input1, area1) # define the connections to create the pointers def matrix(n, m, pre=None, post=None, value=1): m = [[0] * n for i in range(m)] if pre is None: pre = range(n) if post is None: post = range(m) for i in range(max(len(pre), len(post))): m[post[i % len(post)]][pre[i % len(pre)]] = value return m pointers = nengo.Network(label='pointers') with pointers: for i in range(p.pointer_count): nengo.Ensemble(p.N_pointer, dimensions=p.input_count * 2 + 1, radius=np.sqrt(p.input_count * 2 + 1), label='%d' % i) for i in range(p.pointer_count): pointer = pointers.ensembles[i] nengo.Connection( pointer_source, pointer, transform=matrix( p.input_count, p.input_count * 2 + 1, post=[k * 2 for k in range(p.input_count)])) nengo.Connection(pointer_target, pointer, transform=matrix(p.pointer_count, p.input_count * 2 + 1, pre=[i], post=[p.input_count * 2])) nengo.Connection(area0, pointer, transform=matrix(p.pointer_count, p.input_count * 2 + 1, pre=[i], post=[1])) nengo.Connection(area1, pointer, transform=matrix(1, p.input_count * 2 + 1, pre=[0], post=[3])) # define the connections to extract the current value # from the pointers def ref_func(x): if x[-1] < 0.5: return 0 sum = 0 for i in range(p.input_count): if x[2 * i] > 0.5: sum += x[2 * i + 1] return sum basis = [] for i in range(p.pointer_count): b = [0] * p.pointer_count b[i] = 1 basis.append(b) b = [0] * p.pointer_count b[i] = -1 basis.append(b) reference = nengo.Ensemble(p.N_reference, p.pointer_count, radius=np.sqrt(p.pointer_count), encoders=nengo.dists.Choice(basis), intercepts=nengo.dists.Uniform( 0.1, 0.9), label='reference') for i in range(p.pointer_count): matrix = [p.crosstalk] * p.pointer_count matrix[i] = 1.0 - p.crosstalk pointer = pointers.ensembles[i] nengo.Connection(pointer, reference, function=ref_func, transform=[[x] for x in matrix]) # add a memory to integrate the value referenced by the pointers memory = nengo.networks.EnsembleArray(p.N_memory, p.pointer_count, radius=1, label='memory') nengo.Connection(reference, memory.input, transform=1) nengo.Connection(memory.output, memory.input, transform=1, synapse=p.memory_synapse) # create a system to report which fingers were pressed report = nengo.networks.EnsembleArray( p.N_report, p.pointer_count, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform(0.3, 0.9), radius=0.3, label='report') nengo.Connection(memory.output, report.input, transform=1) m = [[-10] * p.pointer_count for i in range(p.pointer_count)] for i in range(p.pointer_count): m[i][i] = 0 nengo.Connection(report.output, report.input, transform=m, synapse=0.01) reported = nengo.networks.EnsembleArray( p.N_report, p.pointer_count, radius=1, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform(0.05, 0.9), label='reported') nengo.Connection(report.output, reported.input, transform=1, synapse=0.2) nengo.Connection(reported.output, report.input, transform=-1) nengo.Connection(reported.output, reported.input, transform=1.2) # create a system to report whether the first # or second number is bigger compare = nengo.Ensemble(p.N_compare, 1, label='compare', radius=1) nengo.Connection(memory.ensembles[0], compare[0], transform=p.evidence_scale) nengo.Connection(memory.ensembles[1], compare[0], transform=-p.evidence_scale) # create inhibitory gates to control the two reporting systems report_gate_f = nengo.Ensemble(50, 1, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform( 0.1, 0.9), label='report gate f') report_gate_c = nengo.Ensemble(50, 1, encoders=nengo.dists.Choice([[1]]), intercepts=nengo.dists.Uniform( 0.1, 0.9), label='report gate c') nengo.Connection(report_finger, report_gate_f, transform=-10) nengo.Connection(report_compare, report_gate_c, transform=-10) report_bias = nengo.Node([1], label='bias') nengo.Connection(report_bias, report_gate_f) nengo.Connection(report_bias, report_gate_c) nengo.Connection(report_gate_c, compare.neurons, transform=[[-100.0]] * p.N_compare, synapse=0.01) for i in range(p.pointer_count): nengo.Connection(report_gate_f, report.ensembles[i].neurons, transform=[[-100.0]] * p.N_report, synapse=0.01) nengo.Connection(report_gate_f, reported.ensembles[i].neurons, transform=[[-100.0]] * p.N_report, synapse=0.01) for ens in memory.all_ensembles + [compare]: nengo.Connection(memory_clear, ens.neurons, transform=[[-10]] * ens.n_neurons, synapse=0.01) self.p_report = nengo.Probe(report.output, synapse=0.01) self.p_compare = nengo.Probe(compare, synapse=0.01) self.p_memory = nengo.Probe(memory.output, synapse=0.01) if p.backend == 'nengo_spinnaker': import nengo_spinnaker nengo_spinnaker.add_spinnaker_params(model.config) for node in model.all_nodes: if callable(node.output): if not hasattr(node.output, '_nengo_html_'): model.config[node].function_of_time = True return model