示例#1
0
def setup_synapse():
    """Create an intfire object and create two synapses on it."""
    if4 = moose.IntFire('if4')
    sf4 = moose.SimpleSynHandler('if4/sh')
    sg1 = moose.SpikeGen('sg1')
    sg2 = moose.SpikeGen('sg2')
    sf4.synapse.num = 2  # set synapse count to 2
    sf4.synapse[0].weight = 0.5
    sf4.synapse[0].delay = 1e-3
    sf4.synapse[1].weight = 2.0
    sf4.synapse[1].delay = 2e-3
    moose.connect(sg1, 'spikeOut', sf4.synapse[0], 'addSpike')
    moose.connect(sg2, 'spikeOut', sf4.synapse[1], 'addSpike')
示例#2
0
def make_synapse(path):
    """Create a synapse with two time constants."""
    syn = moose.SynChan(path)
    syn.tau1 = 5.0  # ms
    syn.tau2 = 1.0  # ms
    syn.Gbar = 1.0  # mS
    syn.Ek = 0.0
    synsh = moose.SimpleSynHandler(path + '/sh')
    synsh.synapse.num = 1
    # syn.bufferTime = 1.0 # ms
    synsh.synapse.delay = 1.0
    synsh.synapse.weight = 1.0
    print(('Synapses:', len(synsh.synapse), 'w=', synsh.synapse[0].weight))
    spikegen = moose.SpikeGen('%s/spike' % (syn.parent.path))
    spikegen.edgeTriggered = False  # Make it fire continuously when input is high
    spikegen.refractT = 10.0  # With this setting it will fire at 1 s / 10 ms = 100 Hz
    spikegen.threshold = 0.5
    # This will send alternatind -1 and +1 to SpikeGen to make it fire
    spike_stim = moose.PulseGen('%s/spike_stim' % (syn.parent.path))
    spike_stim.delay[0] = 50.0
    spike_stim.level[0] = 1.0
    spike_stim.width[0] = 100.0
    moose.connect(spike_stim, 'output', spikegen, 'Vm')
    m = moose.connect(spikegen, 'spikeOut', synsh.synapse[0], 'addSpike')
    return syn, spikegen
示例#3
0
def create_population(container, netparams, name_soma):
    netpath = container.path
    proto=[]
    neurXclass={}
    locationlist=[]
    #determine total number of neurons
    size,numneurons,vol=count_neurons(netparams)
    pop_percent=[]
    for neurtype in netparams.pop_dict.keys():
        if moose.exists(neurtype):
            proto.append(moose.element(neurtype))
            neurXclass[neurtype]=[]
            pop_percent.append(netparams.pop_dict[neurtype].percent)
    #create cumulative array of probabilities for selecting neuron type
    choicearray=np.cumsum(pop_percent)
    if choicearray[-1]<1.0:
        log.info("Warning!!!! fractional populations sum to {}",choicearray[-1])
    #array of random numbers that will be used to select neuron type
    rannum = np.random.uniform(0,choicearray[-1],numneurons)
    #Error check for last element in choicearray equal to 1.0
    log.info("numneurons= {} {} choicarray={}", size, numneurons, choicearray)
    log.debug("rannum={}", rannum)
    for i,xloc in enumerate(np.linspace(netparams.grid[0]['xyzmin'], netparams.grid[0]['xyzmax'], size[0])):
        for j,yloc in enumerate(np.linspace(netparams.grid[1]['xyzmin'], netparams.grid[1]['xyzmax'], size[1])):
            for k,zloc in enumerate(np.linspace(netparams.grid[2]['xyzmin'], netparams.grid[2]['xyzmax'], size[2])):
                #for each location in grid, assign neuron type, update soma location, add in spike generator
                neurnumber=i*size[2]*size[1]+j*size[2]+k
                neurtypenum=np.min(np.where(rannum[neurnumber]<choicearray))
                log.debug("i,j,k {} {} {} neurnumber {} type {}", i,j,k, neurnumber, neurtypenum)
                typename = proto[neurtypenum].name
                tag = '{}_{}'.format(typename, neurnumber)
                new_neuron=moose.copy(proto[neurtypenum],netpath, tag)
                neurXclass[typename].append(container.path + '/' + tag)
                comp=moose.element(new_neuron.path + '/'+name_soma)
                comp.x=i*xloc
                comp.y=j*yloc
                comp.z=k*zloc
                log.debug("x,y,z={},{},{} {}", comp.x, comp.y, comp.z, new_neuron.path)
                locationlist.append([new_neuron.name,comp.x,comp.y,comp.z])
                #spike generator - can this be done to the neuron prototype?
                spikegen = moose.SpikeGen(comp.path + '/spikegen')
                #should these be parameters in netparams?
                spikegen.threshold = 0.0
                spikegen.refractT=1e-3
                m = moose.connect(comp, 'VmOut', spikegen, 'Vm')
    #Create variability in neurons of network
    for neurtype in netparams.chanvar.keys():
        for chan,var in netparams.chanvar[neurtype].items():
            #single multiplier for Gbar for all the channels compartments
            if var>0:
                log.debug('adding variability to {} soma {}, variance: {}', neurtype,chan, var)
                GbarArray=abs(np.random.normal(1.0, var, len(neurXclass[neurtype])))
                for ii,neurname in enumerate(neurXclass[neurtype]):
                    soma_chan_path=neurname+'/'+name_soma+'/'+chan
                    if moose.exists(soma_chan_path):
                        chancomp=moose.element(soma_chan_path)
                        chancomp.Gbar=chancomp.Gbar*GbarArray[ii]
    #
    return {'location': locationlist,
            'pop':neurXclass}
