コード例 #1
0
ファイル: test_mem_calib.py プロジェクト: astoeckel/PyNN
    def getMem(self, voltageRest, mappingOffset, calibOutputPins,
               calibNeuronMems):
        import pyNN.hardware.spikey as pynn
        pynn.setup(useUsbAdc=True,
                   avoidSpikes=True,
                   mappingOffset=mappingOffset,
                   calibTauMem=False,
                   calibOutputPins=calibOutputPins,
                   calibNeuronMems=calibNeuronMems)

        neuron = pynn.Population(1, pynn.IF_facets_hardware1,
                                 self.neuronParams)
        #neuronDummy = pynn.Population(1, pynn.IF_facets_hardware1, self.neuronParams)
        neuron.set({'v_rest': voltageRest})
        #neuronDummy.set({'v_rest': self.voltageRange[0]})
        neuron.record()
        pynn.record_v(neuron[0], '')

        pynn.run(self.runtime)

        mem = pynn.membraneOutput
        spikes = neuron.getSpikes()

        pynn.end()

        self.assertTrue(
            (float(len(spikes)) / self.runtime * 1e3) <= self.limFreq,
            'there should not be any (too much) spikes')
        return mem.mean()
コード例 #2
0
        def getMemLoop():
            result = []

            pynn.setup(useUsbAdc=True)
            neuron = pynn.Population(noNeurons, pynn.IF_facets_hardware1)

            for j in range(noNeurons):
                if j % 2 == 0:
                    neuron[j].set_parameters(v_rest=vRestEven)
                else:
                    neuron[j].set_parameters(v_rest=vRestOdd)

            neuron.record()

            for i in range(noNeurons):
                pynn.record_v(neuron[i], '')

                pynn.run(runtime)

                mem = pynn.membraneOutput
                spikes = neuron.getSpikes()

                shutil.copy(spikeyconfigFilename,
                            spikeyconfigFilename + extListNo[i])
                self.assertTrue(
                    (float(len(spikes)) / runtime * 1e3) <= limFreq,
                    'there should not be any (too much) spikes')
                result.append([mem.mean(), mem.std()])

            pynn.end()

            return result
コード例 #3
0
    def record_tau(self, neuronNr, iLeak, v_rest=None):
        print 'now at neuron number', neuronNr

        # linear dependency of simulation time on 1/iLeak
        duration = 5.0*1000.0/float(iLeak)
        duration = np.min([duration, 50000.0])

        # initialize pyNN
        mappingOffset = neuronNr
        if self.chipVersion == 4:
            mappingOffset = neuronNr - 192
        p.setup(useUsbAdc=True, calibTauMem=False, calibVthresh=False, calibSynDrivers=False, calibIcb=False, mappingOffset=mappingOffset, workStationName=self.workstation)

        # set g_leak such that iLeak is the desired value
        iLeak_base = default.iLeak_base
        g_leak = float(iLeak)/iLeak_base

        # determine tau_mem, v_rest and v_reset all at once
        trials = 0
        params = deepcopy(self.neuronParams)
        params['g_leak'] = g_leak
        if v_rest != None:
            params['v_rest'] = v_rest

        neuron = p.Population(1, p.IF_facets_hardware1, params)
        neuron.record()
        p.record_v(neuron[0], '')

        crossedTargetRate = False
        while params['v_rest'] < self.maxVRest:
            print 'now at trial', trials, '/ v_rest =', params['v_rest']
            p.run(duration)
            trace = p.membraneOutput
            dig_spikes = neuron.getSpikes()[:,1]
            memtime = p.timeMembraneOutput
            timestep = memtime[1] - memtime[0]

            # if neuron spikes with too low rate, try again with higher resting potential
            if len(dig_spikes) < self.targetSpikes:
                params['v_rest'] = params['v_rest'] + self.vRestStep
                neuron.set(params)
                print 'Neuron spiked with too low rate, trying again with parameters', params
                trials += 1
            else: # proper spiking
                crossedTargetRate = True
                break

        if not crossedTargetRate:
            utils.report('Could not find parameters for which neuron {0} spikes. Will return nan tau_mem'.format(neuronNr), self.reportFile)
            return np.concatenate(([iLeak], [np.nan] * 6, [params['v_rest']]))

        p.end()

        # determine tau_mem from measurements
        result = utils.fit_tau_mem(trace, memtime, dig_spikes, timestep=timestep, reportFile=self.reportFile)
        if result == None: # fit failed
            utils.report('Fit of membrane time constant for neuron {0} failed (iLeak = {1})'.format(neuronNr, iLeak), self.reportFile)
            return np.concatenate(([iLeak], [np.nan] * 6, [params['v_rest']]))
        return np.concatenate(([iLeak], result, [params['v_rest']]))
コード例 #4
0
def compareSpikesToMembrane(duration):
    """
    Tests the precise timing of digital spikes and spikes extracted from the membrane potential.
    The neuron is stimulated with Poisson spike sources.
    """
    np.random.seed(int(time.time()))
    neuronNo = np.random.random_integers(0, 191)
    print 'Using neuron number', neuronNo

    poissonParams = {'start': 100.0, 'duration': duration -
                     100.0, 'rate': 30.0}  # offset of 100 ms to get all spikes
    weightExc = 4  # digital hardware value
    weightInh = 15  # digital hardware value
    freqLimit = 1.0  # 1/s
    meanLimit = 0.2  # ms
    stdLimit = 0.2  # ms

    import pyNN.hardware.spikey as pynn

    pynn.setup(mappingOffset=neuronNo)

    stimExc = pynn.Population(64, pynn.SpikeSourcePoisson, poissonParams)
    stimInh = pynn.Population(192, pynn.SpikeSourcePoisson, poissonParams)
    neuron = pynn.Population(1, pynn.IF_facets_hardware1)
    prj = pynn.Projection(stimExc, neuron, pynn.AllToAllConnector(
        weights=weightExc * pynn.minExcWeight()), target='excitatory')
    prj = pynn.Projection(stimInh, neuron, pynn.AllToAllConnector(
        weights=weightInh * pynn.minInhWeight()), target='inhibitory')

    neuron.record()
    pynn.record_v(neuron[0], '')

    pynn.run(duration)

    spikes = neuron.getSpikes()[:, 1]
    membrane = pynn.membraneOutput
    memTime = pynn.timeMembraneOutput
    spikesMem, deriv, thresh = spikesFromMem(memTime, membrane)

    pynn.end()

    #plot(memTime, membrane, spikes, spikesMem, deriv, thresh)

    print 'Spikes and spikes on membrane:', len(spikes), '/', len(spikesMem)
    assert len(spikes) / duration * 1e3 >= freqLimit, 'Too less spikes.'
    assert len(spikes) == len(spikesMem), 'Spikes do not match membrane.'
    spikesDiff = spikesMem - spikes
    spikesDiffMean = np.mean(spikesDiff)
    spikesDiffStd = np.std(spikesDiff)
    print 'Offset between spikes and membrane:', spikesDiffMean, '+-', spikesDiffStd
    assert spikesDiffMean < meanLimit, 'Spike and membrane have too large offset.'
    assert spikesDiffStd < stdLimit, 'Time axes of spikes and membrane are different.'
