Exemplo n.º 1
0
def maxSpikesIn(runtime):
    '''Maximum number of spikes that can be sent:
    Should be limited by memory size on FPGA board (256MB => 256x1024x1024x8/32x3 approx. 200e6 spikes).'''

    rate = 10.0
    weight = 1.0

    poissonParam = {'start': 0, 'duration': runtime, 'rate': rate}

    pynn.setup()

    stim = pynn.Population(256, pynn.SpikeSourcePoisson, poissonParam)
    neuron = pynn.Population(192, pynn.IF_facets_hardware1)
    prj = pynn.Projection(stim,
                          neuron,
                          pynn.AllToAllConnector(weights=pynn.minInhWeight() *
                                                 weight),
                          target='inhibitory')

    neuron.record()

    pynn.run(runtime)
    spikes = neuron.getSpikes()
    lost, sent = pynn.getInputSpikes()

    print 'spikes in / out', sent, len(spikes)

    pynn.end()
Exemplo n.º 2
0
def test():
    '''mapping of bio index to hardware index should work for networks
    where not all neurons are recorded'''
    pynn.setup()

    if mappingOffset > 0:
        dummy = pynn.Population(mappingOffset, pynn.IF_facets_hardware1)

    neuronList = []
    for i in range(noNeurons):
        neuronList.append(pynn.Population(1, pynn.IF_facets_hardware1))
        neuronList[-1].record()
        dummy = pynn.Population(1, pynn.IF_facets_hardware1)

    stim = pynn.Population(1, pynn.SpikeSourcePoisson)
    for neuron in neuronList:
        pynn.Projection(stim, neuron,
                        pynn.AllToAllConnector(weights=pynn.minExcWeight()))

    pynn.run(1000.0)
    pynn.end()

    f = open('spikeyconfig.out')
    for line in f:
        for i in range(mappingOffset + 2 * noNeurons):
            if line.find('w ' + str(192 + i)) >= 0:
                weight = int(line.split(' ')[256 + 2 - 1])
                print 192 + i, weight
                assert (weight == shouldPatternWeights[i]
                        ), 'results do not fit expectation'
    f.close()
Exemplo n.º 3
0
def run(mappingOffset):
    """
    Measures firing rate of one neuron (determined by mappingOffset) in dependence on value of g_leak.
    If linear fit to these firing rates does not show a significantly large slope,
    g_leak is assumed to be not set correctly.
    """
    pynn.setup(mappingOffset=mappingOffset,
               calibTauMem=False,
               calibSynDrivers=False,
               calibVthresh=False)
    # set v_rest over v_reset to get neuron firing
    neuron = pynn.Population(1, pynn.IF_facets_hardware1, {
        'v_rest':
        pynn.IF_facets_hardware1.default_parameters['v_thresh'] + 10.0
    })
    neuron.record()

    rateList = []
    for gLeak in gLeakRange:
        neuron.set({'g_leak': gLeak / default.iLeak_base})
        pynn.hardware.hwa._neuronsChanged = True
        pynn.run(runtime)
        rateList.append(
            [gLeak, float(len(neuron.getSpikes())) / runtime * 1e3])

    pynn.end()

    rateList = np.array(rateList)
    pol = np.polyfit(rateList[:, 0], rateList[:, 1], 1)  # linear fit
    print 'fitted polynom:', pol
    assert pol[0] > slopeMin, 'rate does not change with g_leak'
Exemplo n.º 4
0
    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()
        def run(noNeurons):
            runtime = 1000.0

            import numpy as np
            import pyNN.hardware.spikey as pynn
            pynn.setup()

            neurons = pynn.Population(noNeurons, pynn.IF_facets_hardware1)
            neurons.record()
            stim = pynn.Population(10, pynn.SpikeSourcePoisson, {
                'rate': 20.0,
                'duration': runtime
            })
            prj = pynn.Projection(stim, neurons, pynn.AllToAllConnector())
            prj.setWeights(pynn.maxExcWeight())

            pynn.run(runtime)
            spikes = neurons.getSpikes([])
            # for neuron in np.unique(spikes[:,0]):
            # print 'neuron', int(neuron), 'has', len(spikes[spikes[:,0] ==
            # neuron]), 'spikes'
            noSpikes = len(spikes)
            lost, sent = pynn.getInputSpikes()
            pynn.end()

            print 'no neurons / spikes in / lost / out:', noNeurons + 1, sent, lost, noSpikes

            return noSpikes
