Exemplo n.º 1
0
 def setupSpikeReceiver(self, network=None):
     print "\tSetting up Spike Receiver..."
     networkLabels = []
     for pop in network:
         ExternalDevices.activate_live_output_for(pop[1], database_notify_host="localhost", database_notify_port_num=19996)
         networkLabels.append(pop[1].label)
        
     liveConnection = SpynnakerLiveSpikesConnection(receive_labels=networkLabels, local_port=19996, send_labels=None)   
     
     for label in networkLabels:
         liveConnection.add_receive_callback(label, self.plotReceivedSpike)    
Exemplo n.º 2
0
def setupSpikeReceiver(network=None):
    print "Setting up Spike Receiver..."
    networkLabels = []
    for pop in network:
        ExternalDevices.activate_live_output_for(pop[1], database_notify_host="localhost", database_notify_port_num=19996, board_address='10.162.177.122')
        networkLabels.append(pop[1].label)
        
    if not useCVisualiser:
        liveConnection = SpynnakerLiveSpikesConnection(receive_labels=networkLabels, local_port=19996, send_labels=None)   
    
    for label in networkLabels:
        liveConnection.add_receive_callback(label, receiveSpike)    
    return liveConnection       
Exemplo n.º 3
0
def setupVisualiser(network=None, retinaLeft=None, retinaRight=None):
    
    
    print "Setting up Visualiser..."
    global retinaThreads, disparityThread, logFile
    
    logFile = open("dipsarities.txt", 'w')
    
    print "\tSetting up Spike Receiver..."
    networkLabels = []
    for pop in network:
        ExternalDevices.activate_live_output_for(pop[1], database_notify_host="localhost", database_notify_port_num=19996)
        networkLabels.append(pop[1].label)
    
    liveConnection_receiver = SpynnakerLiveSpikesConnection(receive_labels=networkLabels, local_port=19996, send_labels=None) 
    
    disparityThread = spike_plotter()
    
    for label in networkLabels:
        liveConnection_receiver.add_receive_callback(label, disparityThread.plotReceivedSpike)
    
    disparityThread.start()
    
    print "\tSetting up Spike Injectors for Retina Left and Retina Right..."            
    retinaLabels = []
    for popL, popR in zip(retinaLeft, retinaRight):
        retinaLabels.append(popL[1].label)
        retinaLabels.append(popR[1].label)
      
    liveConnection_sender = SpynnakerLiveSpikesConnection(receive_labels=None, local_port=19999, send_labels=retinaLabels)
    bg_col=pygame.Color(230,230,230,0)
    on_col=pygame.Color(10,220,10,0)
    off_col=pygame.Color(220,10,10,0)
    retinaThreads[ports[0]] = dvs_reader(port=ports[0], colors = {"bg": bg_col, "on": on_col, "off": off_col}, label="RetL", liveConnection=liveConnection_sender)
    retinaThreads[ports[1]] = dvs_reader(port=ports[1], colors = {"bg": bg_col, "on": on_col, "off": off_col}, label="RetR", liveConnection=liveConnection_sender)
     
    liveConnection_sender.add_start_callback(retinaLabels[0], startInjecting)
    
    panelsDrawer = Thread(target=setupPanels)
    panelsDrawer.start()