コード例 #5
0
ファイル: memory_leak.py プロジェクト: astoeckel/PyNN
def emulate():
    # pynn.setup(useUsbAdc=True)
    pynn.setup()
    stimI = pynn.Population(40, pynn.SpikeSourcePoisson, {
        'start': 0,
        'duration': runtime,
        'rate': rate
    })
    stimE = pynn.Population(20, pynn.SpikeSourcePoisson, {
        'start': 0,
        'duration': runtime,
        'rate': rate
    })
    neuron = pynn.Population(192, pynn.IF_facets_hardware1)
    prjI = pynn.Projection(stimI,
                           neuron,
                           pynn.AllToAllConnector(weights=weight *
                                                  pynn.minInhWeight()),
                           target='inhibitory')
    prjE = pynn.Projection(stimE,
                           neuron,
                           pynn.AllToAllConnector(weights=weight *
                                                  pynn.minExcWeight()),
                           target='excitatory')
    stimI.record()
    stimE.record()
    neuron.record()
    pynn.record_v(neuron[0], '')

    pynn.run(runtime)
    spikesInI = stimI.getSpikes()
    spikesInE = stimE.getSpikes()
    spikes = neuron.getSpikes()
    mem = pynn.membraneOutput

    print 'spikes out', len(spikes)
    print 'spikes in', len(spikesInI), len(spikesInE)
    print 'mem data points', len(mem)

    pynn.end()
コード例 #6
0
    def recordTauRef(self, neuronNr, icb):
        # necessary hardware setup
        p.setup(useUsbAdc=True, mappingOffset=neuronNr-192, calibTauMem=True, calibVthresh=False, calibSynDrivers=False, calibIcb=False, workStationName=self.workstation)
        p.hardware.hwa.setIcb(icb)
        # observed neuron
        neuron = p.Population(1, p.IF_facets_hardware1, self.neuronParams)
        # stimulating population
        input = p.Population(self.inputParameters['numInputs'], p.SpikeSourceArray, self.inputParameters['inputSpikes'])
        # connect input and neuron
        conn = p.AllToAllConnector(allow_self_connections=False, weights=self.inputParameters['weight'])
        proj = p.Projection(input, neuron, conn, synapse_dynamics=None, target='excitatory')

        # record spikes and membrane potential
        neuron.record()
        p.record_v(neuron[0],'')

        # run experiment
        p.run(self.duration)

        # evaluate results
        spikesDig = neuron.getSpikes()[:,1]
        membrane = p.membraneOutput
        time = p.timeMembraneOutput
        # clean up
        p.end()

        # determine sampling bins
        timestep = time[1] - time[0]

        # detect analog spikes
        spikesAna, isiAna = utils.find_spikes(membrane, time, spikesDig, reportFile=self.reportFile)

        # determine refractory period from measurement of analog spikes
        tau_ref, tau_ref_err, doubles_spikes = utils.fit_tau_refrac(membrane, timestep, spikesAna, isiAna, noDigSpikes=len(spikesDig), reportFile=self.reportFile, debugPlot=self.debugPlot)
       
        return tau_ref, tau_ref_err, doubles_spikes, spikesDig