Exemplo n.º 6
0
def test_noSpikesBug():
    import numpy as np
    import pyNN.hardware.spikey as pynn

    duration = 10 * 1000.0  # ms
    neuronParams = {
        'v_reset': -80.0,  # mV
        'e_rev_I': -80.0,  # mV
        'v_rest': -45.0,  # mV / rest above threshold
        'v_thresh': -55.0,  # mV
        'g_leak': 20.0,  # nS / without Scherzer calib approx. tau_m = 2ms
    }
    noTrials = 100
    failCount = 0
    for i in range(noTrials):
        pynn.setup()
        neuron = pynn.Population(1, pynn.IF_facets_hardware1, neuronParams)
        neuron.record()
        pynn.run(duration)
        spikes = neuron.getSpikes()[:, 1]
        pynn.end()  # comment this out and everything is fine

        if len(spikes) == 0:
            failCount += 1

    assert failCount == 0, str(
        float(failCount) / noTrials * 1e2) + ' % of runs did not have spikes'
Exemplo n.º 7
0
def maxRuntime(runtime):
    '''Maximum runtime:
    Limited by wrap around of counter (after approx. 6600s).
    Can be extended to infinitly long runtimes by considering wrap around.
    Subtract/Add offset to in/out spike times for each wrap around.'''

    rate = 1.0
    weight = 1.0

    poissonParam = {'start': 0, 'duration': runtime, 'rate': rate}

    pynn.setup()

    stim = pynn.Population(1, pynn.SpikeSourcePoisson, poissonParam)
    neuron = pynn.Population(1, pynn.IF_facets_hardware1)
    prj = pynn.Projection(stim,
                          neuron,
                          pynn.AllToAllConnector(weights=pynn.minInhWeight() *
                                                 weight),
                          target='inhibitory')

    neuron.record()

    pynn.run(runtime)
    spikes = neuron.getSpikes()
    lost, sent = pynn.getInputSpikes()

    print 'spikes in / out', sent, len(spikes)

    pynn.end()
Exemplo n.º 8
0
def maxSpikesOut(runtime):
    '''Maximum number of spikes that can be received:
    Should be limited by memory size on FPGA board (128MB approx. 100e6 spikes, other half for ADC).'''

    neuronParams = {
        'v_reset': -80.0,  # mV
        'e_rev_I': -80.0,  # mV
        'v_rest': -45.0,  # mV / rest above threshold
        'v_thresh': -55.0,  # mV
        'g_leak': 20.0,  # nS / without Scherzer calib approx. tau_m = 2ms
    }

    pynn.setup()

    neuron = pynn.Population(192, pynn.IF_facets_hardware1, neuronParams)
    neuron.record()

    pynn.run(runtime)

    spikes = neuron.getSpikes()[:, 1]
    lost, sent = pynn.getInputSpikes()

    print 'spikes in / out', sent, len(spikes)

    pynn.end()
Exemplo n.º 9
0
def test_spikey5_allneurons():
    '''
    Tests mapping and firing of all 384 neurons.
    '''
    runtime = 1000.0
    stimRate = 10.0
    weight = 7

    pynn.setup()

    neurons = pynn.Population(384, pynn.IF_facets_hardware1)
    stim = pynn.Population(10, pynn.SpikeSourcePoisson, {
        'start': 0,
        'duration': runtime,
        'rate': stimRate
    })

    prj = pynn.Projection(
        stim,
        neurons,
        method=pynn.AllToAllConnector(weights=pynn.minExcWeight() * weight),
        target='excitatory')

    pynn.run(runtime)

    spikes = neurons.getSpikes()
    print 'spikes from', len(np.unique(spikes)), 'different neurons'
    # TODO: check for spikes from all neurons

    pynn.end()