class _ROS_Spinnaker_Interface(object):

    """
    Transform incoming ROS Messages into spikes and inject them into the Spinnaker Board and the other way round.

a
    Args:
b
    n_neurons_source (int):  The number of neurons of the Spike Source.

    transfer_function_send (function handle): A handle to the transfer function used to convert
        the ROS input data into spikes.
    
    transfer_function_recv (function handle): A handle to the transfer function used to convert
        the live spikes to a ROS value.
    
    output_population (pynn.Population): The pyNN.Population you want to get the live spikes from.
        Defaults to None, so the live output is disabled.

    ros_topic_send (str): The ROS Topic used for sending into spinnaker.
        Defaults to "to_spinnaker".

    ros_topic_recv (str): The ROS Topic used for sending into ROS.
        Defaults to "from_spinnaker".

    clk_rate (int): The frequency the ROS Node is running with in Hz.
        Defaults to 1000 Hz.
    
    ros_output_rate (int): The frequency with which ros messages are sent out.
        Defaults to 10 Hz.

    benchmark (bool): Receive a timing output at the end of the simulation.
        Defaults to False.


    Attributes:

    InjectorPopulation: The ExternalDevices.SpikeInjector instance which is used internally.


    Functions:
        
        is_roscore_running(): True if the ros core is runnig else False.

        activate_live_output_for(pynn.Population): Set the pynn population you want to get the live spikes from.

        add_simulation_start_callback(function): Register the function as callback at simulation start.


    Examples:
        Have a look at the ros_spinnaker_interface_example.py or other example scripts.

    Notes:
        This interface uses the Spinnaker LiveSpikesConnection internally with the local ports
        19999 and 17895 and the spinnaker port 12345. These ports are widely used for live spikes and
        therefore should'nt cause any problems, however you can also simply change them in the constructor if needed.
        For each parallel interface used, these port numbers are increased by one, so the second interface will use
        the local ports 20000 and 17896 and 12346 on spinnaker, etc.

        If you want to change or extend this interface, consider that there is a sub process started by the 
        interface itself, as well as a thread controlled by spinnaker. Make sure they terminate and communicate properly.

        Currently only the std_msgs.msg.Int64 type is supported for ROS Messages. If you want to use your own
        ros message types it is possible, but you need to change some code yourself:
            - in the _incoming_ros_package_callback unpack the ros message fields and decide what to do with it.
            - in run_ros_node adjust the Publisher and Subscriber message types and (if needed) the publisher callback.
    """


    _instance_counter = count(0)


    def __init__(self,
            n_neurons_source=None,
            Spike_Source_Class=None,
            Spike_Sink_Class=None,
            output_population=None,
            ros_topic_send='to_spinnaker',
            ros_topic_recv='from_spinnaker',
            clk_rate=1000,
            ros_output_rate=10,
            benchmark=False):

        # Members
        self.n_neurons = n_neurons_source if n_neurons_source is not None else 1
        self._Spike_Source_Class = Spike_Source_Class
        self._Spike_Sink_Class = Spike_Sink_Class

        self.interface_id = self._instance_counter.next()

        self._output_population = output_population


        self.send_topic = ros_topic_send
        self.recv_topic = ros_topic_recv
        self._clk_rate = clk_rate  # in Hz
        self._ros_output_rate = ros_output_rate  # Hz
        self._benchmark = benchmark

        

        self._injector_label = 'injector{}'.format(self.interface_id)
        spike_injector_port = 12345 + self.interface_id
        local_port = 19999 + self.interface_id
        local_recv_port = 17895
        self._database_notify_port = local_port

        self._queue_ros_spinnaker = Queue()
        self._queue_spinnaker_ros = Queue()

        # My own "population" data structures to send and receive spikes, initialized later.
        self._spike_source = None
        self._spike_sink = None

        send_labels = [self._injector_label]
        rcv_labels = None

        self.sender_active = n_neurons_source is not None and self._Spike_Source_Class is not None
        self.receiver_active = self._output_population is not None and self._Spike_Sink_Class is not None

        if self.receiver_active:
            rcv_labels = [self._output_population.label]

        self._spike_injector_population = pynn.Population(size=self.n_neurons,
                                                          cellclass=ExternalDevices.SpikeInjector,
                                                          cellparams={'port': spike_injector_port,
                                                                      'database_notify_port_num':local_port},
                                                          label=self._injector_label)

        self._spinnaker_connection = LiveSpikesConnection(receive_labels=rcv_labels,
                                                          local_port=local_port,
                                                          send_labels=send_labels)

        self._spinnaker_connection.add_start_callback(self._injector_label, self._init_ros_node)  # spinnaker thread!

        if self.receiver_active:
            self._spinnaker_connection.add_receive_callback(self._output_population.label, self._incoming_spike_callback)

            ExternalDevices.activate_live_output_for(self._output_population,
                                                     port=local_recv_port+self.interface_id,
                                                     database_notify_port_num=self._database_notify_port)

    def _init_ros_node(self, label, sender):
        """
        Initialize the spike source and start the ros node.
        
        This is started as thread from the spinnaker LiveSpikesConnection at the beginning of the simulation.
        """
        timestep = 1.0 / self._clk_rate * 1000

        #if the readout population consists of more than one neuron -> set the readout_pop flag
        if self._output_population.size > 1:
            self._readout_pop_flag = True
            print('**********readout_flag_activated*************'.format(self.interface_id))
        

        if self.sender_active:
            self._spike_source = self._Spike_Source_Class(self.n_neurons,
                                                          label,
                                                          sender,
                                                          self._queue_ros_spinnaker,
                                                          timestep)

        if self.receiver_active:
            self._spike_sink = self._Spike_Sink_Class(len(self._output_population),  # get number of neurons
                                                      self._queue_spinnaker_ros,
                                                      timestep)

        if not self.is_roscore_running():
            sys.exit(0)

        p = Process(target=self.run_ros_node)
        p.daemon = True
        print("Interface {} started".format(self.interface_id))
        p.start()

    def run_ros_node(self):
        """
        Initialize a ROS Node and subscribe and publish to the given ROS Topics.

        ROS requires this function to run in its own child process.

        The tick generator makes sure that it runs once per timestep.
        """
        rospy.init_node('spinnaker_ros_interface{}'.format(self.interface_id), anonymous=True)

        if self._readout_pop_flag:
            if self.receiver_active:
                publisher = rospy.Publisher(self.recv_topic, Pop_List, queue_size=10)
            if self.sender_active:
                rospy.Subscriber(self.send_topic, Int64, self._incoming_ros_package_callback)
        else:
            if self.receiver_active:
                publisher = rospy.Publisher(self.recv_topic, Int64, queue_size=10)
            if self.sender_active:
                rospy.Subscriber(self.send_topic, Int64, self._incoming_ros_package_callback)

        rospy.on_shutdown(self.on_ros_node_shutdown)

        def ros_publisher_callback(event):
            if not self.receiver_active:
                return
            try:
                publisher.publish(self._spike_sink._get_ros_value())
            except rospy.ROSException:
                return

        rospy.Timer(rospy.Duration(1.0 / self._ros_output_rate), ros_publisher_callback)  # 10 Hz default
        
        ros_timer = rospy.Rate(self._clk_rate)
        
        self.interface_start_time = time.time()

        if self._benchmark:
            last = time.clock()
            self._num_timer_warnings = 0
            self._num_ticks = 0
            self._mainloop_execution_times = []
        
        while not rospy.is_shutdown():
            if self.sender_active:
                self._spike_source._update()
            if self.receiver_active:
                self._spike_sink._update()
            
            # Count if the mainloop execution takes too long
            if self._benchmark:
                self._num_ticks += 1
                now = time.clock()
                self._mainloop_execution_times.append(now - last)
                if (now - last) > (1.0 / self._clk_rate):
                    self._num_timer_warnings += 1
                last = now

            ros_timer.sleep()
        
    def _incoming_ros_package_callback(self, ros_msg):
        """
        Callback for the incoming data. Forwards the data via UDP to the Spinnaker Board.
        """
        self._queue_ros_spinnaker.put(ros_msg.data)  # data is the name of the ros std_msgs data field.

    def _incoming_spike_callback(self, label, time, neuron_ids):
        """
        Call this callback to process incoming live spikes.
        """
        for neuron_id in neuron_ids:
            spike = (label, time, neuron_id)
            self._queue_spinnaker_ros.put(spike)

    def is_roscore_running(self):
        """
        Returns True if the ROS Core is running and False otherwise.
        """
        return True  # TODO
        try:
            _, _, ros_master_pid = rospy.get_master().getPid()
            return True

        except socket.error:
            print('\n\n[!] Cannot communicate with ROS Master. Please check if ROS Core is running.\n\n')
            return False
    
    @property
    def InjectorPopulation(self):
        """
        The handle to the ExternalDevices.SpikeInjector which is used internally.
        Can be used for pynn.Connectors
        """
        return self._spike_injector_population if self.sender_active else None

    def __str__(self):
        return 'ROS-Spinnaker-Interface'

    def __repr__(self):
        return self._spike_injector_population
    
    def on_ros_node_shutdown(self):
        # These do nothing on default. The plot functions need to be redefined in the SpikeSink/Source used to
        # actually do something.

        if self._benchmark:
            lock.acquire()
            print("Interface {} Benchmark".format(self.interface_id))
            # print("startet running on time {}".format(self.interface_start_time))
            # print("stopped runnning on time {}".format(time.time()))
            print("Number of times the mainloop took too long: {}".format(self._num_timer_warnings))
            print("Number of Mainloop Calls: {}".format(self._num_ticks))
            import numpy as np
            mean_execution_time = np.mean(self._mainloop_execution_times)
            print("Mean Mainloop Execution Time: {} ms, (max {} ms)".format(mean_execution_time, 1.0 / self._clk_rate))
            print("Highest possible interface clock rate: {} Hz\n".format(1.0 / mean_execution_time))
            lock.release()

        if self.sender_active:
            self._spike_source.plot()
        if self.receiver_active:
            self._spike_sink.plot()
    
    def add_simulation_start_callback(self, function):
        if self.sender_active:
            self._spinnaker_connection.add_start_callback(self._injector_label, function)