コード例 #7
0
    def runTest(self):
        with_figure = False
        import numpy
        import pyNN.hardware.spikey as pynn
        if with_figure:
            import pylab

        # some test parameters
        neuron_param_even = {
            'g_leak': 1.0,  # nS
            'tau_syn_E': 5.0,  # ms
            'tau_syn_I': 5.0,  # ms
            'v_reset': -100.0,  # mV
            'e_rev_I': -100.0,  # mV,
            'v_rest': -65.0,  # mV
            'v_thresh': -62.0  # mV
        }
        neuron_param_uneven = {
            'g_leak': 1.0,  # nS
            'tau_syn_E': 5.0,  # ms
            'tau_syn_I': 5.0,  # ms
            'v_reset': -100.0,  # mV
            'e_rev_I': -100.0,  # mV,
            'v_rest': -65.0,  # mV
            'v_thresh': 0.0  # mV
        }
        stim_offset = 100.0  # ms
        stim_isi = 500.0  # ms
        stim_num = 10  # Number of external input spikes
        stim_weight = 8.0  # in units of pyn.minExcWeight
        stim_pop_size = 10  # size of stimulating population
        duration = stim_offset + ((stim_num + 1) * stim_isi)

        # neuron order: {0, 2, ..., 190, 1, 3, ..., 191, 192, 193, ... 343}
        neuron_order = range(0, 191, 2) + range(1, 192, 2) + range(192, 384, 1)
        if with_figure:
            pynn.setup(neuronPermutation=neuron_order, useUsbAdc=True)
        else:
            pynn.setup(neuronPermutation=neuron_order)

        # create the population with an even hardware neuron index
        even_population = pynn.Population(96, pynn.IF_facets_hardware1,
                                          neuron_param_even)
        # create the population with an uneven hardware neuron index
        uneven_population = pynn.Population(96, pynn.IF_facets_hardware1,
                                            neuron_param_uneven)
        if with_figure:
            pynn.record_v(even_population[0], '')

        # create the external stimulus
        stim_times = numpy.arange(stim_offset, stim_num * stim_isi, stim_isi)
        stim_pop = pynn.Population(stim_pop_size, pynn.SpikeSourceArray,
                                   {'spike_times': stim_times})

        # connect the external simulus
        stim_con = pynn.AllToAllConnector(weights=stim_weight *
                                          pynn.minExcWeight())
        stim_prj_even = pynn.Projection(stim_pop, even_population, stim_con)
        stim_prj_uneven = pynn.Projection(stim_pop, uneven_population,
                                          stim_con)

        # record spikes of all involved neurons
        even_population.record()
        uneven_population.record()

        # run the emulation
        pynn.run(duration)

        # get the spike data
        pre_swap_spikes_even = even_population.getSpikes()
        pre_swap_spikes_uneven = uneven_population.getSpikes()
        if with_figure:
            plotVoltageAndSpikes(pylab, pynn.timeMembraneOutput,
                                 pynn.membraneOutput, pre_swap_spikes_even,
                                 pre_swap_spikes_uneven)

        # swap the configurations
        pynn.set(even_population[0], pynn.IF_facets_hardware1,
                 {'v_thresh': 0.0})
        pynn.set(uneven_population[0], pynn.IF_facets_hardware1,
                 {'v_thresh': -62.0})

        # run the emulation
        pynn.run(duration)

        # get the spike data
        pst_swap_spikes_even = even_population.getSpikes()
        pst_swap_spikes_uneven = uneven_population.getSpikes()
        if with_figure:
            plotVoltageAndSpikes(pylab, pynn.timeMembraneOutput,
                                 pynn.membraneOutput, pst_swap_spikes_even,
                                 pst_swap_spikes_uneven)

        pre_spikes_count_even = float(len(pre_swap_spikes_even[:, 0]))
        pre_spikes_count_uneven = float(len(pre_swap_spikes_uneven[:, 0]))
        pst_spikes_count_even = float(len(pst_swap_spikes_even[:, 0]))
        pst_spikes_count_uneven = float(len(pst_swap_spikes_uneven[:, 0]))
        # let's see what we've got
        assert (pre_spikes_count_even > 0)
        assert (pst_spikes_count_uneven > 0)
        assert (pre_spikes_count_uneven / pre_spikes_count_even < 0.01)
        assert (pst_spikes_count_even / pst_spikes_count_uneven < 0.01)
        assert (pre_spikes_count_uneven / pst_spikes_count_uneven < 0.01)
        assert (pst_spikes_count_even / pre_spikes_count_even < 0.01)
コード例 #8
0
    def runTest(self):
        with_figure = False
        import numpy
        import pyNN.hardware.spikey as pynn
        if with_figure:
            import pylab

        # some test parameters
        neuron_param = {
            'g_leak': 1.0,  # nS
            'tau_syn_E': 5.0,  # ms
            'tau_syn_I': 5.0,  # ms
            'v_reset': -100.0,  # mV
            'e_rev_I': -100.0,  # mV,
            'v_rest': -65.0,  # mV
            'v_thresh': -62.0  # mV
        }
        stim_offset = 100.0  # ms
        stim_isi = 500.0  # ms
        stim_num = 10  # Number of external input spikes
        stim_weight = 8.0  # in units of pyn.minExcWeight
        stim_pop_size = 10  # size of stimulating population
        duration = stim_offset + ((stim_num + 1) * stim_isi)

        # neuron order: {0, 2, ..., 190, 1, 3, ..., 191, 192, 193, .., 383}
        neuron_order = range(0, 191, 2) + range(1, 192, 2) + range(192, 384, 1)
        if with_figure:
            pynn.setup(neuronPermutation=neuron_order, useUsbAdc=True)
        else:
            pynn.setup(neuronPermutation=neuron_order)

        # create first population with an even hardware neuron index
        fst_population = pynn.Population(48, pynn.IF_facets_hardware1,
                                         neuron_param)
        # create second population with an even hardware neuron index
        snd_population = pynn.Population(48, pynn.IF_facets_hardware1,
                                         neuron_param)
        if with_figure:
            pynn.record_v(fst_population[0], '')

        # create the external stimulus
        stim_times = numpy.arange(stim_offset, stim_num * stim_isi, stim_isi)
        stim_pop = pynn.Population(stim_pop_size, pynn.SpikeSourceArray,
                                   {'spike_times': stim_times})

        # connect the external simulus
        stim_con = pynn.AllToAllConnector(weights=stim_weight *
                                          pynn.minExcWeight())
        stim_prj_fst = pynn.Projection(stim_pop, fst_population, stim_con)
        stim_prj_snd = pynn.Projection(stim_pop, snd_population, stim_con)

        # record spikes of all involved neurons
        fst_population.record()
        snd_population.record()

        # run the emulation
        pynn.run(duration)

        # get the spike data
        pre_change_spikes_fst = fst_population.getSpikes()
        pre_change_spikes_snd = snd_population.getSpikes()
        if with_figure:
            plotVoltageAndSpikes(pylab,
                                 pynn.timeMembraneOutput,
                                 pynn.membraneOutput,
                                 pre_change_spikes_fst,
                                 pre_change_spikes_snd,
                                 nrn_idx_lim=[0, 96])

        # change the configuration for the first group
        # desired behaviour: change the configuration for all even neurons
        # "set" should be stronger than "previous setting in even/uneven group"
        pynn.set(fst_population[0], pynn.IF_facets_hardware1,
                 {'v_thresh': 0.0})

        # run the emulation
        pynn.run(duration)

        # get the spike data
        lidx_change_spikes_fst = fst_population.getSpikes()
        lidx_change_spikes_snd = snd_population.getSpikes()
        if with_figure:
            plotVoltageAndSpikes(pylab,
                                 pynn.timeMembraneOutput,
                                 pynn.membraneOutput,
                                 lidx_change_spikes_fst,
                                 lidx_change_spikes_snd,
                                 nrn_idx_lim=[0, 96])

        pre_spikes_count_fst = float(len(pre_change_spikes_fst[:, 0]))
        pre_spikes_count_snd = float(len(pre_change_spikes_snd[:, 0]))
        lidx_spikes_count_fst = float(len(lidx_change_spikes_fst[:, 0]))
        lidx_spikes_count_snd = float(len(lidx_change_spikes_snd[:, 0]))
        # let's see what we've got
        assert (pre_spikes_count_fst > 0)
        assert (pre_spikes_count_snd > 0)
        assert (lidx_spikes_count_fst / pre_spikes_count_fst < 0.01)
        assert (lidx_spikes_count_snd / pre_spikes_count_snd < 0.01)
