def test_SpikeSourceArray(self):
     spike_times = [50.]
     p = sim.Population(3, sim.SpikeSourceArray(spike_times=spike_times))
     p2 = sim.Population(3, sim.Hardware_IF_cond_exp())
     syn = sim.StaticSynapse(weight=0.012)
     con = sim.Projection(p,
                          p2,
                          connector=sim.OneToOneConnector(),
                          synapse_type=syn,
                          receptor_type='excitatory')
     spike_times_g = p.get('spike_times')
     p2.record('v')
     sim.run(100.0)
     weights = nan_to_num(con.get('weight', format="array"))
     print weights
     data = p2.get_data().segments[0]
     vm = data.filter(name="v")[0]
     print vm
     Figure(
         Panel(weights,
               data_labels=["ext->cell"],
               line_properties=[{
                   'xticks': True,
                   'yticks': True,
                   'cmap': 'Greys'
               }]),
         Panel(vm,
               ylabel="Membrane potential (mV)",
               data_labels=["excitatory", "excitatory"],
               line_properties=[{
                   'xticks': True,
                   'yticks': True
               }]),
     ).save("result")
    def run_experiment(self, weight_distortion=None):
        import pyNN.hardware.brainscales as pynn
        setup_params = dict(
            useSystemSim=True,
            ignoreDatabase=True,
            ignoreHWParameterRanges=True,
            hardware=pynn.hardwareSetup["one-hicann"],
            rng_seeds=[123567],
        )

        if weight_distortion is not None:
            setup_params['ess_params'] = {
                'weightDistortion': weight_distortion
            }

        pynn.setup(**setup_params)
        num_neurons = 2
        pop = pynn.Population(num_neurons, pynn.IF_cond_exp)
        # two different input spike trains, with identical rate but shifted to avoid loss in merger tree
        spike_times1 = np.arange(100., 500, 10.)
        spike_times2 = np.arange(105., 505, 10.)
        pop_source = pynn.Population(2, pynn.SpikeSourceArray)
        pop_source.tset('spike_times', [spike_times1, spike_times2])

        weight = 0.1  # weight = pop[0].cell.getConductanceRange("weight")[1]
        conn = pynn.OneToOneConnector(weights=weight)
        proj_0 = pynn.Projection(pop_source, pop, conn)

        pop.record()
        pynn.run(600.)

        spikes = pop.getSpikes()
        spikes_nrn_0 = spikes[spikes[:, 0] == 0, 1]
        spikes_nrn_1 = spikes[spikes[:, 0] == 1, 1]

        pynn.end()
        return len(spikes_nrn_0), len(spikes_nrn_1)
    def runTest(self):
        import pyNN.hardware.brainscales as pynn
        from pyNN.hardware.brainscales import mapper
        import os

        place = mapper.place()

        current_directory = os.path.dirname(os.path.realpath(__file__))
        pynn.setup(timestep=0.1,
                useSystemSim = True,
                algoinitFilename= current_directory + "/algoinit_l1_delay.pl",
                mappingStrategy="user",
                loglevel=2,
                hardware=[dict(setup="wafer", wafer_id=0,hicannIndices=[279,280])],
                hardwareNeuronSize=1,
                logfile='logfile.txt',
                speedupFactor=10000,
                rng_seeds=[123567],
                ignoreHWParameterRanges=True,
                ignoreDatabase=True,
                tempFolder="debug_l1_delay",
                )
        LIF_nrn_params = {
         'cm': 1.0,
         'e_rev_E': 0.0,
         'e_rev_I': -70.0,
         'i_offset': 0.0,
         'tau_m': 20.0,
         'tau_refrac': 5., # high value to avoid 2nd spike
         'tau_syn_E': 5.0,
         'tau_syn_I': 5.0,
         'v_reset': -65.0,
         'v_rest': -65.0,
         'v_thresh': -60.0} # low value for 1 spike

        num_pe = 8 # number of priority encoders
        pop_1 = pynn.Population(num_pe, pynn.IF_cond_exp, LIF_nrn_params)
        pop_2 = pynn.Population(num_pe, pynn.IF_cond_exp, LIF_nrn_params)
        pop_source = pynn.Population(num_pe, pynn.SpikeSourceArray)

        spike_times = [[i*10. + 10.] for i in range(num_pe)]
        pop_source.tset('spike_times',spike_times)
        weight = 0.05
        conn = pynn.OneToOneConnector(weight,0.1)
        proj_0=pynn.Projection(pop_source,pop_1, conn)
        proj_1=pynn.Projection(pop_1,pop_2, conn)
        for i in range(num_pe):
            place.to(pop_1[i], hicann=279, neuron=32*i)
            place.to(pop_2[i], hicann=279, neuron=32*i +1)
        place.commit()

        pop_1.record()
        pop_2.record()

        pynn.run(100.)

        spikes_1 = pop_1.getSpikes()
        spikes_2 = pop_2.getSpikes()
        self.assertEqual(8,len(spikes_1))
        self.assertEqual(8,len(spikes_2))

        # sort spikes by ID:
        spikes_1.sort()
        spikes_2.sort()
        # spiketimes only
        spikes_1 = spikes_1[:,(1,)]
        spikes_2 = spikes_2[:,(1,)]
        delays = spikes_2 - spikes_1

        # delay pe 1 > 0, 2, 4, 7
        self.assertTrue(delays[1] > delays[0])
        self.assertTrue(delays[1] > delays[2])
        self.assertTrue(delays[1] > delays[4])
        self.assertTrue(delays[1] > delays[7])

        # delay pe 6 > 0, 2, 4, 7
        self.assertTrue(delays[6] > delays[0])
        self.assertTrue(delays[6] > delays[2])
        self.assertTrue(delays[6] > delays[4])
        self.assertTrue(delays[6] > delays[7])

        # delay pe 5 > than everything expect 3
        self.assertTrue(delays[5] > delays[0])
        self.assertTrue(delays[5] > delays[1])
        self.assertTrue(delays[5] > delays[2])
        self.assertTrue(delays[5] > delays[4])
        self.assertTrue(delays[5] > delays[6])
        self.assertTrue(delays[5] > delays[7])

        # delay pe 3 > than everything
        self.assertTrue(delays[3] > delays[0])
        self.assertTrue(delays[3] > delays[1])
        self.assertTrue(delays[3] > delays[2])
        self.assertTrue(delays[3] > delays[4])
        self.assertTrue(delays[3] > delays[5])
        self.assertTrue(delays[3] > delays[6])
        self.assertTrue(delays[3] > delays[7])
    def runTest(self):
        import numpy
        backend = "hardware.brainscales"

        import pyNN.hardware.brainscales as pynn


        # set-up the simulator
        pynn.setup(
                timestep=0.1,
                useSystemSim=True,
                speedupFactor=8000,
                ignoreDatabase=True,
                ignoreHWParameterRanges=True,
                hardware=pynn.hardwareSetup['one-hicann'],
                )

        neuron_count = 1 # size of the Population we will create

        # Set the neuron model class
        neuron_model = pynn.EIF_cond_exp_isfa_ista # an Adaptive Exponential I&F Neuron

        neuron_parameters = {
         'a'          : 10.0,    # adaptation variable a in nS
         'b'          : 0.0805, # adaptation variable b in pA
         'cm'         : 0.281,  # membrane capacitance nF
         'delta_T'    : 2.0,    # delta_T fom Adex mod in mV, determines the sharpness of spike initiation
         'e_rev_E'    : 0.0,    # excitatory reversal potential in mV
         'e_rev_I'    : -100.0,  # inhibitory reversal potential in mV
         'i_offset'   : 0.0,    # offset current
         'tau_m'      : 9.3667, # membrane time constant
         'tau_refrac' : 8.0,    # absolute refractory period
         'tau_syn_E'  : 5.0,    # excitatory synaptic time constant
         'tau_syn_I'  : 5.0,    # inhibitory synaptic time constant
         'tau_w'      : 144.0,  # adaptation time constant
         'v_reset'    : -70.6,  # reset potential in mV
         'v_rest'     : -70.6,  # resting potential in mV
         'v_spike'    : -40.0,  # spike detection voltage in mV
         'v_thresh'   : -66.9,  # spike initiaton threshold voltage in mV
         }

        # We create a Population with 1 neuron of our 
        N1 = pynn.Population( size = 1, cellclass = neuron_model, cellparams = neuron_parameters)
        N1.initialize('v',neuron_parameters['v_rest'])

        spiketimes = numpy.arange(100.,800.,0.5)
        S1 = pynn.Population(1,pynn.SpikeSourceArray, cellparams = {'spike_times':spiketimes})

        pynn.Projection(S1,N1,pynn.OneToOneConnector(weights=0.0123938304114), target='inhibitory') # max weight in hardware


        # record the spikes of all neurons of the population
        N1.record()

        # run the simulation for 500 ms
        pynn.run(1000.)


        num_spikes = 0
        # After the simulation, we get Spikes and save the voltage trace to a file
        spike_times = N1.getSpikes()
        for pair in spike_times:
            print "Neuron ", int(pair[0]), " spiked at ", pair[1]
            num_spikes += 1

        pynn.end()

        self.assertEqual(int(num_spikes),1,'The Neuron spiked more than once, i.e. there was a rebound burst, and not a single rebound spike as it should be')