# Create a receiver of live spikes
def receive_spikes(label, time, neuron_ids):
    for neuron_id in neuron_ids:
        print "Received spike at time", time, "from", label, "-", neuron_id
# Set up the live connection for sending spikes
live_spikes_connection = SpynnakerLiveSpikesConnection(
    receive_labels=None, local_port=19999, send_labels=["spike_injector_forward"])
# Set up callbacks to occur at the start of simulation
live_spikes_connection.add_start_callback("spike_injector_forward", send_input_forward)
# if not using the c visualiser, then a new spynnaker live spikes connection
# is created to define that there are python code which receives the
# outputted spikes.
live_spikes_connection = SpynnakerLiveSpikesConnection(
    receive_labels=["pop_forward"], local_port=19996, send_labels=None)
# Set up callbacks to occur when spikes are received
live_spikes_connection.add_receive_callback("pop_forward", receive_spikes)
# Run the simulation on spiNNaker
Frontend.run(run_time)
# Retrieve spikes from the synfire chain population
spikes_forward = pop_forward.getSpikes()
# If there are spikes, plot using matplotlib
if len(spikes_forward) != 0:
    pylab.figure()
    if len(spikes_forward) != 0:
        pylab.plot([i[1] for i in spikes_forward],
                   [i[0] for i in spikes_forward], "b.")
    pylab.ylabel('neuron id')
    pylab.xlabel('Time/ms')
    pylab.title('spikes')
    pylab.show()