コード例 #9
0
               sim.AllToAllConnector(weights=11 * we),
               synapse_dynamics=None,
               target="excitatory")
sim.Projection(parrotsI['y1'],
               populations['h2'],
               sim.AllToAllConnector(weights=15 * wi),
               target="inhibitory")
sim.Projection(parrotsI['y2'],
               populations['h1'],
               sim.AllToAllConnector(weights=15 * wi),
               target="inhibitory")

for label in labels:
    populations[label].record()
vlabel = 'o'
sim.record_v(populations[vlabel][0], '')
#sim.record_v(parrotsE[vlabel][0], '')
#sim.record_v(parrotsI[vlabel][0], '')

# execute the experiment
sim.run(runtime)

# evaluate results
spiketrains = {}
for label in labels:
    spiketrains[label] = populations[label].getSpikes()
    print(label, "spike rate: ", len(spiketrains[label]) / runtime, "kHz")

vm = sim.membraneOutput
tm = sim.timeMembraneOutput
コード例 #10
0
connInh = pynn.AllToAllConnector(weights=weightInh)
connExc_strong = pynn.FixedProbabilityConnector(p_connect=1.0, weights=weightExc * 2)

    # 1st neuron is stimulated by background
pynn.Projection(stimExc, neuronA, connExc, target="excitatory")
pynn.Projection(stimInh, neuronA, connInh, target="inhibitory")

    # 2nd neuron is stimulated by 1st neuron
pynn.Projection(neuronA, neuronB, connExc_strong, synapse_dynamics=None, target="excitatory")

# define which observables to record
    # spike times
neuronA.record()

    # membrane potential
pynn.record_v(neuronB[0], '')

# execute the experiment
pynn.run(runtime)

# evaluate results
spikes = neuronA.getSpikes()[:,1]
membrane = pynn.membraneOutput
membraneTime = pynn.timeMembraneOutput

pynn.end()

####################################################################
# data visualization
####################################################################
コード例 #11
0
neuron = pynn.Population(1, pynn.IF_facets_hardware1)
dummy = pynn.Population(row, pynn.SpikeSourceArray, stimParams)
stimulus = pynn.Population(1, pynn.SpikeSourceArray, stimParams)

# enable and configure STP
stp_model = pynn.TsodyksMarkramMechanism(**stpParams)
pynn.Projection(
    stimulus,
    neuron,
    method=pynn.AllToAllConnector(weights=weight * pynn.minExcWeight()),
    target='excitatory',
    synapse_dynamics=pynn.SynapseDynamics(
        fast=stp_model)  #hier auskommentieren
)

pynn.record_v(neuron[0], '')

pynn.run(runtime)

membrane = np.array(zip(pynn.timeMembraneOutput, pynn.membraneOutput))

pynn.end()

# plot
import matplotlib.pyplot as plt
plt.plot(membrane[:, 0], membrane[:, 1])
plt.xlabel('time (ms)')
plt.ylabel('membrane potential (mV)')
plt.title('STP with distance={} and final spike at {}'.format(dist, final))
#plt.ylim((-73,-69))
plt.savefig('4-3-fac-dist{}-final{}.png'.format(dist, final))
コード例 #12
0
def testNeuron(neuronNr,
               tau_ref_target,
               calibIcb=True,
               tries=5,
               workstation=None,
               seededParams=False):
    # measured tau_ref values
    tau = []
    # failed fits
    failed_tries = 0
    # short membrane time constant for good results
    tau_mem = 1.0  # ms
    # time interval between two subsequently stimulated spikes
    meanISI = 300.  # ms
    # number of test runs for each neuron and icb value
    runs = 30

    # seeded neuron parameters; neurons were calibrated with v_rest = -60.0 mV
    if seededParams:
        v_rest = random.randint(-70, -60)
        v_thresh = random.randint(-55, -50)
        v_reset = random.randint(-90, -85)
    else:
        v_reset = -90.0
        v_rest = -65.0
        v_thresh = -55.0

    neuronParams = {
        'v_reset': v_reset,  # mV
        'e_rev_I': -90.0,  # mV
        'v_rest': v_rest,  # mV
        'v_thresh': v_thresh,  # mV
        'g_leak': 0.2 / (tau_mem / 1000.),  # nS
        'tau_syn_E': 5.0,  # ms
        'tau_syn_I': 10.0,  # ms
        'tau_refrac': tau_ref_target,  # ms
    }

    # experiment duration
    duration = (runs + 1) * meanISI

    # stimulating population
    inputParameters = {
        'numInputs':
        10,  # number of spike sources connected to observed neuron
        'weight': 0.012,  # uS
        'weightIncrement': 0.003,  # uS
        'duration': duration,  # ms
        # ms
        'inputSpikes': {
            'spike_times': np.arange(10, duration, meanISI)
        },
    }

    # hardware setup
    p.setup(useUsbAdc=True,
            calibTauMem=True,
            calibVthresh=False,
            calibSynDrivers=False,
            calibIcb=calibIcb,
            mappingOffset=neuronNr - 192,
            workStationName=workstation)
    # observed neuron
    neuron = p.Population(1, p.IF_facets_hardware1, neuronParams)
    # stimulating population
    input = p.Population(inputParameters['numInputs'], p.SpikeSourceArray,
                         inputParameters['inputSpikes'])
    # connect input and neuron
    conn = p.AllToAllConnector(allow_self_connections=False,
                               weights=inputParameters['weight'])
    proj = p.Projection(input,
                        neuron,
                        conn,
                        synapse_dynamics=None,
                        target='excitatory')

    # record spikes and membrane potential
    neuron.record()
    p.record_v(neuron[0], '')

    # run experiment
    p.run(duration)

    # evaluate results
    spikesDig = neuron.getSpikes()[:, 1]

    # change weight if too few or too many spikes occured
    tries = 0
    while tries < 5 and (len(spikesDig) < runs - 1
                         or len(spikesDig) > runs + 1):
        if len(spikesDig) < runs - 1:
            inputParameters['weight'] += inputParameters['weightIncrement']
            print 'increasing weight to {0}, try {1}'.format(
                inputParameters['weight'], tries)
        else:
            inputParameters['weight'] -= inputParameters['weightIncrement']
            print 'decreasing weight to {0}, try {1}'.format(
                inputParameters['weight'], tries)
        conn = p.AllToAllConnector(allow_self_connections=False,
                                   weights=inputParameters['weight'])
        proj = p.Projection(input,
                            neuron,
                            conn,
                            synapse_dynamics=None,
                            target='excitatory')
        p.run(duration)
        spikesDig = neuron.getSpikes()[:, 1]
        tries += 1

    membrane = p.membraneOutput
    time = p.timeMembraneOutput
    # clean up
    p.end()

    # determine sampling bins
    timestep = time[1] - time[0]

    # detect analog spikes
    spikesAna, isiAna = utils.find_spikes(membrane,
                                          time,
                                          spikesDig,
                                          reportFile=reportFile)

    # determine refractory period from measurement of analog spikes
    tau_ref, tau_ref_err, doubles_spikes = utils.fit_tau_refrac(
        membrane,
        timestep,
        spikesAna,
        isiAna,
        noDigSpikes=len(spikesDig),
        debugPlot=debugPlot)

    return tau_ref, tau_ref_err