def run(lowThreshold):
    runtime = 1000.0
    pynn.setup()

    # set STDP params for low threshold  -> fails when vcthigh-vctlow < 0.04
    if lowThreshold:
        pynn.hardware.hwa.setSTDPParams(0.0, default.tpcsec,
                                        default.tpcorperiod, 1.0, 1.0, 1.0,
                                        0.98, 2.5)
    else:
        pynn.hardware.hwa.setSTDPParams(0.0, default.tpcsec,
                                        default.tpcorperiod, 1.0, 1.0, 1.0,
                                        0.85, 2.5)

    neuron = pynn.Population(1, pynn.IF_facets_hardware1)
    spikeArray = pynn.Population(1, pynn.SpikeSourceArray)

    stdp_model = pynn.STDPMechanism(
        timing_dependence=pynn.SpikePairRule(),
        weight_dependence=pynn.AdditiveWeightDependence())

    prj = pynn.Projection(
        spikeArray,
        neuron,
        method=pynn.AllToAllConnector(weights=pynn.minExcWeight() * 0),
        target='excitatory',
        synapse_dynamics=pynn.SynapseDynamics(slow=stdp_model))

    pynn.run(runtime)
    pynn.end()
    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']]))
Exemplo n.º 12
0
 def runClosed():
     global neurons
     rateOutList = []
     for rate in rateRange:
         pynn.setup()
         build(rate)
         pynn.run(runtime)
         rateOutList.append(
             len(neurons.getSpikes()) / runtime * 1e3 / numNeurons)
         pynn.end()
     return rateOutList
Exemplo n.º 13
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.'
Exemplo n.º 14
0
 def runLoop():
     global neurons, stim
     rateOutList = []
     pynn.setup()
     build(0)
     for rate in rateRange:
         poissonParams = {'start': 0, 'duration': runtime, 'rate': rate}
         stim.set(poissonParams)
         pynn.run(runtime)
         rateOutList.append(
             len(neurons.getSpikes()) / runtime * 1e3 / numNeurons)
     pynn.end()
     return rateOutList
Exemplo n.º 15
0
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()
    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
Exemplo n.º 17
0
# set resting potential over spiking threshold
runtime = 1000.0  # ms
popSize = 192
weight = 7.0 * pynn.minExcWeight()
neuronParams = {"v_rest": -40.0}

neurons = pynn.Population(popSize, pynn.IF_facets_hardware1, neuronParams)
pynn.Projection(neurons, neurons, pynn.FixedNumberPreConnector(15, weights=weight), target="inhibitory")
neurons.record()

pynn.run(runtime)

spikes = neurons.getSpikes()

pynn.end()

# visualize
print "mean firing rate:", round(len(spikes) / runtime / popSize * 1000.0, 1), "1/s"

import matplotlib.pyplot as plt

color = "k"