else:
Exemplo n.º 6
0
live_spikes_connection_send = SpynnakerLiveSpikesConnection(
    receive_labels=None, local_port=19999,
    send_labels=["spike_injector"])



# Set up callbacks to occur at initialisation
live_spikes_connection_send.add_init_callback(
    "spike_injector", init_pop)



live_spikes_connection_receive = SpynnakerLiveSpikesConnection(
	receive_labels=["pop"],
	local_port=19996, send_labels=None)



# Set up callbacks to occur when spikes are received
live_spikes_connection_receive.add_receive_callback(
	"pop", receive_spikes)




def run():

  Frontend.run(run_time)

  Frontend.end()
Exemplo n.º 7
0
        if r == 1:  
            send_spike_retina("ret_right", liveConnectionRetina)
        else:
            send_spike_retina("ret_left", liveConnectionRetina)  
        time.sleep((tNext - t)/1000.0)
         
def init_thread(label, sender):
    if label == "ret_left":
        sender_thread = Thread(target=threadLeft_run, args=(sender,))
        sender_thread.start()
    else:
        sender_thread = Thread(target=threadRight_run, args=(sender,))
        sender_thread.start()  
     
live_spikes_connection_receiver = SpynnakerLiveSpikesConnection(receive_labels=["collector", "inh_left", "inh_right"], local_port=19996, send_labels=None)
live_spikes_connection_receiver.add_receive_callback("collector", receive_spike_cell)
live_spikes_connection_receiver.add_receive_callback("inh_left", receive_spike_cell)
live_spikes_connection_receiver.add_receive_callback("inh_right", receive_spike_cell)
 