コード例 #13
0
ファイル: fp_task6_3.py プロジェクト: nikhil-garg/fp-lab
	'v_thresh'  : -55.0, # mV  # default
	'g_leak'    :  20.0  # nS  -> tau_mem = 0.2nF / 20nS = 10ms
}


neurons = pynn.Population(popSize, pynn.IF_facets_hardware1, neuronParams)

# the inhibitory projection of the complete population to itself, with identical number
# of presynaptic neurons. Enable after measuring the regular-firing case.
pynn.Projection(neurons, neurons, pynn.FixedNumberPreConnector(numInhPerNeuron, weights=weight), target='inhibitory')

# record spikes
neurons.record()

# record membrane potential of first 4 neurons
pynn.record_v([neurons[0], neurons[1], neurons[2], neurons[3]], '')

# start experiment
pynn.run(runtime)

spikes = neurons.getSpikes()

# end experiment (network keeps running...)
pynn.end()

# retrieve spikes and sort neuron-wise. 
snglnrn_spikes = []
snglnrn_spikes_neo = []
for i in range(popSize):
	snglnrn_spikes.append(spikes[np.nonzero(np.equal(i, spikes[:,0])),1][0])
	snglnrn_spikes_neo.append(SpikeTrain(times=snglnrn_spikes[i] * q.ms, t_start=0.0 * q.ms, t_stop=runtime * q.ms))
コード例 #14
0
ファイル: test_tauMemCalib.py プロジェクト: astoeckel/PyNN
def measure_tau_mem(neuronNr, tau_mem_target, calibTauMem=True):
    tauMeasured = []  # measured tau_mem values
    failed_trials = 0  # failed fits
    duration = 5000.  # duration of each measurement in ms
    targetSpikes = 20  # minimum number of spikes (target rate)
    vRestStep = 1.0  # increase of resting potential if too less spikes

    v_rest = p.IF_facets_hardware1.default_parameters['v_thresh'] + 3.0
    if randomNeuronParams:
        v_rest = random.randint(-65, -55)
    neuronParams = {
        'v_thresh': p.IF_facets_hardware1.default_parameters['v_thresh'],
        'v_rest': v_rest,
        'v_reset': p.IF_facets_hardware1.default_parameters['v_reset'],
        'g_leak': 0.2 / tau_mem_target * 1e3
    }  # nS
    maxVRest = neuronParams['v_rest'] + 10.0

    # measure tau_mem
    for i in range(trialsAverage):
        p.setup(useUsbAdc=True,
                calibTauMem=calibTauMem,
                calibVthresh=False,
                calibSynDrivers=False,
                calibIcb=False,
                mappingOffset=neuronNr - 192,
                workStationName=workstation)
        neuron = p.Population(1, p.IF_facets_hardware1, neuronParams)
        neuron.record()
        p.record_v(neuron[0], '')

        params = deepcopy(neuronParams)
        trials = 0
        crossedTargetRate = False
        while params['v_rest'] < maxVRest:
            print 'now at trial', trials, '/ v_rest =', params['v_rest']
            p.run(duration)
            trace = p.membraneOutput
            dig_spikes = neuron.getSpikes()[:, 1]
            memtime = p.timeMembraneOutput
            timestep = memtime[1] - memtime[0]

            # if neuron spikes with too low rate, try again with higher resting
            # potential
            if len(dig_spikes) < targetSpikes:
                params['v_rest'] = params['v_rest'] + vRestStep
                neuron.set(params)
                print 'Neuron spiked with too low rate, trying again with parameters', params
                trials += 1
            else:  # proper spiking
                crossedTargetRate = True
                break

        p.end()

        # determine tau_mem from measurements
        result = utils.fit_tau_mem(trace,
                                   memtime,
                                   dig_spikes,
                                   timestep=timestep,
                                   reportFile=reportFile)
        if result == None:  # fit failed
            failed_trials += 1
            continue
        tauMeasured.append(result[0])

    return tauMeasured, failed_trials