示例#4
0
def many_ematrix_to_one_element():
    """This is an example of event messages from multiple SpikeGen objects
    into a synchan.

    Create a SynChan element with 2 elements in synapse field.

    Create 5 SpikeGen elements.

    Connect alternet SpikeGen elements to synapse[0] and synapse[1]

    ... This is a minimal example. In real simulations the SpikeGens
    will be embedded in compartments representing axon terminals and
    the SynChans will be embedded in somatic/dendritic compartments.

    """
    model = moose.Neutral('/model')
    # data = moose.Neutral('/data')
    synchan = moose.SynChan('/model/synchan')
    synh = moose.SimpleSynHandler('/model/synchan/synh')
    moose.connect(synh, 'activationOut', synchan, 'activation')
    synh.synapse.num = 2
    num_spikegen = 5
    spikegens = [
        moose.SpikeGen('/model/spikegen_%d' % (ii))
        for ii in range(num_spikegen)
    ]
    for ii in range(num_spikegen):
        msg = moose.connect(spikegens[ii], 'spikeOut', synh.synapse[ii % 2],
                            'addSpike')
        # synchan.synapse[ii].delay = ii  * 1e-3
        # synchan.synapse[ii].weight = (ii+1) * 0.1
    for sg in spikegens:
        print(sg.path, '-->', end=' ')
        for m in sg.msgOut:
            print(moose.element(m).adjacent[sg].path)
示例#5
0
def make_spiny_compt():
    comptLength = 100e-6
    comptDia = 4e-6
    numSpines = 5
    compt = create_squid()
    compt.inject = 0
    compt.x0 = 0
    compt.y0 = 0
    compt.z0 = 0
    compt.x = comptLength
    compt.y = 0
    compt.z = 0
    compt.length = comptLength
    compt.diameter = comptDia
    synInput = moose.SpikeGen('/n/compt/synInput')
    synInput.refractT = 47e-3
    synInput.threshold = -1.0
    synInput.edgeTriggered = 0
    synInput.Vm(0)
    cell = moose.element('/n')
    for i in range(numSpines):
        r = create_spine_with_receptor(compt, cell, i, i / float(numSpines))
        r.synapse.num = 1
        syn = moose.element(r.path + '/synapse')
        moose.connect(synInput, 'spikeOut', syn, 'addSpike', 'single')
        syn.weight = 0.2
        syn.delay = i * 1.0e-4
示例#6
0
def make_synapse(comp):
    nmda, mgblock = make_NMDA(comp)
    ampa = make_AMPA(comp)
    spikegen = moose.SpikeGen('%s/spike' % (comp.path))
    moose.connect(spikegen, 'spikeOut', ampa.synapse[0], 'addSpike')
    moose.connect(spikegen, 'spikeOut', nmda.synapse[0], 'addSpike')
    return {'ampa': ampa, 'nmda': nmda, 'mgblock': mgblock, 'spike': spikegen}
示例#7
0
def makeSpinyCompt():
    comptLength = 30e-6
    comptDia = 6e-6
    numSpines = 5
    compt = createSquid()
    compt.inject = 0
    compt.x0 = 0
    compt.y0 = 0
    compt.z0 = 0
    compt.x = comptLength
    compt.y = 0
    compt.z = 0
    compt.length = comptLength
    compt.diameter = comptDia
    #kchan = moose.element( '/n/compt/K' )
    #kchan.Gbar = 0.2e-3
    synInput = moose.SpikeGen('/n/compt/synInput')
    synInput.refractT = 47e-3
    synInput.threshold = -1.0
    synInput.edgeTriggered = 0
    synInput.Vm(0)
    cell = moose.element('/n')
    for i in range(numSpines):
        r = createSpineWithReceptor(compt, cell, i, i / float(numSpines))
        r.synapse.num = 1
        syn = moose.element(r.path + '/synapse')
        moose.connect(synInput, 'spikeOut', syn, 'addSpike', 'Single')
        syn.weight = 0.2 * i * (4 - i)
        syn.delay = i * 1.0e-3
示例#8
0
def testNMDAChan(simtime=1.0, simdt=1e-5, plotdt=1e-5):
    context = moose.PyMooseBase.getContext()
    container = moose.Neutral('test_NMDA')

    soma_b = moose.Compartment('B', container)
    soma_b.Rm = 5.3e9 # GM = 2e-5 S/cm^2
    soma_b.Cm = 8.4823001646924426e-12 # CM = 0.9 uF/cm^2
    soma_b.Em = -65e-3 
    soma_b.initVm = -65e-3
    soma_b.Ra = 282942.12 # RA = 250 Ohm-cm
    
    nmda = moose.NMDAChan('nmda', container)
    nmda.tau2 = 5e-3
    nmda.tau1 = 130e-3
    nmda.Gbar = 1e-9
    nmda.saturation = 1e10
    nmda.connect('channel', soma_b, 'channel')
    spikegen = moose.SpikeGen('spike', container)
    spikegen.threshold = 0.5
    spikegen.connect('event', nmda, 'synapse')
    spikegen.refractT = 0.0
    nmda.delay[0] = 1e-3
    nmda.weight[0] = 1.0
    
    pulsegen = moose.PulseGen('pulse', container)
    pulsegen.setCount(3)
    pulsegen.level[0] = 1.0
    pulsegen.delay[0] = 10e-3
    pulsegen.width[0] = 1e-3
    pulsegen.level[1] = 1.0
    pulsegen.delay[1] = 2e-3
    pulsegen.width[1] = 1e-3    
    pulsegen.delay[2] = 1e9
    pulsegen.connect('outputSrc', spikegen, 'Vm')

    data = moose.Neutral('data')
    vmB = moose.Table('Vm_B', data)
    vmB.stepMode = 3
    vmB.connect('inputRequest', soma_b, 'Vm')
    pulse = moose.Table('pulse', data)
    pulse.stepMode = 3
    pulse.connect('inputRequest', pulsegen, 'output')
    gNMDA = moose.Table('G', data)
    gNMDA.stepMode = 3
    gNMDA.connect('inputRequest', nmda, 'Gk')

    context.setClock(0, simdt)
    context.setClock(1, simdt)
    context.setClock(2, simdt)
    context.setClock(3, plotdt)
    context.reset()
    context.step(simtime)
    # gNMDA.dumpFile('gNMDA.dat', False)
    # vmA.dumpFile('Va.dat', False)
    # vmB.dumpFile('Vb.dat', False)
    ts = np.linspace(0, simtime, len(gNMDA))
    pylab.plot(ts, pulse)
    pylab.plot(ts, np.asarray(gNMDA) * 1e9, label='gNMDA')
    pylab.show()
    np.savetxt('../data/two_comp_nmda.plot', np.transpose(np.vstack((ts, vmB, gNMDA))))