plt.figure()
plt.plot(spikes[:, 1], spikes[:, 0], ls="", marker="o", ms=1, c=color, mec=color)
plt.xlim(0, runtime)
plt.xlabel("time (ms)")
plt.ylabel("neuron ID")
plt.ylim(-0.5, popSize - 0.5)
plt.savefig("decorr_network.png")
    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
    def emulate(self, driverIndexExc, driverIndexInh=None, drvirise=None, drvifallExc=None, drvifallInh=None, drvioutExc=None, drvioutInh=None, filename=None, calibSynDrivers=False):
        '''Run emulations on hardware.'''
        assert self.stimParams != None, 'specifiy stimulus first'
        pynn.setup(calibTauMem=True,
                   calibSynDrivers=calibSynDrivers,
                   calibVthresh=False,
                   calibIcb=False,
                   workStationName=self.workstation,
                   writeConfigToFile=False)

        #create neuron
        self.neuronList.sort()
        neuronCollector = []
        currentIndex = 0
        for neuronIndex in self.neuronList:
            if neuronIndex > currentIndex: #insert dummy neurons if neuronList not continuous
                dummyPopSize = neuronIndex - currentIndex
                dummy = pynn.Population(dummyPopSize, pynn.IF_facets_hardware1, self.neuronParams)
                currentIndex += dummyPopSize
                self.logger.debug('inserted ' + str(dummyPopSize) + ' dummy neurons')
            if neuronIndex == currentIndex:
                neuron = pynn.Population(1, pynn.IF_facets_hardware1, self.neuronParams)
                currentIndex += 1
                neuron.record()
                neuronCollector.append(neuron)
            else:
                raise Exception('Could not create all neurons')

        #create input and connect to neuron
        synDrivers = [[driverIndexExc, 'excitatory'], [driverIndexInh, 'inhibitory']]
        synDrivers.sort()

        currentIndex = 0
        for synDriver in synDrivers:
            toInsertIndex = synDriver[0]
            targetType = synDriver[1]
            if toInsertIndex == None:
                self.logger.debug('skipping ' + targetType + ' stimulation')
                continue
            if toInsertIndex > currentIndex:
                dummyPopSize = toInsertIndex - currentIndex
                dummy = pynn.Population(dummyPopSize, pynn.SpikeSourcePoisson)
                currentIndex += dummyPopSize
                self.logger.debug('inserted ' + str(dummyPopSize) + ' dummy synapse drivers')
            stim = pynn.Population(1, pynn.SpikeSourcePoisson, self.stimParams[targetType])
            self.logger.debug('inserted 1 stimulus of type ' + targetType + ' with rate ' + str(self.stimParams[targetType]['rate']))

            if targetType == 'excitatory':
                hardwareWeightTemp = self.hardwareWeight * pynn.minExcWeight()
            elif targetType == 'inhibitory':
                hardwareWeightTemp = self.hardwareWeight * pynn.minInhWeight()
            else:
                raise Exception('Synapse type not supported!')

            for neuron in neuronCollector:
                pynn.Projection(stim, neuron, method=pynn.AllToAllConnector(weights=hardwareWeightTemp), target=targetType)
            currentIndex += 1

        #set custom parameters
        if drvirise != None:
            pynn.hardware.hwa.drvirise = drvirise
        else:
            pynn.hardware.hwa.drvirise = default.drvirise
        if drvifallExc != None:
            pynn.hardware.hwa.drvifall_base['exc'] = drvifallExc
        else:
            pynn.hardware.hwa.drvifall_base['exc'] = default.drvifall_base['exc']
        if drvifallInh != None:
            pynn.hardware.hwa.drvifall_base['inh'] = drvifallInh
        else:
            pynn.hardware.hwa.drvifall_base['inh'] = default.drvifall_base['inh']
        if drvioutExc != None:
            pynn.hardware.hwa.drviout_base['exc'] = drvioutExc
        else:
            pynn.hardware.hwa.drviout_base['exc'] = default.drviout_base['exc']
        if drvioutInh != None:
            pynn.hardware.hwa.drviout_base['inh'] = drvioutInh
        else:
            pynn.hardware.hwa.drviout_base['inh'] = default.drviout_base['inh']

        #run
        pynn.run(self.runtime)
        #temperature = pynn.hardware.hwa.getTemperature()
        #self.logger.debug('temperature ' + str(temperature) + ' degree Celsius')

        #obtain firing rate
        spikes = None
        neuronCount = 0
        for neuron in neuronCollector:
            spikesNeuron = neuron.getSpikes()
            neuronCount += neuron.size
            if spikes == None:
                spikes = spikesNeuron
            else:
                spikes = np.concatenate((spikes, spikesNeuron))
        if len(spikes) > 0:
            spikes = spikes[spikes[:,1] > self.cutfirst]
            if len(spikes) > 0:
                spikes = spikes[spikes[:,1] <= self.runtime]
        if filename != None:
            np.savetxt(os.path.join(self.folder, filename), spikes)
        spikesPerNeuron = float(len(spikes)) / neuronCount
        pynn.end()
        rate =  spikesPerNeuron * 1e3 / (self.runtime - self.cutfirst)

        return rate