コード例 #15
0
    def test_zero_projection(self):
        #======================================================================
        # set up the following network and record the membrane potential of neuron0
        # for three different combination of weights:
        # run 0: w0 = 0 | w1 = 0
        # run 1: w0 = w | w1 = w
        # run 2: w0 = w | w1 = 0
        #======================================================================
        #           inh weight w0
        #            --> neuron 0
        #           /
        # stim
        #           \
        #            --> neuron 1
        #           inh weight w1
        #======================================================================
        # TODO: write test with call of connect() instead of projection as well
        import numpy
        import pyNN.hardware.spikey as pynn
        if self.with_figures:
            import pylab

        duration = 1000.0  # ms
        w = 10.0  # in units of pynn.minInhWeight
        stim_rate = 40.0  # Hz

        neuron_params = {
            'g_leak': 1.0,  # nS
            'tau_syn_E': 5.0,  # ms
            'tau_syn_I': 5.0,  # ms
            'v_reset': -80.0,  # mV
            'e_rev_I': -80.0,  # mV,
            'v_rest': -65.0,  # mV
            'v_thresh': 0.0  # mV // no spiking
        }

        # call setup with enabled oscilloscope
        pynn.setup(useUsbAdc=True)
        # create the populations
        nrn0 = pynn.Population(1, pynn.IF_facets_hardware1)
        nrn1 = pynn.Population(1, pynn.IF_facets_hardware1)
        stim_params = {'start': 0., 'duration': duration, 'rate': stim_rate}
        stim = pynn.Population(1, pynn.SpikeSourcePoisson, stim_params)
        # record the membrane potential of neuron0
        pynn.record_v(nrn0[0], '')
        # create the connectors
        w_con = pynn.AllToAllConnector(weights=w * pynn.minInhWeight())
        zero_con = pynn.AllToAllConnector(weights=0.0 * pynn.minInhWeight())

        # run the first time
        nrn0_prj = pynn.Projection(stim, nrn0, zero_con, target='inhibitory')
        nrn1_prj = pynn.Projection(stim, nrn1, zero_con, target='inhibitory')
        pynn.run(duration)
        u_run0 = numpy.mean(pynn.membraneOutput)
        du_run0 = numpy.std(pynn.membraneOutput)
        if self.with_figures:
            pylab.figure()
            pylab.plot(pynn.timeMembraneOutput, pynn.membraneOutput)
            pylab.show()

        # second time
        nrn0_prj = pynn.Projection(stim, nrn0, w_con, target='inhibitory')
        nrn1_prj = pynn.Projection(stim, nrn1, w_con, target='inhibitory')
        pynn.run(duration)
        u_run1 = numpy.mean(pynn.membraneOutput)
        du_run1 = numpy.std(pynn.membraneOutput)
        if self.with_figures:
            pylab.figure()
            pylab.plot(pynn.timeMembraneOutput, pynn.membraneOutput)
            pylab.show()

        # third time
        nrn0_prj = pynn.Projection(stim, nrn0, w_con, target='inhibitory')
        nrn1_prj = pynn.Projection(stim, nrn1, zero_con, target='inhibitory')
        pynn.run(duration)
        u_run2 = numpy.mean(pynn.membraneOutput)
        du_run2 = numpy.std(pynn.membraneOutput)
        if self.with_figures:
            pylab.figure()
            pylab.plot(pynn.timeMembraneOutput, pynn.membraneOutput)
            pylab.show()

        # plot and evaluate
        if self.with_figures:
            x_val = numpy.arange(1, 4, 1)
            y_val = [u_run0, u_run1, u_run2]
            y_err = [du_run0, du_run1, du_run2]
            pylab.figure()
            pylab.xlim([0, 4])
            pylab.xlabel("Run")
            pylab.ylabel("Mean membrane voltage [mV]")
            pylab.errorbar(x_val, y_val, yerr=y_err, fmt='o')
            pylab.show()
        assert (((u_run0 - u_run1) / du_run0) > 0.2)
        assert (((u_run0 - u_run2) / du_run0) > 0.2)
        assert (abs((u_run2 - u_run1) / du_run0) < 0.2)
コード例 #16
0
                    pynn.FixedProbabilityConnector(p_connect=probExcExc,
                                                   weights=weightExcExc),
                    target='excitatory')
    pynn.Projection(popCollector['exc'][popIndex],
                    popCollector['inh'][(popIndex + 1) % noPops],
                    pynn.FixedProbabilityConnector(p_connect=probExcInh,
                                                   weights=weightExcInh),
                    target='excitatory')
    pynn.Projection(popCollector['inh'][popIndex],
                    popCollector['exc'][popIndex],
                    pynn.FixedProbabilityConnector(p_connect=probInhExc,
                                                   weights=weightInhExc),
                    target='inhibitory')

# record from first neuron of first excitatory population of chain
pynn.record_v(popCollector['exc'][0][0], '')

# run chain...
pynn.run(runtime)

# collect all spikes in one array
spikeCollector = np.array([]).reshape(0, 2)
for synType in ['exc', 'inh']:
    for popIndex in range(noPops):
        spikeCollector = np.vstack(
            (spikeCollector, popCollector[synType][popIndex].getSpikes()))

# get membrane
membrane = pynn.membraneOutput
membraneTime = pynn.timeMembraneOutput
コード例 #17
0
neuron1.set({'g_leak' : 20.0}) # 17.6
neuron2.set({'g_leak' : 20.0}) # 17.5
neuron3.set({'g_leak' : 20.0}) # 22.0
neuron4.set({'g_leak' : 20.0}) # 32.0

# define which observables to record
# spike times
neuron1.record()
neuron2.record()
neuron3.record()
neuron4.record()

# membrane potential
# when recording more than one membrane voltage, the on-board ADC cannot be used, anymore!
# (it will record a flat line). Instead, only oscilloscope recordings are possible.
pynn.record_v([neuron1[0], neuron2[0], neuron3[0], neuron4[0]], '')
print(neuron1[0])


# execute the experiment
pynn.run(runtime)

# evaluate results
print(neuron1.getSpikes())
spikes1 = neuron1.getSpikes()[:,1]
spikes2 = neuron2.getSpikes()[:,1]
spikes3 = neuron3.getSpikes()[:,1]
spikes4 = neuron4.getSpikes()[:,1]
membrane = pynn.membraneOutput
membraneTime = pynn.timeMembraneOutput
コード例 #18
0
# connect stimulus
pynn.Projection(stimExc, popCollector['exc'][0], pynn.FixedProbabilityConnector(p_connect=probExcExc, weights=weightStimExcExc), target='excitatory')
pynn.Projection(stimExc, popCollector['inh'][0], pynn.FixedProbabilityConnector(p_connect=probExcInh, weights=weightStimExcInh), target='excitatory')
# connect synfire chain populations
for popIndex in range(noPops):
    #if popIndex < noPops - 1: # open chain
        pynn.Projection(popCollector['exc'][popIndex], popCollector['exc'][(popIndex + 1) % noPops],
                        pynn.FixedProbabilityConnector(p_connect=probExcExc, weights=weightExcExc), target='excitatory')
        pynn.Projection(popCollector['exc'][popIndex], popCollector['inh'][(popIndex + 1) % noPops],
                        pynn.FixedProbabilityConnector(p_connect=probExcInh, weights=weightExcInh), target='excitatory')
        pynn.Projection(popCollector['inh'][popIndex], popCollector['exc'][popIndex],
                        pynn.FixedProbabilityConnector(p_connect=probInhExc, weights=weightInhExc), target='inhibitory')