def create_compartment(path):
    comp = moose.Compartment(path)
    comp.diameter = soma_dia
    comp.Em = EREST_ACT + 10.613e-3
    comp.initVm = EREST_ACT
    sarea = np.pi * soma_dia * soma_dia
    comp.Rm = 1/(0.3e-3 * 1e4 * sarea)
    comp.Cm = 1e-6 * 1e4 * sarea
    if moose.exists('/library/na'):
        nachan = moose.element(moose.copy('/library/na', comp, 'na'))
    else:
        nachan = create_na_chan(comp.path)
    nachan.Gbar = 120e-3 * sarea * 1e4
    moose.showfield(nachan)
    moose.connect(nachan, 'channel', comp, 'channel')
    if moose.exists('/library/k'):
        kchan = moose.element(moose.copy('/library/k', comp, 'k'))
    else:
        kchan = create_k_chan(comp.path)
    kchan.Gbar = 36e-3 * sarea * 1e4
    moose.connect(kchan, 'channel', comp, 'channel')
    synchan = moose.SynChan(comp.path + '/synchan')
    synchan.Gbar = 1e-8
    synchan.tau1 = 2e-3
    synchan.tau2 = 2e-3
    synchan.Ek = 0.0
    m = moose.connect(comp, 'channel', synchan, 'channel')
    spikegen = moose.SpikeGen(comp.path + '/spikegen')
    spikegen.threshold = 0.0
    m = moose.connect(comp, 'VmOut', spikegen, 'Vm')
    return comp
def createSynapseOnCompartment(compt):
    FaradayConst = 96485.3415  # s A / mol
    length = compt.length
    dia = compt.diameter

    gluR = moose.SynChan(compt.path + '/gluR')
    gluR.tau1 = 4e-3
    gluR.tau2 = 4e-3
    gluR.Gbar = 1e-6
    gluR.Ek = 10.0e-3
    moose.connect(compt, 'channel', gluR, 'channel', 'Single')
    gluSyn = moose.SimpleSynHandler(compt.path + '/gluR/sh')
    moose.connect(gluSyn, 'activationOut', gluR, 'activation')
    gluSyn.synapse.num = 1
    # Ca comes in through this channel, at least for this example.
    caPool = moose.CaConc(compt.path + '/ca')
    caPool.CaBasal = 1e-4  # 0.1 micromolar
    caPool.tau = 0.01
    B = 1.0 / (FaradayConst * length * dia * dia * math.pi / 4)
    B = B / 20.0  # scaling factor for Ca buffering
    caPool.B = B
    moose.connect(gluR, 'IkOut', caPool, 'current', 'Single')
    # Provide a regular synaptic input.
    synInput = moose.SpikeGen('/n/elec/compt/synInput')
    synInput.refractT = 47e-3
    synInput.threshold = -1.0
    synInput.edgeTriggered = 0
    synInput.Vm(0)
    syn = moose.element(gluSyn.path + '/synapse')
    moose.connect(synInput, 'spikeOut', syn, 'addSpike', 'Single')
    syn.weight = 0.2
    syn.delay = 1.0e-3
    return gluR
示例#11
0
def make_synapse(path):
    """Create a synapse with two time constants. Connect a spikegen to the
    synapse. Create a pulsegen to drive the spikegen."""
    syn = moose.SynChan(path)
    syn.tau1 = 5.0  # ms
    syn.tau2 = 1.0  # ms
    syn.Gk = 1.0  # mS
    syn.Ek = 0.0
    syn.synapse.num = 1
    # syn.bufferTime = 1.0 # ms
    syn.synapse.delay = 1.0
    syn.synapse.weight = 1.0
    print 'Synapses:', len(syn.synapse), 'w=', syn.synapse[0].weight
    spikegen = moose.SpikeGen('%s/spike' % (syn.parent.path))
    spikegen.edgeTriggered = False  # Make it fire continuously when input is high
    spikegen.refractT = 10.0  # With this setting it will fire at 1 s / 10 ms = 100 Hz
    spikegen.threshold = 0.5
    # This will send alternatind -1 and +1 to SpikeGen to make it fire
    spike_stim = moose.PulseGen('%s/spike_stim' % (syn.parent.path))
    spike_stim.delay[0] = 1.0
    spike_stim.level[0] = 1.0
    spike_stim.width[0] = 100.0
    moose.connect(spike_stim, 'output', spikegen, 'Vm')
    # m = moose.connect(spikegen, 'spikeOut', syn.synapse.vec, 'addSpike', 'Sparse')
    # m.setRandomConnectivity(1.0, 1)
    m = moose.connect(spikegen, 'spikeOut', syn.synapse[0],
                      'addSpike')  # this causes segfault
    return syn, spikegen