live_spikes_connection_sender = SpynnakerLiveSpikesConnection(receive_labels=None, local_port=19999, send_labels=["ret_right", "ret_left"])
# Set up callbacks to occur at the start of simulation
# live_spikes_connection_sender.add_start_callback("ret_left", init_thread)
live_spikes_connection_sender.add_start_callback("ret_right", init_thread)
 
# Run the simulation on spiNNaker
 
Frontend.run(run_time)
# Retrieve spikes from the synfire chain population
spikes_collector = collector.getSpikes()
print "Spikes count collector: ", len(spikes_collector)
 
Exemplo n.º 8
0
live_spikes_connection_send.add_start_callback("spike_injector_forward",
                                               send_input_forward)
live_spikes_connection_send.add_start_callback("spike_injector_backward",
                                               send_input_backward)

if not using_c_vis:
    # if not using the c visualiser, then a new spynnaker live spikes connection
    # is created to define that there are python code which receives the
    # outputted spikes.
    live_spikes_connection_receive = SpynnakerLiveSpikesConnection(
        receive_labels=["pop_forward", "pop_backward"],
        local_port=19996,
        send_labels=None)

    # Set up callbacks to occur when spikes are received
    live_spikes_connection_receive.add_receive_callback(
        "pop_forward", receive_spikes)
    live_spikes_connection_receive.add_receive_callback(
        "pop_backward", receive_spikes)

# Run the simulation on spiNNaker
Frontend.run(run_time)

# Retrieve spikes from the synfire chain population
spikes_forward = pop_forward.getSpikes()
spikes_backward = pop_backward.getSpikes()