# record from first neuron of first excitatory population of chain
pynn.record_v(popCollector['exc'][0][0], '')

# hack to elongate refractory period of all neurons
# will be configurable via neuron parameters, soon
pynn.hardware.hwa.setIcb(0.02)

pynn.run(runtime)

# collect all spikes in one array
spikeCollector = np.array([]).reshape(0,2)
for synType in ['exc', 'inh']:
    for popIndex in range(noPops):
        spikeCollector = np.vstack((spikeCollector, popCollector[synType][popIndex].getSpikes()))

# get membrane
membrane = pynn.membraneOutput
コード例 #19
0
def test_compareSpikesToMembrane_restOverThresh():
    """
    Tests the precise timing of digital spikes and spikes extracted from the membrane potential.
    The resting potential is set over the firing threshold, which results in regular firing.
    """

    import pyNN.hardware.spikey as pynn
    np.random.seed(int(time.time()))

    trials = 3
    duration = 5 * 1000.0  # ms
    freqLimit = 10.0  # 1/s
    limitSpikesMissing = 2

    for trial in range(trials):
        neuronNo = np.random.random_integers(0, 191)
        print 'Using neuron number', neuronNo

        pynn.setup(mappingOffset=neuronNo)

        neuron = pynn.Population(1, pynn.IF_facets_hardware1, {
                                 'v_rest': pynn.IF_facets_hardware1.default_parameters['v_thresh'] + 10.0})
        neuron.record()
        pynn.record_v(neuron[0], '')

        pynn.run(duration)

        mem = pynn.membraneOutput
        memTime = pynn.timeMembraneOutput
        spikes = neuron.getSpikes()[:, 1]
        pynn.end()

        print 'Mean membrane:', np.mean(mem)
        noSpikes = len(spikes)
        print 'Number of spikes:', noSpikes
        assert noSpikes > freqLimit * \
            (duration / 1e3), 'Too less spikes: ' + str(noSpikes)

        spikesMem, deriv, thresh = spikesFromMem(memTime, mem)

        #plot(memTime, mem, spikes, spikesMem, deriv, thresh)

        # calculate ISIs
        spikes = np.array(spikes)
        isiDigital = spikes[1:] - spikes[:-1]
        isiDigitalMean = isiDigital.mean()

        spikesMem = np.array(spikesMem)
        isiAnalog = spikesMem[1:] - spikesMem[:-1]
        isiAnalogMean = isiAnalog.mean()

        # any digital or analog spikes missing?
        missingDigital = 0
        missingDigital += len(isiDigital[isiDigital > isiDigitalMean * 1.5])
        missingDigital += len(isiDigital[isiDigital < isiDigitalMean * 0.5])

        missingAnalog = 0
        missingAnalog += len(isiAnalog[isiAnalog > isiAnalogMean * 1.5])
        missingAnalog += len(isiAnalog[isiAnalog < isiAnalogMean * 0.5])

        print 'Number of spikes (digital, analog):', len(spikes), len(spikesMem)
        print 'Spikes missing (digital, analog):', missingDigital, missingAnalog
        print 'Frequency (digital, analog) in 1/s:', 1e3 / isiDigitalMean, 1e3 / isiAnalogMean
        ratioDigAna = isiDigitalMean / isiAnalogMean
        print 'Frequency digital to analog (abs, %):', ratioDigAna, (ratioDigAna - 1.0) * 1e3

        assert abs(len(spikes) - len(spikesMem)
                   ) <= limitSpikesMissing, 'Numbers of digital and analog spikes differ by more than ' + str(limitSpikesMissing) + '.'
        assert missingDigital == 0, 'Digital spikes are missing.'
        assert missingAnalog == 0, 'Analog spikes are missing.'
        assert (ratioDigAna - 1) < 2e-4, 'Time axes differ more than 0.2% between digital spikes and membrane (is ' + \
            str((ratioDigAna - 1.0) * 1e3) + '%).'