示例#12
0
文件: nsdf.py 项目: physicalist/moose
def setup_model():
    """Setup a dummy model with a pulsegen and a spikegen detecting the
    leading edges of the pulses. We record the pulse output as Uniform
    data and leading edge time as Event data."""
    simtime = 100.0
    dt = 1e-3
    model = moose.Neutral('/model')
    pulse = moose.PulseGen('/model/pulse')
    pulse.level[0] = 1.0
    pulse.delay[0] = 10
    pulse.width[0] = 20
    t_lead = moose.SpikeGen('/model/t_lead')
    t_lead.threshold = 0.5
    moose.connect(pulse, 'output', t_lead, 'Vm')
    nsdf = moose.NSDFWriter('/model/writer')
    nsdf.filename = 'nsdf_demo.h5'
    nsdf.mode = 2  #overwrite existing file
    nsdf.flushLimit = 100
    moose.connect(nsdf, 'requestOut', pulse, 'getOutputValue')
    print 'event input', nsdf.eventInput, nsdf.eventInput.num
    print nsdf

    nsdf.eventInput.num = 1
    ei = nsdf.eventInput[0]
    print ei.path
    moose.connect(t_lead, 'spikeOut', nsdf.eventInput[0], 'input')
    tab = moose.Table('spiketab')
    tab.threshold = t_lead.threshold
    clock = moose.element('/clock')
    for ii in range(32):
        moose.setClock(ii, dt)
    moose.connect(pulse, 'output', tab, 'spike')
    print datetime.now().isoformat()
    moose.reinit()
    moose.start(simtime)
    print datetime.now().isoformat()
    np.savetxt('nsdf.txt', tab.vector)
    ###################################
    # Set the environment attributes
    ###################################
    nsdf.stringAttr['title'] = 'NSDF writing demo for moose'
    nsdf.stringAttr[
        'description'] = '''An example of writing data to NSDF file from MOOSE simulation. In
this simulation we generate square pules from a PulseGen object and
use a SpikeGen to detect the threshold crossing events of rising
edges. We store the pulsegen output as Uniform data and the threshold
crossing times as Event data. '''
    nsdf.stringAttr['creator'] = getpass.getuser()
    nsdf.stringVecAttr['software'] = ['python2.7', 'moose3']
    nsdf.stringVecAttr['method'] = ['']
    nsdf.stringAttr['rights'] = ''
    nsdf.stringAttr['license'] = 'CC-BY-NC'
    # Specify units. MOOSE is unit agnostic, so we explicitly set the
    # unit attibutes on individual datasets
    nsdf.stringAttr['/data/uniform/PulseGen/outputValue/tunit'] = 's'
    nsdf.stringAttr['/data/uniform/PulseGen/outputValue/unit'] = 'A'
    eventDataPath = '/data/event/SpikeGen/spikeOut/{}_{}_{}/unit'.format(
        t_lead.vec.value, t_lead.getDataIndex(), t_lead.getFieldIndex())
    nsdf.stringAttr[eventDataPath] = 's'
示例#13
0
def test_synintegration(filename, target_cell, source_type):
    sim = Simulation('synintegration')
    cell = SpinyStellate(SpinyStellate.prototype, 
                         sim.model.path + '/SpinyStellate')
    vm_table = cell.comp[cell.presyn].insertRecorder('Vm', 'Vm', sim.data)
    # Create a common spike gen object
    sp = moose.SpikeGen('spike', sim.model)
    sp.threshold = 0.0
    sp.edgeTriggered = 1
    sptab = moose.Table('spike', sim.data)
    sptab.stepMode = 3
    sptab.connect('inputRequest', sp, 'state')
    (comp_indices, syntype, gbar, tau1, tau2, Ek, ) = \
        get_syninfo(filename, target_cell, source_type)    
    # Set up the synapses
    for ii in range(len(comp_indices)):
        print '%d\t%s\t%g\t%g\t%g\t%g' % (comp_indices[ii], 
                                          syntype[ii], 
                                          gbar[ii], 
                                          tau1[ii], 
                                          tau2[ii], 
                                          Ek[ii])
        comp = cell.comp[comp_indices[ii]]
        weight = 1.0
        if syntype[ii] == 'nmda':
            chan = moose.NMDAChan('nmda_from_%s' % (source_type), comp)
            chan.MgConc = 1.5            
            weight = gbar[ii]
        else:
            chan = moose.SynChan('%s_from_%s' % (syntype[ii], source_type), 
                                 comp)
        chan.Gbar = gbar[ii]
        chan.tau1 = tau1[ii]
        chan.tau2 = tau2[ii]
        chan.Ek = Ek[ii]
        comp.connect('channel', chan, 'channel')
        sp.connect('event', chan, 'synapse')
        count = chan.numSynapses
        if source_type == 'TCR':
            chan.delay[count-1] = 1e-3 # thalamocortical delay
        else:
            chan.delay[count-1] = 0.05e-3 # default delay
        chan.weight[count-1] = weight
        gktable = moose.Table('%s_%s_%s' % (cell.name, comp.name, chan.name), sim.data)
        gktable.stepMode = 3
        gktable.connect('inputRequest', chan, 'Gk')
    pulsegen = moose.PulseGen('pulse', sim.model)
    pulsegen.firstDelay = 3.0
    pulsegen.firstLevel = 1.0
    pulsegen.firstWidth = 1e-3
    pulsegen.trigMode = moose.FREE_RUN
    pulsegen.connect('outputSrc', sp, 'Vm')
    ptable = moose.Table('pulse', sim.data)
    ptable.stepMode = 3
    ptable.connect('inputRequest', pulsegen, 'output')
    sim.schedule(simdt=1e-6, plotdt=1e-6)
    sim.run(10.0)
    sim.save_data_h5(filename.replace('network_', 'synintegration_'))