# If there are spikes, plot using matplotlib
if len(spikes_forward) != 0 or len(spikes_backward) != 0:
    pylab.figure()
    if len(spikes_forward) != 0:
        pylab.plot([i[1] for i in spikes_forward],
    def __init__(self):

        # initial call to set up the front end (pynn requirement)
        Frontend.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)

        use_c_visualiser = True
        use_spike_injector = True

        # neurons per population and the length of runtime in ms for the
        # simulation, as well as the expected weight each spike will contain
        self.n_neurons = 100

        # set up gui
        p = None
        if use_spike_injector:
            from multiprocessing import Process
            from multiprocessing import Event
            ready = Event()
            p = Process(target=GUI, args=[self.n_neurons, ready])
            p.start()
            ready.wait()

        # different runtimes for demostration purposes
        run_time = None
        if not use_c_visualiser and not use_spike_injector:
            run_time = 1000
        elif use_c_visualiser and not use_spike_injector:
            run_time = 10000
        elif use_c_visualiser and use_spike_injector:
            run_time = 100000
        elif not use_c_visualiser and use_spike_injector:
            run_time = 10000

        weight_to_spike = 2.0

        # neural parameters of the IF_curr model used to respond to injected
        # spikes.
        # (cell params for a synfire chain)
        cell_params_lif = {'cm': 0.25,
                           'i_offset': 0.0,
                           'tau_m': 20.0,
                           'tau_refrac': 2.0,
                           'tau_syn_E': 5.0,
                           'tau_syn_I': 5.0,
                           'v_reset': -70.0,
                           'v_rest': -65.0,
                           'v_thresh': -50.0
                           }

        ##################################
        # Parameters for the injector population.  This is the minimal set of
        # parameters required, which is for a set of spikes where the key is
        # not important.  Note that a virtual key *will* be assigned to the
        # population, and that spikes sent which do not match this virtual key
        # will be dropped; however, if spikes are sent using 16-bit keys, they
        # will automatically be made to match the virtual key.  The virtual
        # key assigned can be obtained from the database.
        ##################################
        cell_params_spike_injector = {

            # The port on which the spiNNaker machine should listen for
            # packets. Packets to be injected should be sent to this port on
            # the spiNNaker machine
            'port': 12345
        }

        ##################################
        # Parameters for the injector population.  Note that each injector
        # needs to be given a different port.  The virtual key is assigned
        # here, rather than being allocated later.  As with the above, spikes
        # injected need to match this key, and this will be done automatically
        # with 16-bit keys.
        ##################################
        cell_params_spike_injector_with_key = {

            # The port on which the spiNNaker machine should listen for
            # packets. Packets to be injected should be sent to this port on
            # the spiNNaker machine
            'port': 12346,

            # This is the base key to be used for the injection, which is used
            # to allow the keys to be routed around the spiNNaker machine.
            # This assignment means that 32-bit keys must have the high-order
            # 16-bit set to 0x7; This will automatically be prepended to
            # 16-bit keys.
            'virtual_key': 0x70000
        }

        # create synfire populations (if cur exp)
        pop_forward = Frontend.Population(
            self.n_neurons, Frontend.IF_curr_exp,
            cell_params_lif, label='pop_forward')
        pop_backward = Frontend.Population(
            self.n_neurons, Frontend.IF_curr_exp,
            cell_params_lif, label='pop_backward')

        # Create injection populations
        injector_forward = None
        injector_backward = None
        if use_spike_injector:
            injector_forward = Frontend.Population(
                self.n_neurons, ExternalDevices.SpikeInjector,
                cell_params_spike_injector_with_key,
                label='spike_injector_forward')
            injector_backward = Frontend.Population(
                self.n_neurons, ExternalDevices.SpikeInjector,
                cell_params_spike_injector, label='spike_injector_backward')
        else:
            spike_times = []
            for _ in range(0, self.n_neurons):
                spike_times.append([])
            spike_times[0] = [0]
            spike_times[20] = [(run_time / 100) * 20]
            spike_times[40] = [(run_time / 100) * 40]
            spike_times[60] = [(run_time / 100) * 60]
            spike_times[80] = [(run_time / 100) * 80]
            cell_params_forward = {'spike_times': spike_times}
            spike_times_backwards = []
            for _ in range(0, self.n_neurons):
                spike_times_backwards.append([])
            spike_times_backwards[0] = [(run_time / 100) * 80]
            spike_times_backwards[20] = [(run_time / 100) * 60]
            spike_times_backwards[40] = [(run_time / 100) * 40]
            spike_times_backwards[60] = [(run_time / 100) * 20]
            spike_times_backwards[80] = [0]
            cell_params_backward = {'spike_times': spike_times_backwards}
            injector_forward = Frontend.Population(
                self.n_neurons, Frontend.SpikeSourceArray,
                cell_params_forward,
                label='spike_injector_forward')
            injector_backward = Frontend.Population(
                self.n_neurons, Frontend.SpikeSourceArray,
                cell_params_backward, label='spike_injector_backward')

        # Create a connection from the injector into the populations
        Frontend.Projection(
            injector_forward, pop_forward,
            Frontend.OneToOneConnector(weights=weight_to_spike))
        Frontend.Projection(
            injector_backward, pop_backward,
            Frontend.OneToOneConnector(weights=weight_to_spike))

        # Synfire chain connections where each neuron is connected to its next
        # neuron
        # NOTE: there is no recurrent connection so that each chain stops once
        # it reaches the end
        loop_forward = list()
        loop_backward = list()
        for i in range(0, self.n_neurons - 1):
            loop_forward.append((i, (i + 1) %
                                 self.n_neurons, weight_to_spike, 3))
            loop_backward.append(((i + 1) %
                                  self.n_neurons, i, weight_to_spike, 3))
        Frontend.Projection(pop_forward, pop_forward,
                            Frontend.FromListConnector(loop_forward))
        Frontend.Projection(pop_backward, pop_backward,
                            Frontend.FromListConnector(loop_backward))

        # record spikes from the synfire chains so that we can read off valid
        # results in a safe way afterwards, and verify the behavior
        pop_forward.record()
        pop_backward.record()

        # Activate the sending of live spikes
        ExternalDevices.activate_live_output_for(
            pop_forward, database_notify_host="localhost",
            database_notify_port_num=19996)
        ExternalDevices.activate_live_output_for(
            pop_backward, database_notify_host="localhost",
            database_notify_port_num=19996)

        if not use_c_visualiser:
            # if not using the c visualiser, then a new spynnaker live spikes
            # connection is created to define that there are python code which
            # receives the outputted spikes.
            live_spikes_connection_receive = SpynnakerLiveSpikesConnection(
                receive_labels=["pop_forward", "pop_backward"],
                local_port=19999, send_labels=None)

            # Set up callbacks to occur when spikes are received
            live_spikes_connection_receive.add_receive_callback(
                "pop_forward", receive_spikes)
            live_spikes_connection_receive.add_receive_callback(
                "pop_backward", receive_spikes)
        # Run the simulation on spiNNaker
        Frontend.run(run_time)

        # Retrieve spikes from the synfire chain population
        spikes_forward = pop_forward.getSpikes()
        spikes_backward = pop_backward.getSpikes()

        # If there are spikes, plot using matplotlib
        if len(spikes_forward) != 0 or len(spikes_backward) != 0:
            pylab.figure()
            if len(spikes_forward) != 0:
                pylab.plot([i[1] for i in spikes_forward],
                           [i[0] for i in spikes_forward], "b.")
            if len(spikes_backward) != 0:
                pylab.plot([i[1] for i in spikes_backward],
                           [i[0] for i in spikes_backward], "r.")
            pylab.ylabel('neuron id')
            pylab.xlabel('Time/ms')
            pylab.title('spikes')
            pylab.show()
        else:
            print "No spikes received"

        # Clear data structures on spiNNaker to leave the machine in a clean
        # state for future executions
        Frontend.end()
        if use_spike_injector:
            p.join()