コード例 #20
0
    def calib(self):

        self.result['datetime'] = dt.datetime.now()
        self.result['temperature'] = 'TODO'
        self.result['person'] = pwd.getpwuid(os.getuid()).pw_name

        # one setup is necessary in order to determine spikey version
        pynn.setup(workStationName=self.workstation, calibOutputPins=False, calibNeuronMems=False, calibTauMem=False, calibSynDrivers=False, calibVthresh=False, calibBioDynrange=False)
        self.chipVersion = pynn.hardware.chipVersion()

        for block in range(2):
            if not self.chipVersion == 4 or block == 1:
                for pin in range(4):

                    lower = -90.
                    upper = -40.
                    step = (upper - lower) / self.numVsteps
                    for vrest in numpy.arange(lower, upper+step/2., step):

                        pin_in = numpy.nan
                        pin_out = numpy.nan

                        for pinBlock in range(self.numPinBlocks):

                            neuron = block * 192 + pinBlock * 4 + pin

                            # necessary setup
                            mappingOffset = neuron
                            if self.chipVersion == 4:
                                mappingOffset = neuron % 192
                            pynn.setup(useUsbAdc=True, workStationName=self.workstation, mappingOffset=mappingOffset, rng_seeds=self.seeds, avoidSpikes=True, \
                                       calibOutputPins=False, calibNeuronMems=False, calibTauMem=False, calibSynDrivers=False, calibVthresh=False)

                            self.neuronParams['v_rest'] = vrest

                            # set up network
                            n = pynn.create(pynn.IF_facets_hardware1,self.neuronParams,n=1)

                            pynn.record_v(n, '')
                            pynn.record(n, '')

                            #http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
                            traceSum = 0.0
                            traceSumSqr = 0.0
                            # execute the experiment in a loop
                            for i in range(self.numRuns):
                                pynn.run(self.duration, translateToBioVoltage=False)
                                if i==0:
                                    pin_in = pynn.hardware.hwa.vouts[neuron/192,neuron%2 + 2]
                                else:
                                    assert pin_in == pynn.hardware.hwa.vouts[neuron/192,neuron%2 + 2], 'vout should not differ'
                                mem = pynn.membraneOutput
                                memMean = mem.mean()
                                traceSum += memMean
                                traceSumSqr += numpy.power(memMean, 2)
                                noSpikes = len(pynn.spikeOutput[1])
                                if not float(noSpikes) / self.duration * 1e3 == 0:
                                    self.noSpikesTotal += noSpikes
                                    print 'there are', noSpikes, 'spikes on the membrane (most likely / hopefully ghost spikes)'
                                    assert mem.std() < self.limMemStd, 'digital spikes and spikes on the membrane found!'
                            pin_out = traceSum / self.numRuns
                            pin_out_std = (traceSumSqr - (numpy.power(traceSum, 2) / self.numRuns)) / (self.numRuns - 1)
                            pynn.end()

                            print 'For neuron',neuron,'the written voltage',pin_in,'appeared on the scope as',pin_out,'/2'

                            #save raw data
                            newData = numpy.vstack((neuron, pin_in, pin_out, numpy.sqrt(pin_out_std))).T
                            if self.rawData == None:
                                self.rawData = newData
                            else:
                                self.rawData = numpy.vstack((self.rawData, newData))



        def filter_and_fit(dataset):
            #filter data
            dataset = numpy.atleast_2d(dataset)
            dataToFit = numpy.atleast_2d(dataset[dataset[:,1] >= self.voltageLimLow])
            dataToFit = numpy.atleast_2d(dataToFit[dataToFit[:,1] <= self.voltageLimHigh])
            noPins = len(numpy.unique(numpy.array(dataset[:,0] / 192, numpy.int) * 4 + dataset[:,0] % 4))
            assert (len(dataset) - len(dataToFit)) % noPins == 0, 'discarding data failed'
            print 'discarded', (len(dataset) - len(dataToFit)) / noPins, 'data points'

            #fit polynomial
            return numpy.polyfit(dataToFit[:,2], dataToFit[:,1], self.polyDegree)

        for block in range(2):
            if self.chipVersion == 4 and block == 0:
                continue

            for pin in range(4):
                #data for output pin calibration
                dataOnePin = self.rawData[numpy.array(self.rawData[:,0] / 192, numpy.int) * 4 + self.rawData[:,0] % 4 == block * 4 + pin]

                #calculate mean over neurons with same pin
                vouts = numpy.unique(dataOnePin[:,1])
                mean = []
                std = []
                for vout in vouts:
                    mean.append(numpy.mean(dataOnePin[dataOnePin[:,1] == vout][:,2]))
                    std.append(numpy.std(dataOnePin[dataOnePin[:,1] == vout][:,2]))
                dataOnePinMean = numpy.vstack((numpy.zeros_like(vouts), vouts, mean, std)).T

                self.result['polyFitOutputPins']['pin' + str(block * 4 + pin)] = filter_and_fit(dataOnePinMean)

                for pinBlock in range(self.numPinBlocks):
                    neuron = block * 192 + pinBlock * 4 + pin
                    #data for membrane calibration of single neurons
                    dataOneNeuron = self.rawData[self.rawData[:,0] == neuron]
                    self.result['polyFitNeuronMems']['neuron' + str(neuron).zfill(3)] = filter_and_fit(dataOneNeuron)



        print 'total number of spikes', self.noSpikesTotal, 'in', len(numpy.unique(numpy.array(self.rawData[:,0] / 192, numpy.int) * 4 + self.rawData[:,0] % 4)) * (self.numVsteps + 1) * self.numPinBlocks * self.numRuns, 'runs'
        return self.result, self.rawData
コード例 #21
0
    def runTest(self):
        with_figure = False
        import numpy
        import pyNN.hardware.spikey as pynn
        if with_figure:
            import pylab

        # some test parameters
        weight = 12.0  # in units of pyn.minExcWeight

        neuron_params = {
            'g_leak': 1.0,  # nS
            'tau_syn_E': 5.0,  # ms
            'tau_syn_I': 5.0,  # ms
            'v_reset': -100.0,  # mV
            'e_rev_I': -100.0,  # mV,
            'v_rest': -65.0,  # mV
            'v_thresh': -63.0  # mV
        }

        stim_offset = 100.0  # ms
        stim_isi = 500.0  # ms
        stim_num = 10  # Number of external input spikes
        stim_weight = 8.0  # in units of pyn.minExcWeight
        stim_pop_size = 10  # size of stimulating population

        # set up the test network where pre_neuron and pst_neuron are on different
        # blocks
        #======================================================================
        #                    pre_neuron ==> pst_neuron
        #
        # stim ==> sil_neuron
        #======================================================================
        # there shouldn't be a connection between sil_neuron and pst_neuron
        neuron_order = range(0, 384, 1)
        if with_figure:
            pynn.setup(neuronPermutation=neuron_order, useUsbAdc=True)
        else:
            pynn.setup(neuronPermutation=neuron_order)

        # create the populations
        pre_neuron = pynn.Population(1, pynn.IF_facets_hardware1)
        sil_neuron = pynn.Population(1, pynn.IF_facets_hardware1)
        pst_neuron = pynn.Population(1, pynn.IF_facets_hardware1)
        if with_figure:
            pynn.record_v(pst_neuron[0], '')

        # create the connection
        pre_pst_con = pynn.AllToAllConnector(weights=weight *
                                             pynn.minExcWeight())
        pre_pst_prj = pynn.Projection(pre_neuron, pst_neuron, pre_pst_con)

        # create the external stimulus
        stim_times = numpy.arange(stim_offset, stim_num * stim_isi, stim_isi)
        stim_pop = pynn.Population(stim_pop_size, pynn.SpikeSourceArray,
                                   {'spike_times': stim_times})

        # connect the external simulus
        stim_con = pynn.AllToAllConnector(weights=stim_weight *
                                          pynn.minExcWeight())
        stim_prj = pynn.Projection(stim_pop, sil_neuron, stim_con)

        # record spikes of all involved neurons
        pre_neuron.record()
        pst_neuron.record()
        sil_neuron.record()

        # run the emulation
        pynn.run(stim_offset + ((stim_num + 1) * stim_isi))

        if with_figure:
            pylab.figure()
            pylab.plot(pynn.timeMembraneOutput, pynn.membraneOutput)
            pylab.show()

        # let's see what we've got, accept up to 1 ghost spike
        assert (len(pre_neuron.getSpikes()) < 2)
        assert (len(pst_neuron.getSpikes()) < 2)
        assert (len(sil_neuron.getSpikes()) >= 10)
        assert (len(sil_neuron.getSpikes()) < 12)