示例#14
0
    def makeSynapse(self,
                    target,
                    classname='SynChan',
                    name='synapse',
                    threshold=0.0,
                    absRefract=1.5e-3,
                    Ek=0.0,
                    Gbar=None,
                    tau1=None,
                    tau2=None,
                    weight=1.0,
                    delay=0.0,
                    Pr=1.0):
        """Make a synaptic connection from this compartment to target
        compartment and set the properties of the synaptic connection
        as specified in the parametrs.

        For NMDAChan, [Mg2+] has to be set separately. Also note that
        the weight and delay vectors are not available until reset is
        called. So these must be assigned afterwards.

        """
        classobj = eval('moose.' + classname)
        synapse = classobj(name, target)
        synapse.Ek = float(Ek)  # TODO set value according to original model
        synapse.Gbar = float(
            Gbar)  # TODO set value according to original model
        synapse.tau1 = float(tau1)
        synapse.tau2 = float(tau2)
        target.connect('channel', synapse, 'channel')
        spikegen = None
        spikegen = moose.SpikeGen('%s/spike' % (self.path))
        spikegen.threshold = float(threshold)
        spikegen.absRefract = float(absRefract)
        self.connect('VmSrc', spikegen, 'Vm')
        if not spikegen.connect('event', synapse, 'synapse'):
            raise Exception('Error creating connection: %s->%s' %
                            (spikegen.path, synapse.path))
        # This is too much of log info. Hence commenting out.
        # else:
        #     config.LOGGER.debug('Connected %s->%s' % (spikegen.path, synapse.path))

        # We had an awkward situation here: the weight and delay
        # vectors were not updated until reset/setDelay/setWeight was
        # called.  So we had to use num_synapse (which should
        # actually have been incremented by 1 due to the connection)
        # instead of (num_synapse - 1).
        # 2010-03-29 After making a mandatory call to updateNumSynapse()
        # in getNumSynapses(), this is fixed.
        num_synapses = synapse.numSynapses
        synapse.delay[num_synapses - 1] = float(delay)
        synapse.weight[num_synapses - 1] = float(weight)
        if config.stochastic:
            synapse.initPr[num_synapses - 1] = Pr
        config.LOGGER.debug('Created synapse: %s of type %s' %
                            (synapse.path, synapse.className))
        return synapse
示例#15
0
def init_channel_lib():
    """Initialize the prototype channels in library"""
    if not config.channel_lib:
        config.LOGGER.debug('* Generating channel prototypes in /library')
        for channel_name in config.channel_name_list:
            channel_class = eval(channel_name)
            channel = channel_class(channel_name, config.lib)
            config.channel_lib[channel_name] = channel
            config.LOGGER.debug('* Created %s' % (channel.path))
        config.channel_lib['SpikeGen'] = moose.SpikeGen('spike', config.lib)
    return config.channel_lib
示例#16
0
def connect_spikegen():
    """Connect a SpikeGen object to an IntFire neuron such that spike
    events in spikegen get transmitted to the synapse of the IntFire
    neuron."""
    if3 = moose.IntFire('if3')
    sf3 = moose.SimpleSynHandler('if3/sh')
    moose.connect(sf3, 'activationOut', if3, 'activation')
    sf3.synapse.num = 1
    sg = moose.SpikeGen('sg')
    syn = moose.element(sf3.synapse)
    moose.connect(sg, 'spikeOut', syn, 'addSpike')
示例#17
0
def spiketables(neuron,param_cond):
    spiketab=[]
    for neur in neuron.keys():
        soma=moose.element(neur+'/'+param_cond.NAME_SOMA)
        spikegen=moose.SpikeGen(soma.path+'/spikegen')
        spikegen.threshold=0.0
        spikegen.refractT=1.0e-3
        msg=moose.connect(soma,'VmOut',spikegen,'Vm')
        spiketab.append(moose.Table('/data/spike_'+neur))
        moose.connect(spikegen,'spikeOut',spiketab[-1],'spike')
    return spiketab
示例#18
0
def create_spikegen(name, type, refractory_period, rate=None, threshold=None):
    ''' Create spikegen which is used as pre synaptic trigger.
    '''
    if not moose.exists('/spikegens'):
        spikelib = moose.Neutral('/spikegens')
    if type.lower() in "random" and rate is not None:
        spikegen = moose.RandSpike('/spikegens/' + name)
        spikegen.rate = np.float(rate)
    elif type.lower() in "linear" and threshold is not None:
        spikegen = moose.SpikeGen('/spikegens/' + name)
        spikegen.threshold = np.float(threshold)
    spikegen.refractT = np.float(refractory_period)
    return spikegen