Exemplo n.º 10
0
sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0)

# echo population ----------------------------------------------------------
target = sim.Population(num_neurons, model, cell_params, label="echo")

target.record()

ExternalDevices.activate_live_output_for(target, 
                                         database_notify_host="localhost",
                                         database_notify_port_num=live_out_port)

live_spikes_receive = SpynnakerLiveSpikesConnection(receive_labels=["echo",],
                                                    local_port=receive_port, 
                                                    send_labels=None)

live_spikes_receive.add_receive_callback("echo", receive_spikes)

# END: echo population ----------------------------------------------------------


# stim population ----------------------------------------------------------
stimulation = sim.Population(num_neurons, ImageDvsEmulatorDevice, cam_params,
                             label="Webcam population")

# END: stim population ----------------------------------------------------------


# connections ----------------------------------------------------------
connector = sim.OneToOneConnector(weights=weight_to_spike)

projection = sim.Projection(stimulation, target, connector)
Exemplo n.º 11
0
    Frontend.Projection(source[pop], collector[pop], Frontend.OneToOneConnector(weights=22, delays=0.2), target='excitatory') 
    collector[pop].record()
    counter_received_spikes.append(0)
    collector_labels.append('{0}'.format(pop))

def receive_spike_cell(label, time, neuron_ids):
    if time < 5050 :
        counter_received_spikes[int(label)] += len(neuron_ids) 