示例#19
0
def synintegration2(filename, target_cell):
    raise NotImplementedError
    syntab = None
    netfile = h5.File(filename, 'r')
    syntab = netfile['network/synapse'][:]
    idx = np.char.startswith(syntab['dest'], target_cell)
    syntab = syntab[idx]
    sim = Simulation('synintegration')
    cell = SpinyStellate(SpinyStellate.prototype, 
                         sim.model.path + '/SpinyStellate')
    vm_table = cell.comp[cell.presyn].insertRecorder('Vm', 'Vm', sim.data)
    # Create a common spike gen object
    sp = moose.SpikeGen('spike', sim.model)
    sp.threshold = 0.0
    sp.edgeTriggered = 1
    sptab = moose.Table('spike', sim.data)
    sptab.stepMode = 3
    sptab.connect('inputRequest', sp, 'state')
    for ii in range(len(syntab)):
        source = syntab['source'][ii].partition('/')[0]
        dest, compname = syntab['dest'][ii].split('/')
        if source == dest:
            print 'source = dest', source, filename
            continue
        comp_no = compname.split('_')[-1]
        comp = cell[int(comp_no)]
        weight = 1.0
        if syntab['type'][ii] == 'nmda':
            chan = moose.NMDAChan('nmda_from_%s' % 
                                  (source.split('_')[0]), comp)
            chan.MgConc = 1.5            
            weight = syntab['Gbar'][ii]
        else:
            chan = moose.SynChan('%s_from_%s' % 
                                 (syntab['type'][ii], source.split('_')[0]), 
                                 comp)
        chan.Gbar = syntab['Gbar'][ii]
        chan.tau1 = syntab['tau1'][ii]
        chan.tau2 = syntab['tau2'][ii]
        chan.Ek = syntab['Ek'][ii]
        comp.connect('channel', chan, 'channel')
        sp.connect('event', chan, 'synapse')
        count = chan.numSynapses
        if source_type == 'TCR':
            chan.delay[count-1] = 1e-3 # thalamocortical delay
        else:
            chan.delay[count-1] = 0.05e-3 # default delay
        chan.weight[count-1] = weight
        gktable = moose.Table('%s_%s_%s' % (cell.name, comp.name, chan.name), sim.data)
        gktable.stepMode = 3
        gktable.connect('inputRequest', chan, 'Gk')
示例#20
0
    def createNetwork(self):
        '''setting up of the cells and their connections'''
        hopfield = moose.Neutral('/hopfield')
        pg = moose.PulseGen('/hopfield/inPulGen')

        pgTable = moose.Table('/hopfield/inPulGen/pgTable')
        moose.connect(pgTable, 'requestOut', pg, 'getOutputValue')

        pg.firstDelay = 10e-3
        pg.firstWidth = 2e-03
        pg.firstLevel = 3.0
        pg.secondDelay = 1.0

        for i in range(self.numNeurons):
            cellPath = '/hopfield/cell_' + str(i)
            cell = moose.IntFire(cellPath)
            cell.setField('tau', 10e-3)
            cell.setField('refractoryPeriod', 5e-3)
            cell.setField('thresh', 0.99)
            cell.synapse.num = self.numNeurons
            #definite firing everytime ip is given
            cell.synapse[i].weight = 1.00  #synapse i = input synapse
            cell.synapse[i].delay = 0.0  #1e-3 #instantaneous

            #VmVals = moose.Table(cellPath+'/Vm_cell_'+str(i))
            #moose.connect(VmVals, 'requestOut', cell, 'getVm')
            spikeVals = moose.Table(cellPath + '/spike_cell_' + str(i))
            moose.connect(cell, 'spike', spikeVals, 'input')

            inSpkGen = moose.SpikeGen(cellPath + '/inSpkGen')
            inSpkGen.setField('edgeTriggered', True)
            inSpkGen.setField('threshold', 2.0)
            moose.connect(pg, 'output', inSpkGen, 'Vm')
            #inTable = moose.Table(cellPath+'/inSpkGen/inTable')
            #moose.connect(inTable, 'requestOut', inSpkGen, 'getHasFired')
            moose.connect(inSpkGen, 'spikeOut', cell.synapse[i],
                          'addSpike')  #self connection is the input
            self.inSpike.append(inSpkGen)
            #self.inTables.append(inTable)
            #self.Vms.append(VmVals)
            self.cells.append(cell)
            self.allSpikes.append(spikeVals)

        for ii in range(self.numNeurons):
            for jj in range(self.numNeurons):
                if ii == jj:
                    continue
                self.cells[jj].synapse[ii].weight = 0
                self.cells[jj].synapse[ii].delay = 20e-3
                moose.connect(self.cells[ii], 'spike',
                              self.cells[jj].synapse[ii], 'addSpike')
示例#21
0
def create_model():
    """Create two single compartmental neurons, neuron_A is the
    presynaptic neuron and neuron_B is the postsynaptic neuron.

        1. The presynaptic cell's Vm is monitored by a SpikeGen
        object. Whenever the Vm crosses the threshold of the spikegen, it
        sends out a spike event message.
    
        2. This is event message is received by a SynHandler, which
        passes the event as activation parameter to a SynChan object.

        3. The SynChan, which is connected to the postsynaptic neuron
        as a channel, updates its conductance based on the activation
        parameter.

        4. The change in conductance due to a spike may evoke an
        action potential in the post synaptic neuron.

    """
    model = moose.Neutral('/model')
    nrn_a = create_1comp_neuron('/model/neuron_A')[0]
    nrn_b = create_1comp_neuron('/model/neuron_B')[0]
    #: SynChan for post synaptic neuron
    synchan = moose.SynChan('/model/neuron_B/synchan')
    synchan.Gbar = 1e-8
    synchan.tau1 = 2e-3
    synchan.tau2 = 2e-3
    msg = moose.connect(nrn_b, 'channel', synchan, 'channel')
    #: Create SynHandler to handle spike event input and set the
    #: activation input of synchan
    synhandler = moose.SimpleSynHandler('/model/neuron_B/synhandler')
    synhandler.synapse.num = 1
    synhandler.synapse[0].delay = 5e-3
    moose.connect(synhandler, 'activationOut', synchan, 'activation')
    #: SpikeGen detects when presynaptic Vm crosses threshold and
    #: sends out a spike event
    spikegen = moose.SpikeGen('/model/neuron_A/spikegen')
    spikegen.threshold = 0.0
    msg = moose.connect(nrn_a, 'VmOut', spikegen, 'Vm')
    msg = moose.connect(spikegen, 'spikeOut', synhandler.synapse[0],
                        'addSpike')
    return {
        'presynaptic': nrn_a,
        'postsynaptic': nrn_b,
        'spikegen': spikegen,
        'synchan': synchan,
        'synhandler': synhandler
    }
示例#22
0
def loadModel(filename):
    global soma_, cellSpikeTable_
    neuromlR = NeuroML()
    neuromlR.readNeuroMLFromFile(filename)
    libcell = moose.Neuron('/library/CA1soma')
    CA1Cellid = moose.copy(libcell,moose.Neutral('/cells'),'CA1')
    CA1Cell = moose.Neuron(CA1Cellid)

    spikeGen = moose.SpikeGen(CA1Cell.path+'/spikeGen')
    spikeGen.threshold = -30e-3 # V
    soma_ = moose.Compartment(CA1Cell.path+'/Seg0_soma_0_0')
    soma_.inject = 0 # by default the cell has a current injection
    moose.connect(soma_,'VmOut',spikeGen,'Vm')
    table_path = moose.Neutral(CA1Cell.path+'/data').path
    cellSpikeTable_ = moose.Table(table_path+'/spikesTable')
    moose.connect(spikeGen,'spikeOut', cellSpikeTable_,'input')
示例#23
0
def init_chanlib():
    """Return a dict of channel name, channel prototype pairs. If the
    channel prototypes have not been initialized, this functions
    initializes the same."""
    global _channels
    if _channels:
        return _channels
    if not moose.exists(config.modelSettings.libpath):
        moose.Neutral(config.modelSettings.libpath)
    _channels.update(nachans.initNaChannelPrototypes())
    _channels.update(kchans.initKChannelPrototypes())
    _channels.update(archan.initARChannelPrototypes())
    _channels.update(cachans.initCaChannelPrototypes())
    _channels.update(capool.initCaPoolPrototypes())
    _channels['spike'] = moose.SpikeGen('{}/spike'.format(
        config.modelSettings.libpath))
    return _channels
示例#24
0
def get_targets(cell_paths):
    """Get the cells post synaptic to cells listed in cell_paths."""
    # print '###', cell_paths
    target_sources_map = defaultdict(list)
    for cp in cell_paths:
        # print '###', cp
        sg_list = moose.context.getWildcardList(cp + '/##[TYPE=SpikeGen]', True)
        for sg in sg_list:
            sg = moose.SpikeGen(sg)
            for synId in sg.neighbours('event', 2):
                print synId.path()
                syn = moose.Neutral(synId)
                if not(syn.className == 'SynChan' or syn.className == 'NMDAChan'):
                    continue
                for comp in moose.Neutral(synId).neighbours('channel', 2):
                    # print '-->', comp.path()
                    target_sources_map[comp.path().rpartition('/')[0]].append(cp)
    return target_sources_map
示例#25
0
 def __init__(self, *args):
     moose.Compartment.__init__(self, *args)
     self.spikegen = moose.SpikeGen('%s/spike' % (self.path))
     self.spikegen.edgeTriggered = 1 # This ensures that spike is generated only on leading edge.
     self.dynamics = moose.Func('%s/dynamics' % (self.path))
     self.initVm = 0.0
     self.Rm = 10e6
     self.Ra = 1e4
     self.Cm = 100e-9
     self.Em = 0 #-65e-3
     self.initVm = 0 #self.Em
     
     # Note that the result is dependent on exact order of
     # execution of SpikeGen and Func. If Func gets executed first
     # SpikeGen will never cross threshold.
     self.dynamics.expr = 'x >= y? z: x'
     moose.connect(self, 'VmOut', self.dynamics, 'xIn')
     moose.connect(self.dynamics, 'valueOut', self, 'setVm')
     moose.connect(self, 'VmOut', self.spikegen, 'Vm')
示例#26
0
def make_synapse(path):
    """Create a synapse with two time constants. Connect a spikegen to the
    synapse. Create a pulsegen to drive the spikegen."""

    syn = moose.SynChan(path)
    syn.tau1 = 5.0  # ms
    syn.tau2 = 1.0  # ms
    syn.Gk = 1.0  # mS
    syn.Ek = 0.0

    ## NOTE: This is old implementation.
    #syn.synapse.num = 1
    ## syn.bufferTime = 1.0 # ms
    #syn.synapse.delay = 1.0
    #syn.synapse.weight = 1.0
    #print 'Synapses:', len(syn.synapse), 'w=', syn.synapse[0].weight

    # IN new implementation, there is SimpleSynHandler class which takes cares
    # of multiple synapses. Class SynChan does not have any .synapse field.
    synH = moose.SimpleSynHandler('%s/SynHandler' % path)
    synH.synapse.num = 1
    ## syn.bufferTime = 1.0 # ms
    synH.synapse.delay = 1.0
    synH.synapse.weight = 1.0
    synH.connect('activationOut', syn, 'activation')
    print(('Synapses:', len(synH.synapse), 'w=', synH.synapse[0].weight))

    spikegen = moose.SpikeGen('%s/spike' % (syn.parent.path))
    spikegen.edgeTriggered = False  # Make it fire continuously when input is high
    spikegen.refractT = 10.0  # With this setting it will fire at 1 s / 10 ms = 100 Hz
    spikegen.threshold = 0.5
    # This will send alternatind -1 and +1 to SpikeGen to make it fire
    spike_stim = moose.PulseGen('%s/spike_stim' % (syn.parent.path))
    spike_stim.delay[0] = 1.0
    spike_stim.level[0] = 1.0
    spike_stim.width[0] = 100.0
    moose.connect(spike_stim, 'output', spikegen, 'Vm')
    m = moose.connect(spikegen, 'spikeOut', synH.synapse.vec, 'addSpike',
                      'Sparse')
    m.setRandomConnectivity(1.0, 1)
    m = moose.connect(spikegen, 'spikeOut', synH.synapse[0],
                      'addSpike')  # this causes segfault
    return syn, spikegen