for col in collector:     
    ExternalDevices.activate_live_output_for(col, database_notify_host="localhost",database_notify_port_num=19996)
    
live_spikes_connection_receiver = SpynnakerLiveSpikesConnection(receive_labels=collector_labels, local_port=19996, send_labels=None)

for label in collector_labels:
    live_spikes_connection_receiver.add_receive_callback(label, receive_spike_cell)


Frontend.run(run_time)

total_spikes_count = 0
for col in collector:
    total_spikes_count += len(col.getSpikes())

print "Spikes count collector:", total_spikes_count
print "Spikes count received:", sum(counter_received_spikes)

Frontend.end()


    
        if neuron_id == 0 and label== "pop_backward_parrot":
            live_spikes_connection.send_spike("spike_injector_forward", 0)
        elif neuron_id == 99 and label== "pop_forward_parrot":
            live_spikes_connection.send_spike("spike_injector_forward", 1)
# Set up the live connection for sending spikes
live_spikes_connection = SpynnakerLiveSpikesConnection(
    local_port=19996, send_labels=["spike_injector_forward"])
# Set up the live connection for sending spikes to closed loop
live_spikes_connection_receiver = SpynnakerLiveSpikesConnection(
    receive_labels=["pop_forward_parrot", "pop_backward_parrot"],
    local_port=19995)
# Set up callbacks to occur at the start of simulation
live_spikes_connection.add_start_callback("spike_injector_forward",
                                          send_input_forward)
# Set up callbacks to occur when spikes are received
live_spikes_connection_receiver.add_receive_callback("pop_forward_parrot", receive_spikes)
live_spikes_connection_receiver.add_receive_callback("pop_backward_parrot", receive_spikes)
# Run the simulation on spiNNaker
Frontend.run(run_time)

# Retrieve spikes from the synfire chain population
spikes_forward = pop_forward.getSpikes()
spikes_backward = pop_backward.getSpikes()
# If there are spikes, plot using matplotlib
if len(spikes_forward) != 0 or len(spikes_backward) != 0:
    pylab.figure()
    if len(spikes_forward) != 0:
        pylab.plot([i[1] for i in spikes_forward],
                   [i[0] for i in spikes_forward], "b.")
    if len(spikes_backward) != 0:
        pylab.plot([i[1] for i in spikes_backward],
Exemplo n.º 13
0
            sender.send_spike("med", n, send_full_keys=False)
            n += 1
        counter_sent += neuronCount
#             time.sleep(0.007)
    print time.time()
           

   
def init(label, sender):
    pass
    sender_thread = Thread(target=th_run, args=(sender,))
    sender_thread.start()  
     
ExternalDevices.activate_live_output_for(source, database_notify_host="localhost",database_notify_port_num=19996)
live_spikes_connection_receiver = SpynnakerLiveSpikesConnection(receive_labels=["src"], local_port=19996, send_labels=None)
live_spikes_connection_receiver.add_receive_callback("src", receive_spike_cell)

live_spikes_connection_sender = SpynnakerLiveSpikesConnection(receive_labels=None, local_port=19999, send_labels=["med"])
live_spikes_connection_sender.add_start_callback("med", init)

Frontend.run(run_time)
# Retrieve spikes from the synfire chain population

# print "Spikes count source:", len(source.getSpikes())
# print "Spikes count collector_ssa:", len(collector_ssa.getSpikes())
# print collector_ssa.getSpikes()[:20]
# print "Spikes count collector_inj:", len(collector_inj.getSpikes())

print counter_received, counter_sent
# print collector_inj.getSpikes()[:20]
# print source.getSpikes()