示例#27
0
    def __init__(self,
                 path,
                 syn_shape,
                 Cm=1.0,
                 Em=0.0,
                 Rm=1.0,
                 Vr=0.0,
                 Vt=1.0,
                 refractT=0.0,
                 inject=0.0,
                 tau_e=0.001,
                 tau_i=0.001,
                 e_e=0.0,
                 e_i=-0.07):
        moose.IntFire.__init__(self, path)
        self.Cm = Cm
        self.Em = Em
        self.Rm = Rm
        self.Vr = Vr
        self.Vt = Vt
        self.refractT = refractT
        self.inject = inject

        self.syn_shape = syn_shape
        self.esyn = moose.SynChan("%s/excitatory" % path)
        self.isyn = moose.SynChan("%s/inhibitory" % path)
        for syn in self.esyn, self.isyn:
            syn.tau2 = 1e-6  # instantaneous rise, for shape=='exp'
            syn.Gbar = 1 * uS
            self.connect("channel", syn, "channel")
            syn.n_incoming_connections = 0

        self.tau_e = tau_e
        self.tau_i = tau_i
        self.e_e = e_e
        self.e_i = e_i

        self.source = moose.SpikeGen("source", self)
        self.source.thresh = 0.0
        self.source.abs_refract = 2.0
        self.connect("VmSrc", self.source, "Vm")
        self.comp = self  # for recorder mixin
示例#28
0
def many_ematrix_to_one_element():
    model = moose.Neutral('/model')
    # data = moose.Neutral('/data')
    synchan = moose.SynChan('/model/synchan')
    synh = moose.SimpleSynHandler('/model/synchan/synh')
    moose.connect(synh, 'activationOut', synchan, 'activation')
    synh.synapse.num = 2
    num_spikegen = 5
    spikegens = [
        moose.SpikeGen('/model/spikegen_%d' % (ii))
        for ii in range(num_spikegen)
    ]
    for ii in range(num_spikegen):
        msg = moose.connect(spikegens[ii], 'spikeOut', synh.synapse[ii % 2],
                            'addSpike')
        # synchan.synapse[ii].delay = ii  * 1e-3
        # synchan.synapse[ii].weight = (ii+1) * 0.1
    for sg in spikegens:
        print(sg.path, '-->', end=' ')
        for m in sg.msgOut:
            print(moose.element(m).adjacent[sg].path)
示例#29
0
def setupmodel(modelpath, iaf_Rm, iaf_Cm, pulse_interval):
    """Create a LeakyIaF neuron under `modelpath` and a synaptic
    channel (SynChan) in it. Create a spike generator stimulated by a
    pulse generator to give input to the synapse.
    """
    model_container = moose.Neutral(modelpath)
    data_container = moose.Neutral(datapath)
    iaf = moose.LIF('%s/iaf' % (modelpath))
    iaf.Rm = iaf_Rm
    iaf.Cm = iaf_Cm
    iaf.initVm = -0.070
    iaf.Em = -0.065
    #iaf.Vreset = -0.070
    iaf.thresh = -0.055
    # iaf.refractoryPeriod = 0.005
    syn = moose.SynChan('%s/syn' % (iaf.path))
    synh = moose.SimpleSynHandler(syn.path + '/synh')
    moose.connect(synh, 'activationOut', syn, 'activation')
    synh.synapse.num = 1
    synh.synapse[0].delay = 0.01
    syn.Ek = 0.0
    syn.Gbar = 1.0
    moose.connect(syn, 'channel', iaf, 'channel')
    moose.connect(iaf, 'VmOut', syn, 'Vm')
    sg = moose.SpikeGen('%s/spike' % (modelpath))
    sg.threshold = 0.1
    moose.connect(sg, 'spikeOut', synh.synapse[0], 'addSpike')
    pg = moose.PulseGen('%s/pulse' % (modelpath))
    pg.delay[0] = pulse_interval
    pg.width[0] = 1e-3
    pg.level[0] = 0.5
    moose.connect(pg, 'output', sg, 'Vm')
    return {
        'model': model_container,
        'iaf': iaf,
        'synchan': syn,
        'spikegen': sg,
        'pulsegen': pg
    }
示例#30
0
def setupTable(name,
               obj,
               qtyname,
               tables_path=None,
               threshold=None,
               spikegen=None):
    """ Sets up a table with 'name' which stores 'qtyname' field from 'obj'.
    The table is created under tables_path if not None, else under obj.path . """
    if tables_path is None:
        tables_path = obj.path + "/data"
    ## in case tables_path does not exist, below wrapper will create it
    tables_path_obj = moose.Neutral(tables_path)
    qtyTable = moose.Table(tables_path_obj.path + "/" + name)
    assert qtyTable, "%s not found" % qtyTable
    ## stepMode no longer supported, connect to 'input'/'spike' message dest to record Vm/spiktimes
    # qtyTable.stepMode = TAB_BUF
    if spikegen is None:
        if threshold is None:
            ## below is wrong! reads qty twice every clock tick!
            # moose.connect( obj, qtyname+'Out', qtyTable, "input")
            ## this is the correct method
            moose.connect(qtyTable, "requestOut", obj, "get" + qtyname)
        else:
            ## create new spikegen
            spikegen = moose.SpikeGen(tables_path_obj.path + "/" + name +
                                      "_spikegen")
            ## connect the compartment Vm to the spikegen
            moose.connect(obj, "VmOut", spikegen, "Vm")
            ## spikegens for different synapse_types can have different thresholds
            spikegen.threshold = threshold
            spikegen.edgeTriggered = (
                1  # This ensures that spike is generated only on leading edge.
            )
    else:
        moose.connect(spikegen, "spikeOut", qtyTable,
                      "input")  ## spikeGen gives spiketimes
    return qtyTable