Example #1
0
def setupTable(name, obj, qtyname, tablePath=None, threshold=None):
    '''This is replacement function for moose.utils.setupTable

    It stores qtyname from obj.
    '''
    assert qtyname[0].isupper(), "First character must be uppercase character"
    debug.printDebug("DEBUG"
            , "Setting up table for: {} -> get{}".format(obj.path, qtyname)
            )
    if tablePath is None:
        tablePath = '{}/{}'.format(obj.path, 'data')
        debug.printDebug("WARN"
                , "Using default table path: {}".format(tablePath)
                , frame = inspect.currentframe()
                )
    if not moose.exists(obj.path):
        raise RuntimeError("Unknown path {}".format(obj.path))

    moose.Neutral(tablePath)
    table = moose.Table('{}/{}'.format(tablePath, name))
    if threshold is None:
        moose.connect(table, "requestOut", obj, "get{}".format(qtyname))
    else:
        raise UserWarning("TODO: Table with threshold is not implemented yet")
    return table
Example #2
0
def make_NMDA( name ):
    if moose.exists( '/library/' + name ):
        return
    NMDA = moose.NMDAChan( '/library/' + name )
    NMDA.Ek = 0.0
    NMDA.tau1 = 20.0e-3
    NMDA.tau2 = 20.0e-3
    NMDA.Gbar = 5 * SOMA_A
    NMDA.CMg = 1.2		#	[Mg]ext in mM
    NMDA.KMg_A = 1.0/0.28
    NMDA.KMg_B = 1.0/62
    NMDA.temperature = 300  # Temperature in Kelvin.
    NMDA.extCa = 1.5        # [Ca]ext in mM
    NMDA.intCa = 0.00008        # [Ca]int in mM
    NMDA.intCaScale = 1         # Scale factor from elec Ca units to mM
    NMDA.intCaOffset = 0.00008  # Basal [Ca]int in mM
    NMDA.condFraction = 0.02  # Fraction of conductance due to Ca

    addmsg1 = moose.Mstring( NMDA.path + '/addmsg1' )
    addmsg1.value = '.	ICaOut ../Ca_conc current'
    addmsg2 = moose.Mstring( NMDA.path + '/addmsg2' )
    addmsg2.value = '../Ca_conc	concOut . assignIntCa'

    sh = moose.SimpleSynHandler( NMDA.path + '/sh' )
    moose.connect( sh, 'activationOut', NMDA, 'activation' )
    sh.numSynapses = 1
    sh.synapse[0].weight = 1
    return NMDA
Example #3
0
def example():
    """
    The RandSpike class generates spike events from a Poisson process
    and sends out a trigger via its `spikeOut` message. It is very
    common to approximate the spiking in many neurons as a Poisson
    process, i.e., the probability of `k` spikes in any interval `t`
    is given by the Poisson distribution:

        exp(-ut)(ut)^k/k! 

    for k = 0, 1, 2, ... u is the rate of spiking (the mean of the
    Poisson distribution). See `wikipedia
    <http://en.wikipedia.org/wiki/Poisson_process>`__ for details.

    Many cortical neuron types spontaneously fire action
    potentials. These are called ectopic spikes. In this example we
    simulate this with a RandSpike object with rate 10 spikes/s and
    send this to a single compartmental neuron via a synapse. 

    In this model the synaptic conductance is set so high that each
    incoming spike evokes an action potential.
    """
    ectopic = moose.RandSpike('ectopic_input')
    ectopic.rate = 10.0
    cellmodel = create_cell()
    moose.connect(ectopic, 'spikeOut', 
                  cellmodel['synhandler'].synapse[0], 'addSpike')
    tab_vm = moose.Table('/Vm')
    moose.connect(tab_vm, 'requestOut', cellmodel['neuron'], 'getVm')
    moose.reinit()
    moose.start(SIMTIME)
    return tab_vm
Example #4
0
def createFunction(fb,setpool,objB,objA):
    fapath1 = fb.path.replace(objB,objA)
    fapath = fapath1.replace('[0]','')

    if not moose.exists(fapath):
        # if fb.parent.className in ['CubeMesh','CyclMesh']:
        #   des = moose.Function('/'+objA+'/'+fb.parent.name+'/'+fb.name)
        # elif fb.parent.className in ['Pool','ZombiePool','BufPool','ZombieBufPool']:
        #   for akey in list(poolListina[findCompartment(fb).name]):
        #       if fb.parent.name == akey.name:
        #           des = moose.Function(akey.path+'/'+fb.name)
        des = moose.Function(fapath)
    else:
        des = moose.element(fapath)
    inputB = moose.element(fb.path+'/x').neighbors["input"]
    moose.connect(des, 'valueOut', moose.element(setpool),'setN' )
    inputA = []
    inputA = moose.element(fapath+'/x').neighbors["input"]
    if not inputA:
        for src in inputB:
            pool = ((src.path).replace(objB,objA)).replace('[0]','')
            numVariables = des.numVars
            expr = ""
            expr = (des.expr+'+'+'x'+str(numVariables))
            expr = expr.lstrip("0 +")
            expr = expr.replace(" ","")
            des.expr = expr
            moose.connect( pool, 'nOut', des.x[numVariables], 'input' )
Example #5
0
def run(nogui):
    
    reader = NML2Reader(verbose=True)

    filename = 'test_files/NML2_SingleCompHHCell.nml'
    print('Loading: %s'%filename)
    reader.read(filename, symmetric=True)
    
    
    msoma = reader.getComp(reader.doc.networks[0].populations[0].id,0,0)
    print(msoma)
    
    
    data = moose.Neutral('/data')
    
    pg = reader.getInput('pulseGen1')
    
    inj = moose.Table('%s/pulse' % (data.path))
    moose.connect(inj, 'requestOut', pg, 'getOutputValue')
    
    
    vm = moose.Table('%s/Vm' % (data.path))
    moose.connect(vm, 'requestOut', msoma, 'getVm')
    
    simdt = 1e-6
    plotdt = 1e-4
    simtime = 300e-3
    #moose.showmsg( '/clock' )
    for i in range(8):
        moose.setClock( i, simdt )
    moose.setClock( 8, plotdt )
    moose.reinit()
    moose.start(simtime)
    
    print("Finished simulation!")
    
    t = np.linspace(0, simtime, len(vm.vector))
    
    if not nogui:
        import matplotlib.pyplot as plt

        vfile = open('moose_v_hh.dat','w')

        for i in range(len(t)):
            vfile.write('%s\t%s\n'%(t[i],vm.vector[i]))
        vfile.close()
        plt.subplot(211)
        plt.plot(t, vm.vector * 1e3, label='Vm (mV)')
        plt.legend()
        plt.title('Vm')
        plt.subplot(212)
        plt.title('Input')
        plt.plot(t, inj.vector * 1e9, label='injected (nA)')
        #plt.plot(t, gK.vector * 1e6, label='K')
        #plt.plot(t, gNa.vector * 1e6, label='Na')
        plt.legend()
        plt.figure()
        test_channel_gates()
        plt.show()
        plt.close()
Example #6
0
def makeCellProto( name ):
    elec = moose.Neuron( '/library/' + name )
    ecompt = []
    soma = rd.buildCompt( elec, 'soma', somaDia, somaDia, -somaDia, RM, RA, CM )
    dend = rd.buildCompt( elec, 'dend', dendLen, dendDia, 0, RM, RA, CM )
    moose.connect( soma, 'axial', dend, 'raxial' )
    elec.buildSegmentTree()
Example #7
0
def create_cell():
    """Create a single-compartment Hodgking-Huxley neuron with a
    synaptic channel. 

    This uses the :func:`ionchannel.create_1comp_neuron` function for
    model creation.

    Returns a dict containing the neuron, the synchan and the
    synhandler for accessing the synapse,
    """
    neuron = create_1comp_neuron('/neuron')
    #: SynChan for post synaptic neuron
    synchan = moose.SynChan('/neuron/synchan')
    synchan.Gbar = 1e-8
    synchan.tau1 = 2e-3
    synchan.tau2 = 2e-3
    msg = moose.connect(neuron, 'channel', synchan, 'channel')
    #: Create SynHandler to handle spike event input and set the
    #: activation input of synchan
    synhandler = moose.SimpleSynHandler('/neuron/synhandler')
    synhandler.synapse.num = 1
    synhandler.synapse[0].delay = 5e-3
    moose.connect(synhandler, 'activationOut', synchan, 'activation')
    return {'neuron': neuron,
            'synchan': synchan,
            'synhandler': synhandler}
Example #8
0
def create_hhcomp(parent='/library', name='hhcomp', diameter=-30e-6, length=0.0):
    """Create a compartment with Hodgkin-Huxley type ion channels (Na and
    K).

    Returns a 3-tuple: (compartment, nachannel, kchannel)

    """
    comp, sarea = create_passive_comp(parent, name, diameter, length)
    if moose.exists('/library/na'):
        moose.copy('/library/na', comp.path, 'na')
    else:
        create_na_chan(parent=comp.path)
    na = moose.element('%s/na' % (comp.path))
    # Na-conductance 120 mS/cm^2
    na.Gbar = 120e-3 * sarea * 1e4 
    na.Ek = 115e-3 + EREST_ACT
    moose.connect(comp, 'channel', na, 'channel')
    if moose.exists('/library/k'):
        moose.copy('/library/k', comp.path, 'k')
    else:
        create_k_chan(parent=comp.path)
    k = moose.element('%s/k' % (comp.path))
    # K-conductance 36 mS/cm^2
    k.Gbar = 36e-3 * sarea * 1e4 
    k.Ek = -12e-3 + EREST_ACT
    moose.connect(comp, 'channel', k, 'channel')
    return comp, na, k
Example #9
0
def main( runTime ):
    try:
        moose.delete('/acc92')
        print("Deleted old model")
    except Exception as  e:
        print("Could not clean. model not loaded yet")

    moose.loadModel('acc92_caBuff.g',loadpath,'gsl')  
    ca = moose.element(loadpath+'/kinetics/Ca')
    pr = moose.element(loadpath+'/kinetics/protein')
    clockdt = moose.Clock('/clock').dts 
    moose.setClock(8, 0.1)#simdt
    moose.setClock(18, 0.1)#plotdt
    print clockdt
    print " \t \t simdt ", moose.Clock('/clock').dts[8],"plotdt ",moose.Clock('/clock').dts[18]
    ori =  ca.concInit
    tablepath = loadpath+'/kinetics/Ca'
    tableele = moose.element(tablepath)
    table = moose.Table2(tablepath+'.con')
    x = moose.connect(table, 'requestOut', tablepath, 'getConc')
    tablepath1 = loadpath+'/kinetics/protein'
    tableele1 = moose.element(tablepath1)
    table1 = moose.Table2(tablepath1+'.con')
    x1 = moose.connect(table1, 'requestOut', tablepath1, 'getConc')

    ca.concInit = ori
    print("[INFO] Running for 4000 with Ca.conc %s " % ca.conc)
    moose.start(4000)

    ca.concInit = 5e-03
    print("[INFO] Running for 20 with Ca.conc %s " % ca.conc)
    moose.start(20)

    ca.concInit = ori
    moose.start( runTime ) #here give the interval time 

    ca.concInit = 5e-03
    print("[INFO] Running for 20 with Ca.conc %s " % ca.conc)
    moose.start(20)

    ca.concInit = ori
    print("[INFO] Running for 2000 with Ca.conc %s " % ca.conc)
    moose.start(2000)

    pylab.figure()
    pylab.subplot(2, 1, 1)
    t = numpy.linspace(0.0, moose.element("/clock").runTime, len(table.vector)) # sec
    pylab.plot( t, table.vector, label="Ca Conc (interval- 8000s)" )
    pylab.legend()
    pylab.subplot(2, 1, 2)
    t1 = numpy.linspace(0.0, moose.element("/clock").runTime, len(table1.vector)) # sec
    pylab.plot( t1, table1.vector, label="Protein Conc (interval- 8000s)" )
    pylab.legend()
    pylab.savefig( os.path.join( dataDir, '%s_%s.png' % (table1.name, runTime) ) )

    print('[INFO] Saving data to csv files in %s' % dataDir)
    tabPath1 = os.path.join( dataDir, '%s_%s.csv' % (table.name, runTime))
    numpy.savetxt(tabPath1, numpy.matrix([t, table.vector]).T, newline='\n')
    tabPath2 = os.path.join( dataDir, '%s_%s.csv' % (table1.name, runTime) )
    numpy.savetxt(tabPath2, numpy.matrix([t1, table1.vector]).T, newline='\n')
Example #10
0
def make_NMDA():
	if moose.exists( 'NMDA' ):
		return
	NMDA = moose.SynChan( 'NMDA' )
	NMDA.Ek = 0.0
	NMDA.tau1 = 20.0e-3
	NMDA.tau2 = 20.0e-3
	NMDA.Gbar = 5 * SOMA_A

	block = moose.MgBlock( '/library/NMDA/block' )
	block.CMg = 1.2		#	[Mg] in mM
	block.Zk = 2
	block.KMg_A = 1.0/0.28
	block.KMg_B = 1.0/62

	moose.connect( NMDA, 'channelOut', block, 'origChannel', 'OneToOne' )
	addmsg1 = moose.Mstring( '/library/NMDA/addmsg1' )
	addmsg1.value = '.. channel	./block	channel'
	#Here we want to also tell the cell reader to _remove_ the original
	#Gk, Ek term going from the channel to the compartment, as this is
	# now handled by the MgBlock.
	#addmsg2 = moose.Mstring( 'NMDA/addmsg2'
	#addmsg2.value = 'DropMsg	..	channel'
	addmsg3 = moose.Mstring( '/library/NMDA/addmsg3' )
	addmsg3.value = '.. VmOut	.	Vm'
Example #11
0
def singleCompt( name, params ):
    mod = moose.copy( '/library/' + name + '/' + name, '/model' )
    A = moose.element( mod.path + '/A' )
    Z = moose.element( mod.path + '/Z' )
    Z.nInit = 1
    Ca = moose.element( mod.path + '/Ca' )
    CaStim = moose.element( Ca.path + '/CaStim' )
    runtime = params['preStimTime'] + params['stimWidth'] + params['postStimTime'] 
    steptime = 100

    CaStim.expr += ' + x2 * (t > ' + str( runtime ) + ' ) * ( t < ' + str( runtime + steptime ) +  ' )'
    print(CaStim.expr)
    tab = moose.Table2( '/model/' + name + '/Atab' )
    #for i in range( 10, 19 ):
        #moose.setClock( i, 0.01 )
    ampl = moose.element( mod.path + '/ampl' )
    phase = moose.element( mod.path + '/phase' )
    moose.connect( tab, 'requestOut', A, 'getN' )
    ampl.nInit = params['stimAmplitude'] * 1
    phase.nInit = params['preStimTime']

    ksolve = moose.Ksolve( mod.path + '/ksolve' )
    stoich = moose.Stoich( mod.path + '/stoich' )
    stoich.compartment = mod
    stoich.ksolve = ksolve
    stoich.path = mod.path + '/##'
    runtime += 2 * steptime

    moose.reinit()
    moose.start( runtime )
    t = np.arange( 0, runtime + 1e-9, tab.dt )
    return name, t, tab.vector
Example #12
0
def loadModel(filename, chanProto, chanDistrib, passiveDistrib):
    """Load the model and insert channels """
    global modelName
    global nchans, ncompts

    # Load in the swc file.
    modelName = "elec"
    cellProto = [ ( filename, modelName ) ]
    rdes = rd.rdesigneur( cellProto = cellProto
            , combineSegments = True
            , passiveDistrib = passiveDistrib
            , chanProto = chanProto
            , chanDistrib = chanDistrib
            )

    rdes.buildModel('/model')

    compts = moose.wildcardFind( "/model/%s/#[ISA=CompartmentBase]"%modelName )
    setupStimuls( compts[0] )

    for compt in compts:
        vtab = moose.Table( '%s/vm' % compt.path )
        moose.connect( vtab, 'requestOut', compt, 'getVm' )
        _records[compt.path] = vtab

    nchans  = len(set([x.path for x in
        moose.wildcardFind('/model/elec/##[TYPE=ZombieHHChannel]')])
        )
    _logger.info("Total channels: %s" % nchans)
    return _records
Example #13
0
def setup_model(model_path, synapse_locations, passive=False, solver='hsolve'):
    """Set up a single cell model under `model_path` with synapses
    created in the compartments listed in `synapse_locations`.


    `model_path` - location where the model should be created.

    `synapse_locations`: compartment names for the synapses.

    """
    cell = moose.copy(make_prototype(passive), model_path)
    if solver.lower() == 'hsolve':
        hsolve = moose.HSolve( '%s/solve' % (cell.path))
        hsolve.dt = simdt
        hsolve.target = cell.path
    syninfo_list = []
    for compname in synapse_locations:
        comppath = '%s/%s' % (cell.path, compname)
        print('1111 Creating synapse in', comppath)
        compartment = moose.element(comppath)
        syninfo = make_synapse(compartment)
        syninfo_list.append(syninfo)
        # connect  pulse stimulus
        stim_path = '%s/%s/stim' % (cell.path, compname)
        print('2222 Creating stimuls in', stim_path)
        stim = moose.PulseGen(stim_path)
        moose.connect(stim, 'output', syninfo['spike'], 'Vm')
        syninfo['stimulus'] = stim
    return {'neuron': cell,
            'syninfo': syninfo_list}
Example #14
0
def create_squid(parent):
    """Create a single compartment squid model."""
    soma = moose.SymCompartment(parent.path + '/soma')
    Em = EREST_ACT + 10.613e-3
    soma.Em = Em
    soma.initVm = EREST_ACT
    soma.Cm = 7.85e-9 * 0.5
    soma.Rm = 4.2e5 * 5.0
    soma.Ra = 7639.44e3

    nachan = moose.HHChannel(parent.path + '/soma/Na')
    nachan.Xpower = 3
    xGate = moose.HHGate(nachan.path + '/gateX')
    xGate.setupAlpha(Na_m_params + [VDIVS, VMIN, VMAX])
    # This is important: one can run without it but the output will diverge.
    xGate.useInterpolation = 1
    nachan.Ypower = 1
    yGate = moose.HHGate(nachan.path + '/gateY')
    yGate.setupAlpha(Na_h_params + [VDIVS, VMIN, VMAX])
    yGate.useInterpolation = 1
    nachan.Gbar = 0.942e-3
    nachan.Ek = 115e-3 + EREST_ACT
    moose.connect(nachan, 'channel', soma, 'channel', 'OneToOne')
    kchan = moose.HHChannel(parent.path + '/soma/K')
    kchan.Xpower = 4.0
    xGate = moose.HHGate(kchan.path + '/gateX')
    xGate.setupAlpha(K_n_params + [VDIVS, VMIN, VMAX])
    xGate.useInterpolation = 1
    kchan.Gbar = 0.2836e-3
    kchan.Ek = -12e-3 + EREST_ACT
    moose.connect(kchan, 'channel', soma, 'channel', 'OneToOne')
    return soma
def main():
    """ This example illustrates loading, running of an SBML model defined in XML format.\n
	The model 00001-sbml-l3v1.xml is taken from l3v1 SBML testcase.\n
	Plots are setup.\n
	Model is run for 20sec.\n
	As a general rule we created model under '/path/model' and plots under '/path/graphs'.\n
    """

    mfile =  os.path.join( script_dir, 'chem_models/00001-sbml-l3v1.xml')
    runtime = 20.0
        
    # Loading the sbml file into MOOSE, models are loaded in path/model
    sbmlId = moose.readSBML(mfile,'sbml')
    

    s1 = moose.element('/sbml/model/compartment/S1')
    s2= moose.element('/sbml/model/compartment/S2')
                      
    # Creating MOOSE Table, Table2 is for the chemical model
    graphs = moose.Neutral( '/sbml/graphs' )
    outputs1 = moose.Table2 ( '/sbml/graphs/concS1')
    outputs2 = moose.Table2 ( '/sbml/graphs/concS2')

    # connect up the tables
    moose.connect( outputs1,'requestOut', s1, 'getConc' );
    moose.connect( outputs2,'requestOut', s2, 'getConc' );

        
    # Reset and Run
    moose.reinit()
    moose.start(runtime)
Example #16
0
def main():
    makeModel()
    solver = moose.GslStoich("/model/compartment/solver")
    solver.path = "/model/compartment/##"
    solver.method = "rk5"
    mesh = moose.element("/model/compartment/mesh")
    moose.connect(mesh, "remesh", solver, "remesh")
    moose.setClock(5, 1.0)  # clock for the solver
    moose.useClock(5, "/model/compartment/solver", "process")

    moose.reinit()
    moose.start(100.0)  # Run the model for 100 seconds.

    a = moose.element("/model/compartment/a")
    b = moose.element("/model/compartment/b")

    # move most molecules over to b
    b.conc = b.conc + a.conc * 0.9
    a.conc = a.conc * 0.1
    moose.start(100.0)  # Run the model for 100 seconds.

    # move most molecules back to a
    a.conc = a.conc + b.conc * 0.99
    b.conc = b.conc * 0.01
    moose.start(100.0)  # Run the model for 100 seconds.

    # Iterate through all plots, dump their contents to data.plot.
    for x in moose.wildcardFind("/model/graphs/conc#"):
        moose.element(x[0]).xplot("scriptKineticSolver.plot", x[0].name)

    quit()
Example #17
0
def make_spiny_compt():
    comptLength = 100e-6
    comptDia = 4e-6
    numSpines = 5
    compt = create_squid()
    compt.inject = 1e-7
    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
        """
Example #18
0
def make_NMDA():
	if moose.exists( 'NMDA' ):
		return
	NMDA = moose.SynChan( 'NMDA' )
	NMDA.Ek = 0.0
	NMDA.tau1 = 20.0e-3
	NMDA.tau2 = 20.0e-3
	NMDA.Gbar = 5 * SOMA_A

	block = moose.MgBlock( '/library/NMDA/block' )
	block.CMg = 1.2		#	[Mg] in mM
	block.Zk = 2
	block.KMg_A = 1.0/0.28
	block.KMg_B = 1.0/62

	moose.connect( NMDA, 'channelOut', block, 'origChannel', 'OneToOne' )
	addmsg1 = moose.Mstring( '/library/NMDA/addmsg1' )
	addmsg1.value = '.. channel	./block	channel'
	#Here we want to also tell the cell reader to _remove_ the original
	#Gk, Ek term going from the channel to the compartment, as this is
	# now handled by the MgBlock.
	#addmsg2 = moose.Mstring( 'NMDA/addmsg2'
	#addmsg2.value = 'DropMsg	..	channel'
	addmsg1 = moose.Mstring( '/library/NMDA/addmsg1' )
	addmsg1.value = '.. VmOut	./block	Vm'
	addmsg2 = moose.Mstring( '/library/NMDA/addmsg2' )
	addmsg2.value = './block	IkOut ../Ca_conc current'
	addmsg3 = moose.Mstring( '/library/NMDA/addmsg3' )
	addmsg3.value = '.. VmOut	.	Vm'

	sh = moose.SimpleSynHandler( 'NMDA/sh' )
	moose.connect( sh, 'activationOut', NMDA, 'activation' )
	sh.numSynapses = 1
	sh.synapse[0].weight = 1
    def connectSynapse(self, spikegen, synapse):
        ''' Add synapse. '''

        assert isinstance(synapse, moose.SynChan), type(synapse)

        #utils.dump("INFO"
        #        , "Connecting ({})\n\t`{}`\n\t`{}`".format(
        #                "Sparse"
        #                , spikegen.path
        #                , synapse.vec.path
        #                )
        #        , frame = inspect.currentframe()
        #        )

        # Following 6 lines are from snippet Izhikevich_with_synapse.py file. I
        # am not sure whether this is the right way to make a synpase. However,
        # let's try this till we get a non-zero result after simulation.
        spikeStim = moose.PulseGen('%s/spike_stim' % (synapse.parent.path))
        spikeStim.delay[0] = 50.0
        spikeStim.level[0] = 1.0
        spikeStim.width[0] = 100.0
        moose.connect(spikeStim, 'output', spikegen, 'Vm')
        m = moose.connect(spikegen, "spikeOut"
                , synapse.synapse.vec, "addSpike"
                , "Sparse"
                )
        m.setRandomConnectivity(1.0, 1)
        return m
def make_synapses(spikegen, synchan, delay=5e-3):
    """
    Create synapses from spikegens to synchans in a manner similar to
    OneToAll connection.

spikegen:   list of spikegen objects
            These are sources of synaptic event messages.

synchan:    list of synchan objects
            These are the targets of the synaptic event messages.

delay:      mean delay of synaptic transmission.
            Individual delays are normally distributed with sd=0.1*mean.

    """
    scount = len(spikegen)
    for ii, sid in enumerate(synchan):
        s = moose.SynChan(sid)
        sh = moose.SimpleSynHandler( sid.path + "/synh" )
        moose.connect( sh, "activationOut", s, "activation" )
        sh.synapse.num = scount
        delay_list = np.random.normal(delay, delay*0.1, scount)
        # print delay_list
        for jj in range(scount):
            sh.synapse[jj].delay = delay_list[jj]
            # Connect all spikegens to this synchan except that from
            # same compartment - we assume if parents are same the two belong to the same compartment
            if s.parent.path != spikegen[jj].parent.path:
                m = moose.connect(spikegen[jj], 'spikeOut', moose.element(sh.path + '/synapse'),  'addSpike')
def two_populations(size=2):
    """An example with two population connected via synapses."""
    net = moose.Neutral('network2')
    pop_a = create_population(moose.Neutral('/network2/pop_A'), size)
    pop_b = create_population(moose.Neutral('/network2/pop_B'), size)
    make_synapses(pop_a['spikegen'], pop_b['synchan'])
    make_synapses(pop_b['spikegen'], pop_a['synchan'])
    pulse = moose.PulseGen('/network2/net2_pulse')
    pulse.firstLevel = 1e-9
    pulse.firstDelay = 0.05 # disable the pulsegen
    pulse.firstWidth = 0.02
    moose.connect(pulse, 'output', pop_a['compartment'][0], 'injectMsg')
    data = moose.Neutral('/data')
    vm_a = [moose.Table('/data/net2_Vm_A_%d' % (ii)) for ii in range(size)]
    for tab, comp in zip(vm_a, pop_a['compartment']):
        moose.connect(tab, 'requestOut', comp, 'getVm')
    vm_b = [moose.Table('/data/net2_Vm_B_%d' % (ii)) for ii in range(size)]
    for tab, comp in zip(vm_b, pop_b['compartment']):
        moose.connect(tab, 'requestOut', comp, 'getVm')
    gksyn_a = [moose.Table('/data/net2_Gk_syn_a_%d' % (ii)) for ii in range(size)]
    for tab, synchan in zip(gksyn_a, pop_a['synchan']):
        moose.connect(tab, 'requestOut', synchan, 'getGk')
    gksyn_b = [moose.Table('/data/net2_Gk_syn_b_%d' % (ii)) for ii in range(size)]
    for tab, synchan in zip(gksyn_b, pop_b['synchan']):
        moose.connect(tab, 'requestOut', synchan, 'getGk')
    pulsetable = moose.Table('/data/net2_pulse')
    pulsetable.connect('requestOut', pulse, 'getOutputValue')
    return {'vm_a': vm_a,
            'vm_b': vm_b,
            'gksyn_a': gksyn_a,
            'gksyn_b': gksyn_b,
            'pulse': pulsetable,}
Example #22
0
def creaetHHComp(parent='/library', name='hhcomp', diameter=1e-6, length=1e-6):
    """Create a compartment with Hodgkin-Huxley type ion channels (Na and
    K).

    Returns a 3-tuple: (compartment, nachannel, kchannel)

    """
    compPath = '{}/{}'.format(parent, name)
    mc = MooseCompartment( compPath, length, diameter, {})
    c = mc.mc_
    sarea = mc.surfaceArea

    if moose.exists('/library/na'):
        moose.copy('/library/na', c.path, 'na')
    else:
        create_na_chan(parent = c.path)

    na = moose.element('%s/na' % (c.path))

    # Na-conductance 120 mS/cm^2
    na.Gbar = 120e-3 * sarea * 1e4
    na.Ek = 115e-3 + EREST_ACT

    moose.connect(c, 'channel', na, 'channel')
    if moose.exists('/library/k'):
        moose.copy('/library/k', c.path, 'k')
    else:
        create_k_chan(parent = c.path)

    k = moose.element('%s/k' % (c.path))
    # K-conductance 36 mS/cm^2
    k.Gbar = 36e-3 * sarea * 1e4
    k.Ek = -12e-3 + EREST_ACT
    moose.connect(c, 'channel', k, 'channel')
    return (c, na, k)
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
Example #24
0
 def _addSpine( self, parent, spineProto, pos, angle, x, y, z, size, k ):
     spine = moose.copy( spineProto, parent.parent, 'spine' + str(k) )
     kids = spine[0].children
     coords = []
     ppos = np.array( [parent.x0, parent.y0, parent.z0] )
     for i in kids:
         #print i.name, k
         j = i[0]
         j.name += str(k)
         #print 'j = ', j
         coords.append( [j.x0, j.y0, j.z0] )
         coords.append( [j.x, j.y, j.z] )
         self._scaleSpineCompt( j, size )
         moose.move( i, self.elecid )
     origin = coords[0]
     #print 'coords = ', coords
     # Offset it so shaft starts from surface of parent cylinder
     origin[0] -= parent.diameter / 2.0 
     coords = np.array( coords )
     coords -= origin # place spine shaft base at origin.
     rot = np.array( [x, [0,0,0], [0,0,0]] )
     coords = np.dot( coords, rot )
     moose.delete( spine )
     moose.connect( parent, "raxial", kids[0], "axial" )
     self._reorientSpine( kids, coords, ppos, pos, size, angle, x, y, z )
def create_squid():
    """Create a single compartment squid model."""
    parent = moose.Neutral ('/n' )
    compt = moose.Compartment( '/n/compt' )
    Em = EREST_ACT + 10.613e-3
    compt.Em = Em
    compt.initVm = EREST_ACT
    compt.Cm = 7.85e-9
    compt.Rm = 4.2e5
    compt.Ra = 7639.44e3
    nachan = moose.HHChannel( '/n/compt/Na' )
    nachan.Xpower = 3
    xGate = moose.HHGate(nachan.path + '/gateX')    
    xGate.setupAlpha(Na_m_params +
                      [VDIVS, VMIN, VMAX])
    nachan.Ypower = 1
    yGate = moose.HHGate(nachan.path + '/gateY')
    yGate.setupAlpha(Na_h_params + 
                      [VDIVS, VMIN, VMAX])
    nachan.Gbar = 0.942e-3
    nachan.Ek = 115e-3+EREST_ACT
    moose.connect(nachan, 'channel', compt, 'channel', 'OneToOne')

    kchan = moose.HHChannel( '/n/compt/K' )
    kchan.Xpower = 4.0
    xGate = moose.HHGate(kchan.path + '/gateX')    
    xGate.setupAlpha(K_n_params +
                      [VDIVS, VMIN, VMAX])
    kchan.Gbar = 0.2836e-3
    kchan.Ek = -12e-3+EREST_ACT
    moose.connect(kchan, 'channel', compt, 'channel', 'OneToOne')
    return compt
Example #26
0
def test_crossing_single():
    """This function creates an ematrix of two PulseGen elements and
    another ematrix of two Table elements.

    The two pulsegen elements have same amplitude but opposite phase.

    Table[0] is connected to PulseGen[1] and Table[1] to Pulsegen[0].

    In the plot you should see two square pulses of opposite phase.

    """
    size = 2
    pg = moose.PulseGen('pulsegen', size)
    for ix, ii in enumerate(pg.vec):
        pulse = moose.element(ii)
        pulse.delay[0] = 1.0
        pulse.width[0] = 2.0
        pulse.level[0] = (-1)**ix
    tab = moose.Table('table', size)
    moose.connect(tab.vec[0], 'requestOut', pg.vec[1], 'getOutputValue', 'Single')
    moose.connect(tab.vec[1], 'requestOut', pg.vec[0], 'getOutputValue', 'Single')
    print 'Neighbors:'
    for t in tab.vec:
        print t.path
        for n in moose.element(t).neighbors['requestOut']:
            print 'requestOut <-', n.path
    moose.setClock(0, 0.1)
    moose.useClock(0, '/##', 'process')
    moose.start(5)
    for ii in tab.vec:
        t = moose.Table(ii).vector
        print len(t)
        pylab.plot(t)
    pylab.show()
Example #27
0
def make_spiny_compt(root_path, number,synInput):
    comptLength = 100e-6
    comptDia = 4e-6
    numSpines = Number_Of_Spines
    cell = moose.Neutral (root_path+"/cell"+str(number))
    
    compt = create_squid(cell)
    compt.inject = INJECT_CURRENT
    compt.x0 = 0
    compt.y0 = 0
    compt.z0 = 0
    compt.x = comptLength
    compt.y = 0
    compt.z = 0
    compt.length = comptLength
    compt.diameter = comptDia
    
    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
        """
Example #28
0
def main():
    ######## Put your favourite cell model here ######
    ##This one is from PMID 22730554: Suo et al J. Mol Cell Biol 2012
    filename = 'cells/ko20x-07.CNG.swc'
    moose.Neutral( '/library' )
    rdes = rd.rdesigneur( \
            cellProto = [[ filename, 'elec' ] ],\
            passiveDistrib = passiveDistrib_,
            chanProto = chanProto_,
            chanDistrib = chanDistrib_
        )
    rdes.buildModel( '/model' )
    moose.reinit()

    ################## Now we store plots ########################
    somaVm = moose.Table( '/somaVm' )
    moose.connect( somaVm, 'requestOut', rdes.soma, 'getVm' )
    ################## Now we set up the display ########################
    compts = moose.wildcardFind( "/model/elec/#[ISA=CompartmentBase]" )
    compts[0].inject = inject

    print("Setting Up 3D Display")
    app = QtGui.QApplication(sys.argv)
    vm_viewer = create_vm_viewer(rdes, somaVm)
    vm_viewer.show()
    vm_viewer.start()
    return app.exec_()
Example #29
0
def create_population(container, size):
    """Create a population of `size` single compartmental neurons with Na+
    and K+ channels. Also create SpikeGen objects and SynChan objects
    connected to these which can act as plug points for setting up
    synapses later.

    This uses ..ref::`ionchannel.create_1comp_neuron`.

    """
    path = container.path
    print path, size, type(path)
    comps = create_1comp_neuron("{}/neuron".format(path), number=size)
    synpath = path + "/synchan"
    print synpath, size, type(size)
    synchan = moose.vec(synpath, n=size, dtype="SynChan")
    synchan.Gbar = 1e-8
    synchan.tau1 = 2e-3
    synchan.tau2 = 2e-3
    m = moose.connect(comps, "channel", synchan, "channel", "OneToOne")
    synhandler = moose.vec("{}/synhandler".format(path), n=size, dtype="SimpleSynHandler")
    moose.connect(synhandler, "activationOut", synchan, "activation", "OneToOne")
    spikegen = moose.vec("{}/spikegen".format(path), n=size, dtype="SpikeGen")
    spikegen.threshold = 0.0
    m = moose.connect(comps, "VmOut", spikegen, "Vm", "OneToOne")
    return {"compartment": comps, "spikegen": spikegen, "synchan": synchan, "synhandler": synhandler}
Example #30
0
def createSquid():
    """Create a single compartment squid model."""
    parent = moose.Neutral ('/n' )
    elec = moose.Neutral ('/n/elec' )
    compt = moose.SymCompartment( '/n/elec/compt' )
    Em = EREST_ACT + 10.613e-3
    compt.Em = Em
    compt.initVm = EREST_ACT
    compt.Cm = 7.85e-9 * 0.5
    compt.Rm = 4.2e5 * 5.0
    compt.Ra = 7639.44e3
    compt.length = 100e-6
    compt.diameter = 4e-6
    nachan = moose.HHChannel( '/n/elec/compt/Na' )
    nachan.Xpower = 3
    xGate = moose.HHGate(nachan.path + '/gateX')
    xGate.setupAlpha(Na_m_params + [VDIVS, VMIN, VMAX])
    xGate.useInterpolation = 1
    nachan.Ypower = 1
    yGate = moose.HHGate(nachan.path + '/gateY')
    yGate.setupAlpha(Na_h_params + [VDIVS, VMIN, VMAX])
    yGate.useInterpolation = 1
    nachan.Gbar = 0.942e-3
    nachan.Ek = 115e-3+EREST_ACT
    moose.connect(nachan, 'channel', compt, 'channel', 'OneToOne')

    kchan = moose.HHChannel( '/n/elec/compt/K' )
    kchan.Xpower = 4.0
    xGate = moose.HHGate(kchan.path + '/gateX')
    xGate.setupAlpha(K_n_params + [VDIVS, VMIN, VMAX])
    xGate.useInterpolation = 1
    kchan.Gbar = 0.2836e-3
    kchan.Ek = -12e-3+EREST_ACT
    moose.connect(kchan, 'channel', compt, 'channel', 'OneToOne')
    return compt
Example #31
0
    gktab = moose.Table('/data/CaT_Gk')
    iktab = moose.Table('/data/CaT_Ik')

    dend.Cm = Cm
    dend.Rm = Rm
    dend.Em = Em
    dend.initVm = Vm_0
    dend.diameter = dend_diameter
    dend.length = dend_length

    pulse.delay[0] = 8.
    pulse.width[0] = 500e-3
    pulse.level[0] = inject
    pulse.delay[1] = 1e9

    m = moose.connect(pulse, 'output', dend, 'injectMsg')

    moose.connect(vmtab, 'requestOut', dend, 'getVm')

    chan_proto.chanlib()
    chan = addOneChan('CaT', gbar, dend)

    moose.connect(gktab, 'requestOut', chan, 'getGk')
    moose.connect(iktab, 'requestOut', chan, 'getIk')
    diftab = []
    buftab = []
    difs, difb = add_difshells_and_buffers(dend)
    if pumps:
        pump = moose.MMPump('/model/dend/pump')
        pump.Vmax = kcat
        pump.Kd = km
Example #32
0
def addPlot(objpath, field, plot):
    assert moose.exists(objpath)
    tab = moose.Table('/graphs/' + plot)
    obj = moose.element(objpath)
    moose.connect(tab, 'requestOut', obj, field)
    return tab
def makeTab(plotname, molpath):
    tab = moose.Table2('/model/graphs/' + plotname)  # Make output table
    # connect up the tables
    moose.connect(tab, 'requestOut', moose.element(molpath), 'getConc')
def makeChemModel(compt):
    """
    This function sets up a simple oscillatory chemical system within
    the script. The reaction system is::

        s ---a---> a  // s goes to a, catalyzed by a.
        s ---a---> b  // s goes to b, catalyzed by a.
        a ---b---> s  // a goes to s, catalyzed by b.
        b -------> s  // b is degraded irreversibly to s.

    in sum, **a** has a positive feedback onto itself and also forms **b**.
    **b** has a negative feedback onto **a**.
    Finally, the diffusion constant for **a** is 1/10 that of **b**.
    """
    # create container for model
    diffConst = 10e-12  # m^2/sec
    motorRate = 1e-6  # m/sec
    concA = 1  # millimolar

    # create molecules and reactions
    a = moose.Pool(compt.path + '/a')
    b = moose.Pool(compt.path + '/b')
    s = moose.Pool(compt.path + '/s')
    e1 = moose.MMenz(compt.path + '/e1')
    e2 = moose.MMenz(compt.path + '/e2')
    e3 = moose.MMenz(compt.path + '/e3')
    r1 = moose.Reac(compt.path + '/r1')

    a.concInit = 0.1
    b.concInit = 0.1
    s.concInit = 1

    moose.connect(e1, 'sub', s, 'reac')
    moose.connect(e1, 'prd', a, 'reac')
    moose.connect(a, 'nOut', e1, 'enzDest')
    e1.Km = 1
    e1.kcat = 1

    moose.connect(e2, 'sub', s, 'reac')
    moose.connect(e2, 'prd', b, 'reac')
    moose.connect(a, 'nOut', e2, 'enzDest')
    e2.Km = 1
    e2.kcat = 0.5

    moose.connect(e3, 'sub', a, 'reac')
    moose.connect(e3, 'prd', s, 'reac')
    moose.connect(b, 'nOut', e3, 'enzDest')
    e3.Km = 0.1
    e3.kcat = 1

    moose.connect(r1, 'sub', b, 'reac')
    moose.connect(r1, 'prd', s, 'reac')
    r1.Kf = 0.3  # 1/sec
    r1.Kb = 0  # 1/sec

    # Assign parameters
    a.diffConst = diffConst / 10
    b.diffConst = diffConst
    s.diffConst = 0
Example #35
0
def create_table(tablename, tablecomp, compproperty):
    tab = moose.Table(tablename)
    moose.connect(tab, "requestOut", tablecomp, compproperty)
    return tab
Example #36
0
def makeModel():
    model = moose.Neutral('/model')
    # Make neuronal model. It has no channels, just for geometry
    cell = moose.loadModel('./spinyNeuron.p', '/model/cell', 'Neutral')
    # We don't want the cell to do any calculations. Disable everything.
    for i in moose.wildcardFind('/model/cell/##'):
        i.tick = -1

    # create container for model
    model = moose.element('/model')
    chem = moose.Neutral('/model/chem')
    # The naming of the compartments is dicated by the places that the
    # chem model expects to be loaded.
    compt0 = moose.NeuroMesh('/model/chem/compt0')
    compt0.separateSpines = 1
    compt0.geometryPolicy = 'cylinder'
    compt1 = moose.SpineMesh('/model/chem/compt1')
    moose.connect(compt0, 'spineListOut', compt1, 'spineList', 'OneToOne')
    compt2 = moose.PsdMesh('/model/chem/compt2')
    moose.connect(compt0, 'psdListOut', compt2, 'psdList', 'OneToOne')

    #reacSystem = moose.loadModel( 'simpleOsc.g', '/model/chem', 'ee' )
    makeChemModel(compt0, True)  # Populate all 3 compts with the chem system.
    makeChemModel(compt1, False)
    makeChemModel(compt2, True)

    compt0.diffLength = 2e-6  # This will be over 100 compartments.
    # This is the magic command that configures the diffusion compartments.
    compt0.cell = cell
    moose.showfields(compt0)

    # Build the solvers. No need for diffusion in this version.
    ksolve0 = moose.Ksolve('/model/chem/compt0/ksolve')
    if useGssa:
        ksolve1 = moose.Gsolve('/model/chem/compt1/ksolve')
        ksolve2 = moose.Gsolve('/model/chem/compt2/ksolve')
    else:
        ksolve1 = moose.Ksolve('/model/chem/compt1/ksolve')
        ksolve2 = moose.Ksolve('/model/chem/compt2/ksolve')
    dsolve0 = moose.Dsolve('/model/chem/compt0/dsolve')
    dsolve1 = moose.Dsolve('/model/chem/compt1/dsolve')
    dsolve2 = moose.Dsolve('/model/chem/compt2/dsolve')
    stoich0 = moose.Stoich('/model/chem/compt0/stoich')
    stoich1 = moose.Stoich('/model/chem/compt1/stoich')
    stoich2 = moose.Stoich('/model/chem/compt2/stoich')

    # Configure solvers
    stoich0.compartment = compt0
    stoich1.compartment = compt1
    stoich2.compartment = compt2
    stoich0.ksolve = ksolve0
    stoich1.ksolve = ksolve1
    stoich2.ksolve = ksolve2
    stoich0.dsolve = dsolve0
    stoich1.dsolve = dsolve1
    stoich2.dsolve = dsolve2
    stoich0.path = '/model/chem/compt0/#'
    stoich1.path = '/model/chem/compt1/#'
    stoich2.path = '/model/chem/compt2/#'
    assert (stoich0.numVarPools == 1)
    assert (stoich0.numProxyPools == 0)
    assert (stoich0.numRates == 1)
    assert (stoich1.numVarPools == 1)
    assert (stoich1.numProxyPools == 0)
    if useGssa:
        assert (stoich1.numRates == 2)
        assert (stoich2.numRates == 2)
    else:
        assert (stoich1.numRates == 1)
        assert (stoich2.numRates == 1)
    assert (stoich2.numVarPools == 1)
    assert (stoich2.numProxyPools == 0)
    dsolve0.buildNeuroMeshJunctions(dsolve1, dsolve2)
    stoich0.buildXreacs(stoich1)
    stoich1.buildXreacs(stoich2)
    stoich0.filterXreacs()
    stoich1.filterXreacs()
    stoich2.filterXreacs()

    Ca_input_dend = moose.vec('/model/chem/compt0/Ca_input')
    print len(Ca_input_dend)
    for i in range(60):
        Ca_input_dend[3 + i * 3].conc = 2.0

    Ca_input_PSD = moose.vec('/model/chem/compt2/Ca_input')
    print len(Ca_input_PSD)
    for i in range(5):
        Ca_input_PSD[2 + i * 2].conc = 1.0

    # Create the output tables
    num = compt0.numDiffCompts - 1
    graphs = moose.Neutral('/model/graphs')
    makeTab('Ca_soma', '/model/chem/compt0/Ca[0]')
    makeTab('Ca_d1', '/model/chem/compt0/Ca[1]')
    makeTab('Ca_d2', '/model/chem/compt0/Ca[2]')
    makeTab('Ca_d3', '/model/chem/compt0/Ca[3]')
    makeTab('Ca_s3', '/model/chem/compt1/Ca[3]')
    makeTab('Ca_s4', '/model/chem/compt1/Ca[4]')
    makeTab('Ca_s5', '/model/chem/compt1/Ca[5]')
    makeTab('Ca_p3', '/model/chem/compt2/Ca[3]')
    makeTab('Ca_p4', '/model/chem/compt2/Ca[4]')
    makeTab('Ca_p5', '/model/chem/compt2/Ca[5]')
Example #37
0
def add_difshells_and_buffers(comp):

    if difshell_no < 1:
        return [], []

    difshell = []
    shell_thickness = dend.diameter / difshell_no / 2.
    difbuffer = []
    for i in range(difshell_no):
        shell_radius = comp.diameter / 2 - i * shell_thickness
        dif = add_difshell(comp, i, shell_thickness, shell_radius)
        difshell.append(dif)

        if i > 0:
            moose.connect(difshell[i - 1], "outerDifSourceOut", difshell[i],
                          "fluxFromOut")
            moose.connect(difshell[i], "innerDifSourceOut", difshell[i - 1],
                          "fluxFromIn")

        if difbuff_no > 0:
            difbuffer.append([])
            for j in range(difbuff_no):
                buf = add_difbuffer_to_dishell(comp, i, j, shell_thickness,
                                               shell_radius)
                difbuffer[i].append(buf)
                moose.connect(difshell[i], "concentrationOut", buf,
                              "concentration")
                moose.connect(buf, "reactionOut", difshell[i], "reaction")
                if i > 0:
                    moose.connect(difbuffer[i - 1][j], "outerDifSourceOut",
                                  difbuffer[i][j], "fluxFromOut")
                    moose.connect(difbuffer[i][j], "innerDifSourceOut",
                                  difbuffer[i - 1][j], "fluxFromIn")

    return difshell, difbuffer
Example #38
0
def main(simtime):
    # Simulation information.
    simtime = simtime
    simdt = 0.25e-5
    plotdt = 0.25e-3

    # Cell Compartment infromation
    diameter = 30e-6
    length = 50e-6
    Em = EREST_ACT + 10.613e-3
    CM = 1e-6 * 1e4
    RM = 1 / (0.3E-3 * 1e4)

    # Channel information.
    sa, x_sa = compute_comp_area(diameter, length)
    na_g = 120E-3 * sa * 1E4
    na_ek = 115E-3 + EREST_ACT
    k_g = 36e-3 * sa * 1E4
    k_ek = -12E-3 + EREST_ACT

    # Stimulus information
    inj_delay = 20E-3
    inj_amp = 0.3E-9
    inj_width = 40E-3

    # Create cell
    soma = create_compartment('soma',
                              length,
                              diameter,
                              RM,
                              CM,
                              initVM=EREST_ACT,
                              ELEAK=Em)

    # Create channels
    K_chan = create_channel(chan_name='K',
                            vdivs=VDIVS,
                            vmin=VMIN,
                            vmax=VMAX,
                            x_params=K_n_params,
                            xpow=4)

    Na_chan = create_channel(chan_name='Na',
                             vdivs=VDIVS,
                             vmin=VMIN,
                             vmax=VMAX,
                             x_params=Na_m_params,
                             xpow=3,
                             y_params=Na_h_params,
                             ypow=1)

    # Set conductances
    nachan = moose.copy(Na_chan, soma.path, 'Na', 1)
    kchan = moose.copy(K_chan, soma.path, 'K', 1)
    nachan = set_channel_conductance(nachan, na_g, na_ek)
    kchan = set_channel_conductance(kchan, k_g, k_ek)

    # Add channels to soma
    moose.connect(nachan, 'channel', soma, 'channel', 'OneToOne')
    moose.connect(kchan, 'channel', soma, 'channel', 'OneToOne')

    # connect pulse gen
    pulse_inject = create_pulse_generator(soma,
                                          inj_width,
                                          inj_amp,
                                          delay=inj_delay)

    # Output table
    soma_v_table = create_output_table(table_element='/output',
                                       table_name='somaVm')
    soma_i_table = create_output_table(table_element='/output',
                                       table_name='somaIm')

    # Connect output tables
    moose.connect(soma_v_table, 'requestOut', soma, 'getVm')
    moose.connect(soma_i_table, 'requestOut', pulse_inject, 'getOutputValue')

    # Set moose simulation clocks
    for lable in range(7):
        moose.setClock(lable, simdt)
    moose.setClock(8, plotdt)

    # Run simulation
    moose.reinit()
    moose.start(simtime)

    # Plot output tables.
    v_plot = plot_vm_table(simtime,
                           soma_v_table,
                           soma_i_table,
                           title="soma voltage")
    plt.grid(True)
    plt.legend(['v', 'i'])
    plt.show()
Example #39
0
def main():
    '''
    On the command-line, in moose-examples/snippets directory, run ``python IntegrateFireZoo.py``.  
    The script will ask you which neuron you want to simulate and you can choose and run what you want.  
    Play with the parameters of the IF neurons in the source code.
    '''
    neuronChoices = {'LIF':moose.LIF, 'QIF':moose.QIF, 'ExIF':moose.ExIF, 'AdExIF':moose.AdExIF,
                    'AdThreshIF':moose.AdThreshIF, 'IzhIF':moose.IzhIF}
    #### CHOOSE ONE OF THE NEURON KEYS AS choiceKey FROM BELOW DICTIONARY ####
    #choiceKey = 'LIF'
    #### No need, am inputting it from the user on the terminal
    choiceKeys = list(neuronChoices.keys()) # keys() does not retain the order in dict defn above!
    choiceIndex = eval(str(input('Choose a number corresponding to your desired neuron: '+str([(i,key) for (i,key) in enumerate(choiceKeys)])+' -- ')))
    choiceKey = choiceKeys[choiceIndex]
    neuronChoice = neuronChoices[choiceKey]

    # ###########################################
    # Initialize neuron group
    # ###########################################

    # neuron instantiation
    network = neuronChoice( 'network' ); # choose neuron type above
    moose.le( '/network' )
    network.vec.Em = Vrest
    network.vec.thresh = Vt_base
    network.vec.refractoryPeriod = refrT
    network.vec.Rm = R
    network.vec.vReset = Vreset
    network.vec.Cm = tau/R
    network.vec.initVm = Vrest

    # neuron specific parameters and current injected I
    if choiceKey == 'LIF':
        network.vec.inject = 5e-10 # Amp    # injected current I
    if choiceKey == 'QIF':
        network.vec.a0 = a0
        network.vec.vCritical = vCritical
        network.vec.inject = 5e-10 # Amp    # injected current I
    elif choiceKey == 'ExIF':
        network.vec.deltaThresh = deltaThresh
        network.vec.vPeak = vPeak           # reset at vPeak, not at thresh
        network.vec.inject = 5e-9  # Amp    # injected current I
    elif choiceKey == 'AdExIF':
        network.vec.deltaThresh = deltaThresh
        network.vec.vPeak = vPeak           # reset at vPeak, not at thresh
        network.vec.a0 = a0AdEx
        network.vec.b0 = b0
        network.vec.tauW = tauW
        network.vec.inject = 5e-9  # Amp    # injected current I
    elif choiceKey == 'AdThreshIF':
        network.vec.a0 = a0AdTh
        network.vec.threshJump = threshJump
        network.vec.tauThresh = tauThresh
        network.vec.inject = 1e-9  # Amp    # injected current I
    elif choiceKey == 'IzhIF':
        network.vec.a = a
        network.vec.b = b
        network.vec.d = d
        network.vec.uInit = uRest           # Just sets the initial value of u
        network.vec.vPeak = vPeak           # reset at vPeak, not at thresh
        network.vec.inject = 5e-9  # Amp    # injected current I

    print(("Injecting current =",network.vec[0].inject,"in",choiceKey,"neuron."))

    # ###########################################
    # Setting up table
    # ###########################################

    Vm = moose.Table( '/plotVm' )
    moose.connect( network, 'VmOut', Vm, 'input', 'OneToOne')
    spikes = moose.Table( '/plotSpikes' )
    moose.connect( network, 'spikeOut', spikes, 'input', 'OneToOne')

    # ###########################################
    # Simulate the current injection
    # ###########################################

    dt = 5e-6 # s
    runtime = 0.02 # s

    # moose simulation
    moose.useClock( 1, '/network', 'process' )
    moose.useClock( 2, '/plotSpikes', 'process' )
    moose.useClock( 3, '/plotVm', 'process' )
    moose.setClock( 0, dt )
    moose.setClock( 1, dt )
    moose.setClock( 2, dt )
    moose.setClock( 3, dt )
    moose.setClock( 9, dt )
    moose.reinit()
    moose.start(runtime)

    # ###########################################
    # Plot the simulated Vm-s and STDP curve
    # ###########################################

    # Voltage plots
    Vmseries = Vm.vector
    numsteps = len(Vmseries)
    if choiceKey not in ['ExIF','AdExIF','IzhIF']:
        # insert spikes so that Vm reset at thresh doesn't look weird
        # for ExIF, etc. reset is at vPeak, so not weird.
        for t in spikes.vector:
            Vmseries[int(t/dt)-1] = 30e-3 # V
    timeseries = np.arange(0.,1000*numsteps*dt-1e-10,dt*1000)
    plt.figure(facecolor='w')
    plt.plot(timeseries,Vmseries*1000,color='r') # neuron's Vm
    plt.xlabel('time (ms)')
    plt.ylabel('Vm (mV)')
    plt.title(choiceKey+"neuron, current="+str(network.vec[0].inject)+"A")

    plt.show()
Example #40
0
def connect_CaConc(compartment_list, temperature=None):
    """ Connect the Ca pools and channels within each of the compartments in compartment_list
     Ca channels should have a child Mstring named 'ion' with value set in MOOSE.
     Ca dependent channels like KCa should have a child Mstring called 'ionDependency' with value set in MOOSE.
     Call this only after instantiating cell so that all channels and pools have been created. """
    for compartment in compartment_list:
        caconc = None
        for child in compartment.children:
            if child.className == "CaConc":
                caconc = moose.element(child)
                break
        if caconc is not None:
            child = get_child_Mstring(caconc, "phi")
            if child is not None:
                caconc.B = float(
                    child.value
                )  # B = phi by definition -- see neuroml 1.8.1 defn
            else:
                ## B has to be set for caconc based on thickness of Ca shell and compartment l and dia,
                ## OR based on the Mstring phi under CaConc path.
                ## I am using a translation from Neuron for mitral cell, hence this method.
                ## In Genesis, gmax / (surfacearea*thick) is set as value of B!
                caconc.B = (1 / (2 * FARADAY) /
                            (math.pi * compartment.diameter *
                             compartment.length * caconc.thick))
            for neutralwrap in compartment.children:
                if neutralwrap.className == "HHChannel":
                    channel = moose.HHChannel(child)
                    ## If child Mstring 'ion' is present and is Ca, connect channel current to caconc
                    for childid in channel.children:
                        # in async13, gates which have not been created still 'exist'
                        # i.e. show up as a child, but cannot be wrapped.
                        try:
                            child = moose.element(childid)
                            if child.className == "Mstring":
                                child = moose.Mstring(child)
                                assert child
                                if child.name == "ion":
                                    if child.value in ["Ca", "ca"]:
                                        moose.connect(channel, "IkOut", caconc,
                                                      "current")
                                        # print 'Connected IkOut of',channel.path,'to current of',caconc.path
                                ## temperature is used only by Nernst part here...
                                if child.name == "nernst_str":
                                    nernst = moose.Nernst(channel.path +
                                                          "/nernst")
                                    nernst_params = child.value.split(",")
                                    nernst.Cout = float(nernst_params[0])
                                    nernst.valence = int(nernst_params[1])
                                    nernst.Temperature = temperature
                                    moose.connect(nernst, "Eout", channel,
                                                  "setEk")
                                    moose.connect(caconc, "concOut", nernst,
                                                  "ci")
                                    # print 'Connected Nernst',nernst.path
                        except TypeError:
                            pass

                if neutralwrap.className == "HHChannel2D":
                    channel = moose.HHChannel2D(child)
                    ## If child Mstring 'ionDependency' is present, connect caconc Ca conc to channel
                    for childid in channel.children:
                        # in async13, gates which have not been created still 'exist'
                        # i.e. show up as a child, but cannot be wrapped.
                        try:
                            child = moose.element(childid)
                            if (child.className == "Mstring"
                                    and child.name == "ionDependency"):
                                child = moose.Mstring(child)
                                if child.value in ["Ca", "ca"]:
                                    moose.connect(caconc, "concOut", channel,
                                                  "concen")
                                    # print 'Connected concOut of',caconc.path,'to concen of',channel.path
                        except TypeError as e:
                            logger_.warning(e)
def creat_moose_tables():
    soma_v_table = create_output_table(table_element='/output',
                                       table_name='somaVm')
    soma_i_table = create_output_table(table_element='/output',
                                       table_name='somIm')
    soma_i_table1 = create_output_table(table_element='/output',
                                        table_name='somIm1')
    soma_i_table2 = create_output_table(table_element='/output',
                                        table_name='somIm2')
    soma_i_table3 = create_output_table(table_element='/output',
                                        table_name='somIm3')
    soma_i_table4 = create_output_table(table_element='/output',
                                        table_name='somIm4')

    moose.connect(soma_v_table, 'requestOut', moose.element('/soma'), 'getVm')
    moose.connect(soma_i_table, 'requestOut', moose.element('/soma/Ca_V2'),
                  'getIk')
    moose.connect(soma_i_table1, 'requestOut', moose.element('/soma/Ca_V1'),
                  'getIk')
    moose.connect(soma_i_table2, 'requestOut', moose.element('/soma/K'),
                  'getIk')
    moose.connect(soma_i_table3, 'requestOut', moose.element('/soma/ca_cc'),
                  'getIk')
    moose.connect(soma_i_table4, 'requestOut', moose.element('/soma/CaPool'),
                  'getCa')
    return {
        'vm': [soma_v_table],
        'internal_currents': [
            soma_i_table, soma_i_table1, soma_i_table2, soma_i_table3,
            soma_i_table4
        ]
    }
Example #42
0
def buildOnePlot( path, field = 'getConc' ):
    elist = moose.vec( '/model/chem/' + path )
    tabname = path.replace( '/', '_' )
    tab = moose.Table2( '/graphs/' + tabname, len( elist ) ).vec
    moose.connect( tab, 'requestOut', elist, field, 'OneToOne' )
Example #43
0
def makePlot(name, src, field, tick):
    tab = moose.Table('/graphs/' + name)
    moose.connect(tab, 'requestOut', src, 'get' + field)
    tab.tick = tick
    return tab
Example #44
0
def makeChemProto(name, Aexpr, Bexpr, params):
    sw = params['stimWidth']
    diffLength = params['diffusionLength']
    dca = params['diffConstA'] * diffLength * diffLength
    dcb = params['diffConstB'] * diffLength * diffLength

    # Objects
    chem = moose.Neutral('/library/' + name)
    compt = moose.CubeMesh('/library/' + name + '/' + name)
    A = moose.Pool(compt.path + '/A')
    B = moose.Pool(compt.path + '/B')
    Z = moose.BufPool(compt.path + '/Z')
    Ca = moose.BufPool(compt.path + '/Ca')
    phase = moose.BufPool(compt.path + '/phase')
    vel = moose.BufPool(compt.path + '/vel')
    ampl = moose.BufPool(compt.path + '/ampl')
    Adot = moose.Function(A.path + '/Adot')
    Bdot = moose.Function(B.path + '/Bdot')
    CaStim = moose.Function(Ca.path + '/CaStim')
    A.diffConst = dca
    B.diffConst = dcb

    # Equations

    Adot.expr = parseExpr(Aexpr, params, True)
    Bdot.expr = parseExpr(Bexpr, params, False)
    CaStim.expr = 'x2 * exp( -((x0 - t)^2)/(2* ' + str(sw * sw) + ') )'

    print(Adot.expr)
    print(Bdot.expr)
    print(CaStim.expr)

    # Connections
    Adot.x.num = 4
    moose.connect(Ca, 'nOut', Adot.x[0], 'input')
    moose.connect(A, 'nOut', Adot.x[1], 'input')
    moose.connect(B, 'nOut', Adot.x[2], 'input')
    moose.connect(Z, 'nOut', Adot.x[3], 'input')
    moose.connect(Adot, 'valueOut', A, 'increment')

    Bdot.x.num = 3
    if name == 'negFF':
        moose.connect(Ca, 'nOut', Bdot.x[0], 'input')
    else:
        moose.connect(A, 'nOut', Bdot.x[0], 'input')
    moose.connect(B, 'nOut', Bdot.x[1], 'input')
    moose.connect(Z, 'nOut', Bdot.x[2], 'input')
    moose.connect(Bdot, 'valueOut', B, 'increment')

    CaStim.x.num = 3
    moose.connect(phase, 'nOut', CaStim.x[0], 'input')
    moose.connect(vel, 'nOut', CaStim.x[1], 'input')
    moose.connect(ampl, 'nOut', CaStim.x[2], 'input')
    moose.connect(CaStim, 'valueOut', Ca, 'setN')

    return compt
Example #45
0
def enzymeMerge(comptD, comptS, key, poolListind):
    war_msg = ""
    RE_Duplicated, RE_Notcopiedyet, RE_Dangling = [], [], []
    comptDpath = moose.element(comptD[key]).path
    comptSpath = moose.element(comptS[key]).path
    objD = moose.element(comptDpath).parent.name
    objS = moose.element(comptSpath).parent.name
    #nzyListina => enzyListind

    enzyListind = moose.wildcardFind(comptDpath + '/##[ISA=EnzBase]')
    enzyListins = moose.wildcardFind(comptSpath + '/##[ISA=EnzBase]')
    for es in enzyListins:
        eSsubname, eSprdname = [], []
        eSsubname = subprdList(es, "sub")
        eSprdname = subprdList(es, "prd")
        allexists, allexistp = False, False
        allclean = False

        poolinDlist = poolListind[findCompartment(es).name]
        for pD in poolinDlist:
            if es.parent.name == pD.name:
                edpath = es.parent.path.replace(objS, objD)

                if not moose.exists(edpath + '/' + es.name):
                    #This will take care
                    #  -- If same enzparent name but different enzyme name
                    #  -- or different parent/enzyme name
                    if eSsubname and eSprdname:
                        allexists = checkexist(eSsubname, objS, objD)
                        allexistp = checkexist(eSprdname, objS, objD)
                        if allexists and allexistp:
                            enzPool = moose.element(pD.path)
                            edpath = es.parent.path.replace(objS, objD)
                            enz = moose.element(
                                moose.copy(es, moose.element(edpath)))
                            enzPool = enz.parent
                            if es.className in ["ZombieEnz", "Enz"]:
                                moose.connect(moose.element(enz), "enz",
                                              enzPool, "reac")
                            if es.className in ["ZombieMMenz", "MMenz"]:
                                moose.connect(enzPool, "nOut", enz, "enzDest")
                            connectObj(enz, eSsubname, "sub", comptD, war_msg)
                            connectObj(enz, eSprdname, "prd", comptD, war_msg)
                            allclean = True
                        else:
                            # didn't find sub or prd for this Enzyme
                            RE_Notcopiedyet.append(es)
                    else:
                        #   -- it is dagging reaction
                        RE_Dangling.append(es)
                else:
                    #Same Enzyme name
                    #   -- Same substrate and product including same volume then don't copy
                    #   -- different substrate/product or if sub/prd's volume is different then DUPLICATE the Enzyme
                    allclean = False
                    ed = moose.element(es.path.replace(objS, objD))
                    eDsubname = subprdList(ed, "sub")
                    eSsubname = subprdList(es, "sub")
                    hasSamenoofsublen, hasSameS, hasSamevols = same_len_name_vol(
                        eDsubname, eSsubname)

                    eDprdname = subprdList(ed, "prd")
                    eSprdname = subprdList(es, "prd")
                    hasSamenoofprdlen, hasSameP, hasSamevolp = same_len_name_vol(
                        eDprdname, eSprdname)
                    if not all((hasSamenoofsublen, hasSameS, hasSamevols,
                                hasSamenoofprdlen, hasSameP, hasSamevolp)):
                        # May be different substrate or product or volume of Sub/prd may be different,
                        # Duplicating the enzyme
                        if eSsubname and eSprdname:
                            allexists, allexistp = False, False
                            allexists = checkexist(eSsubname, objS, objD)
                            allexistp = checkexist(eSprdname, objS, objD)
                            if allexists and allexistp:
                                es.name = es.name + "_duplicated"
                                if es.className in ["ZombieEnz", "Enz"]:
                                    edpath = es.parent.path.replace(objS, objD)
                                    enz = moose.copy(es, moose.element(edpath))
                                    moose.connect(enz, 'enz', edpath, 'reac')

                                if es.className in ["ZombieMMenz", "MMenz"]:
                                    edpath = es.parent.path.replace(objS, objD)
                                    enz = moose.copy(es, moose.element(edpath))
                                    enzinfo = moose.Annotator(enz.path +
                                                              '/info')
                                    moose.connect(
                                        moose.element(enz).parent, "nOut",
                                        moose.element(enz), "enzDest")
                                    #moose.connect(moose.element(enz),"enz",moose.element(enz).parent,"reac")

                                connectObj(enz, eSsubname, "sub", comptD,
                                           war_msg)
                                connectObj(enz, eSprdname, "prd", comptD,
                                           war_msg)
                                RE_Duplicated.append(enz)
                                allclean = True
                            else:
                                allclean = False
                    else:
                        allclean = True

                    if not allclean:
                        # didn't find sub or prd for this enzyme
                        #   --  it may be connected Enzyme cplx
                        if eSsubname and eSprdname:
                            RE_Notcopiedyet.append(es)
                        else:
                            RE_Dangling.append(es)

    return RE_Duplicated, RE_Notcopiedyet, RE_Dangling
Example #46
0
def Vclam(delay, width, delay_2, r, c, gain, sat, gain_p, tau_1, tau_2, psat):
    pulseg = moose.PulseGen('pulse')
    pulseg.firstDelay = delay
    pulseg.firstWidth = width
    pulseg.secondDelay = delay_2
    lp = moose.RC('lowpass')
    lp.R = r
    lp.C = c
    DA = moose.DiffAmp('diffamp')
    DA.gain = gain
    DA.saturation = sat
    pid = moose.PIDController('PID')
    pid.gain = gain_p
    pid.tauI = tau_1
    pid.tauD = tau_2
    pid.saturation = psat
    comp = moose.element("/proto")
    moose.connect(pulseg, "output", lp, "injectIn")
    moose.connect(lp, "output", DA, "plusIn")
    moose.connect(DA, "output", pid, "commandIn")
    moose.connect(comp, "VmOut", pid, "sensedIn")
    moose.connect(pid, "output", comp, "injectMsg")
    tab = moose.Table("/data/Im")
    moose.connect(tab, "requestOut", comp, "getIm")
    return tab
Example #47
0
def main():
    # Simulation information.
    simtime = 0.1
    simdt = 0.25e-5
    plotdt = 0.25e-3

    # Cell Compartment infromation
    diameter = 30e-6
    length = 50e-6
    Em = EREST_ACT + 10.613e-3
    CM = 1e-6 * 1e4
    RM = 1 / (0.3E-3 * 1e4)
    RA = 4

    # Stimulus information
    inj_delay = 20E-3
    inj_amp = 1E-9
    inj_width = 40E-3

    # Create cell
    chicken_model = create_swc_model(
        root_name='E19',
        file_name='E19-cell_filling-caudal.CNG.swc',
        RM=RM,
        CM=CM,
        RA=RA,
        ELEAK=Em,
        initVM=Em)
    soma = moose.element('/E19[0]/soma')

    # Create channels
    channels_set = create_set_of_channels(channel_settings, VDIVS, VMIN, VMAX)

    # Fetch all compartment paths.
    moose_paths = []
    for comp in moose.wildcardFind(chicken_model.path +
                                   '/#[TYPE=Compartment]'):
        moose_paths.append(comp.path)

    # Copy all channels to compartments.
    for channel_name, channel_obj in channels_set.items():
        copy_connect_channel_moose_paths(channel_obj, channel_name,
                                         moose_paths)

    # connect pulse gen
    pulse_inject = create_pulse_generator(soma,
                                          inj_width,
                                          inj_amp,
                                          delay=inj_delay)

    # Output table
    soma_v_table = create_output_table(table_element='/output',
                                       table_name='somaVm')
    soma_i_table = create_output_table(table_element='/output',
                                       table_name='somaIm')
    chicken_dend_table = create_output_table(table_element='/output',
                                             table_name='chkdend')

    # Connect output tables
    moose.connect(soma_v_table, 'requestOut', soma, 'getVm')
    moose.connect(soma_i_table, 'requestOut', pulse_inject, 'getOutputValue')
    moose.connect(chicken_dend_table, 'requestOut',
                  moose.element('/E19[0]/dend_36_0'), 'getVm')

    # Set moose simulation clocks
    for lable in range(7):
        moose.setClock(lable, simdt)
    moose.setClock(8, plotdt)

    # Run simulation
    moose.reinit()
    moose.start(simtime)

    # Plot output tables.
    v_plot = plot_vm_table(simtime,
                           soma_v_table,
                           soma_i_table,
                           chicken_dend_table,
                           title="soma vs dend with K and Na gbars")
    v_plot.legend(['soma_V', 'i', 'dend_V'])
    plt.grid(True)
    plt.show()
Example #48
0
def makeReacs():
    # Parameters
    volume = 1e-15
    CaInitConc = 60e-6
    NA = 6.022e23
    tauI = 1
    tauG = 0.1

    model = moose.Neutral('/cells')
    compartment = moose.CubeMesh('/cells/compartment')
    compartment.volume = volume

    # Make pools
    Ca = moose.BufPool('/cells/compartment/Ca')
    tgtCa = moose.BufPool('/cells/compartment/tgtCa')
    m = moose.Pool('/cells/compartment/m')
    chan = moose.Pool('/cells/compartment/chan')

    # Make Funcs
    f1 = moose.Func('/cells/compartment/f1')
    f2 = moose.Func('/cells/compartment/f2')

    # connect up
    moose.connect(f1, 'valueOut', m, 'increment')
    moose.connect(f2, 'valueOut', chan, 'increment')

    moose.connect(Ca, 'nOut', f1, 'xIn')
    moose.connect(tgtCa, 'nOut', f1, 'yIn')

    moose.connect(m, 'nOut', f2, 'xIn')
    moose.connect(chan, 'nOut', f2, 'yIn')

    # Set params
    Ca.concInit = CaInitConc
    tgtCa.concInit = tgtCaInitConc
    m.concInit = 0.0
    chan.concInit = 0.0
    volscale = 1.0

    f1.expr = str(volscale / tauI) + " * (x-y)"
    f2.expr = str(volscale / tauG) + " * (x-y)"

    #Plotting
    channelPlot = makePlot('channelConc', chan, 'Conc', 18)
    mPlot = makePlot('mConc', m, 'Conc', 18)
    caPlot = makePlot('Ca', Ca, 'Conc', 18)
    targetPlot = makePlot('tgtCa', tgtCa, 'Conc', 18)
    return (channelPlot, mPlot, caPlot)
    def _setup_network(self):
        ## Set up the neurons without connections
        ExcInhNetBase._setup_network(self)

        ## Now, add in the connections...
        ## Each pre-synaptic spike cause Vm of post-neuron to rise by
        ##  synaptic weight in one time step i.e. delta-fn synapse.
        ## Since LIF neuron is derived from Compartment class,
        ## conductance-based synapses (SynChan class) can also be used.

        ## E to E synapses can be plastic
        ## Two ways to do this:
        ## 1) Each LIF neuron has one incoming postsynaptic SynHandler,
        ##  which collects the activation from all presynaptic neurons,
        ##  but then a common Ca pool is used.
        ## 2) Each LIF neuron has multiple postsyanptic SynHandlers,
        ##  one for each pre-synaptic neuron, i.e. one per synapse,
        ##  then each synapse has a different Ca pool.
        ## Here we go with option 2) as per Higgins et al 2014 (Brunel private email)
        ## separate SynHandler per EE synapse, thus NmaxExc*excC
        if CaPlasticity:
            self.synsEE = moose.GraupnerBrunel2012CaPlasticitySynHandler( \
                '/network/synsEE', self.NmaxExc*self.excC )
        else:
            self.synsEE = moose.SimpleSynHandler( \
                '/network/synsEE', self.NmaxExc*self.excC )
        moose.useClock(0, '/network/synsEE', 'process')

        ## I to E synapses are not plastic
        self.synsIE = moose.SimpleSynHandler('/network/synsIE', self.NmaxExc)
        ## all synapses to I neurons are not plastic
        self.synsI = moose.SimpleSynHandler('/network/synsI',
                                            self.N - self.NmaxExc)
        ## connect all SynHandlers to their respective neurons
        for i in range(self.NmaxExc):
            moose.connect( self.synsIE.vec[i], 'activationOut', \
                self.network.vec[i], 'activation' )
        for i in range(self.NmaxExc, self.N):
            moose.connect( self.synsI.vec[i-self.NmaxExc], 'activationOut', \
                self.network.vec[i], 'activation' )

        ## Connections from some Exc/Inh neurons to each Exc neuron
        for i in range(0, self.NmaxExc):
            self.synsIE.vec[i].numSynapses = self.incC - self.excC

            ## Connections from some Exc neurons to each Exc neuron
            ## draw excC number of neuron indices out of NmaxExc neurons
            preIdxs = random.sample(range(self.NmaxExc), self.excC)
            ## connect these presynaptically to i-th post-synaptic neuron
            for synnum, preIdx in enumerate(preIdxs):
                synidx = i * self.excC + synnum
                synHand = self.synsEE.vec[synidx]

                ## connect each synhandler to the post-synaptic neuron
                moose.connect( synHand, 'activationOut', \
                    self.network.vec[i], 'activation' )
                ## important to set numSynapses = 1 for each synHandler,
                ## doesn't create synapses if you set the full array of SynHandlers
                synHand.numSynapses = 1

                synij = synHand.synapse[0]
                connectExcId = moose.connect( self.network.vec[preIdx], \
                                'spikeOut', synij, 'addSpike')
                synij.delay = syndelay
                if CaPlasticity:
                    ## set parameters for the Ca Plasticity SynHandler
                    ## have to be set for each SynHandler
                    ## doesn't set for full array at a time
                    synHand.CaInit = 0.0
                    synHand.tauCa = tauCa
                    synHand.tauSyn = tauSyn
                    synHand.CaPre = CaPre
                    synHand.CaPost = CaPost
                    synHand.delayD = delayD
                    synHand.thetaD = thetaD
                    synHand.thetaP = thetaP
                    synHand.gammaD = gammaD
                    synHand.gammaP = gammaP
                    synHand.weightMax = 1.0  # bounds on the weight
                    synHand.weightMin = 0.0
                    synHand.weightScale = \
                                self.J*2.0    # 0.2 mV, weight*weightScale is activation
                    # typically weight <~ 0.5, so activation <~ J
                    synHand.noisy = noisy
                    synHand.noiseSD = noiseSD
                    synHand.bistable = bistable

                    moose.connect( self.network.vec[i], \
                        'spikeOut', synHand, 'addPostSpike')
                    synij.weight = eqWeight  # activation = weight*weightScale
                    # weightScale = 2*J
                    # weight <~ 0.5
                    ## Randomly set 5% of them to be 1.0
                    if np.random.uniform() < 0.05:
                        synij.weight = 1.0
                else:
                    synij.weight = self.J  # no weightScale here, activation = weight

            ## Connections from some Inh neurons to each Exc neuron
            ## draw inhC=incC-excC number of neuron indices out of inhibitory neurons
            preIdxs = random.sample(range(self.NmaxExc, self.N),
                                    self.incC - self.excC)
            ## connect these presynaptically to i-th post-synaptic neuron
            for synnum, preIdx in enumerate(preIdxs):
                synij = self.synsIE.vec[i].synapse[synnum]
                connectInhId = moose.connect( self.network.vec[preIdx], \
                    'spikeOut', synij, 'addSpike')
                synij.delay = syndelay
                synij.weight = -self.scaleI * self.J  # activation = weight

        ## Connections from some Exc/Inh neurons to each Inh neuron
        for i in range(self.N - self.NmaxExc):
            ## each neuron has incC number of synapses
            self.synsI.vec[i].numSynapses = self.incC

            ## draw excC number of neuron indices out of NmaxExc neurons
            preIdxs = random.sample(range(self.NmaxExc), self.excC)
            ## connect these presynaptically to i-th post-synaptic neuron
            for synnum, preIdx in enumerate(preIdxs):
                synij = self.synsI.vec[i].synapse[synnum]
                connectExcId = moose.connect( self.network.vec[preIdx], \
                    'spikeOut', synij, 'addSpike')
                synij.delay = syndelay
                synij.weight = self.J  # activation = weight

            ## draw inhC=incC-excC number of neuron indices out of inhibitory neurons
            preIdxs = random.sample(range(self.NmaxExc, self.N),
                                    self.incC - self.excC)
            ## connect these presynaptically to i-th post-synaptic neuron
            for synnum, preIdx in enumerate(preIdxs):
                synij = self.synsI.vec[i].synapse[self.excC + synnum]
                connectInhId = moose.connect( self.network.vec[preIdx], \
                    'spikeOut', synij, 'addSpike')
                synij.delay = syndelay
                synij.weight = -self.scaleI * self.J  # activation = weight

        moose.useClock(0, '/network/synsIE', 'process')
        moose.useClock(0, '/network/synsI', 'process')
def makeModel():
    # create container for model
    model = moose.Neutral('model')
    compt0 = moose.CubeMesh('/model/compt0')
    compt0.volume = 1e-18
    compt1 = moose.CubeMesh('/model/compt1')
    compt1.volume = 1e-19
    compt2 = moose.CubeMesh('/model/compt2')
    compt2.volume = 1e-20

    # Position containers so that they abut each other, with
    # compt1 in the middle.
    side = compt1.dy
    compt0.y1 += side
    compt0.y0 += side
    compt2.x1 += side
    compt2.x0 += side
    print(('Volumes = ', compt0.volume, compt1.volume, compt2.volume))

    # create molecules and reactions
    a = moose.Pool('/model/compt0/a')
    b = moose.Pool('/model/compt1/b')
    c = moose.Pool('/model/compt2/c')
    reac0 = moose.Reac('/model/compt1/reac0')
    reac1 = moose.Reac('/model/compt1/reac1')

    # connect them up for reactions
    moose.connect(reac0, 'sub', a, 'reac')
    moose.connect(reac0, 'prd', b, 'reac')
    moose.connect(reac1, 'sub', b, 'reac')
    moose.connect(reac1, 'prd', c, 'reac')

    # Assign parameters
    a.concInit = 1
    b.concInit = 12.1
    c.concInit = 1
    reac0.Kf = 0.1
    reac0.Kb = 0.1
    reac1.Kf = 0.1
    reac1.Kb = 0.1

    # Create the output tables
    graphs = moose.Neutral('/model/graphs')
    outputA = moose.Table2('/model/graphs/concA')
    outputB = moose.Table2('/model/graphs/concB')
    outputC = moose.Table2('/model/graphs/concC')

    # connect up the tables
    moose.connect(outputA, 'requestOut', a, 'getConc')
    moose.connect(outputB, 'requestOut', b, 'getConc')
    moose.connect(outputC, 'requestOut', c, 'getConc')

    # Build the solvers. No need for diffusion in this version.
    ksolve0 = moose.Gsolve('/model/compt0/ksolve0')
    ksolve1 = moose.Gsolve('/model/compt1/ksolve1')
    ksolve2 = moose.Gsolve('/model/compt2/ksolve2')
    stoich0 = moose.Stoich('/model/compt0/stoich0')
    stoich1 = moose.Stoich('/model/compt1/stoich1')
    stoich2 = moose.Stoich('/model/compt2/stoich2')

    # Configure solvers
    stoich0.compartment = compt0
    stoich1.compartment = compt1
    stoich2.compartment = compt2
    stoich0.ksolve = ksolve0
    stoich1.ksolve = ksolve1
    stoich2.ksolve = ksolve2
    stoich0.path = '/model/compt0/#'
    stoich1.path = '/model/compt1/#'
    stoich2.path = '/model/compt2/#'
    stoich1.buildXreacs(stoich0)
    stoich1.buildXreacs(stoich2)
    stoich0.filterXreacs()
    stoich1.filterXreacs()
    stoich2.filterXreacs()
Example #51
0
def test_ksolver_parallel(nthreads=4):
    """
    This example implements a reaction-diffusion like system which is
    bistable and propagates losslessly. It is based on the NEURON example 
    rxdrun.py, but incorporates more compartments and runs for a longer time.
    The system is implemented as a hybrid of a reaction and a function which
    sets its rates. Please see rxdFuncDiffusion.py for a variant that uses
    just a function object to set up the system.
    """

    dt = 0.1

    # define the geometry
    compt = moose.CylMesh('/cylinder')
    compt.r0 = compt.r1 = 1
    #  compt.diffLength = 1e-6
    compt.x1 = 1e-2
    assert compt.numDiffCompts == int(
        compt.x1 / compt.diffLength), (compt.numDiffCompts,
                                       compt.x1 / compt.diffLength)
    print('No of compartment %d' % compt.numDiffCompts)

    #define the molecule. Its geometry is defined by its parent volume, cylinder
    c = moose.Pool('/cylinder/pool')
    c.diffConst = 1  # define diffusion constant
    # There is an implicit reaction substrate/product. MOOSE makes it explicit.
    buf = moose.BufPool('/cylinder/buf')
    buf.nInit = 1

    # The reaction is something entirely peculiar, not a chemical thing.
    reaction = moose.Reac('/cylinder/reac')
    reaction.Kb = 0

    # so here we set up a function calculation to do the same thing.
    func = moose.Function('/cylinder/reac/func')
    func.expr = "(1 - x0) * (0.3 - x0)"
    func.x.num = 1  #specify number of input variables.

    #Connect the reaction to the pools
    moose.connect(reaction, 'sub', c, 'reac')
    moose.connect(reaction, 'prd', buf, 'reac')

    #Connect the function to the reaction
    moose.connect(func, 'valueOut', reaction, 'setNumKf')

    #Connect the molecules to the func
    moose.connect(c, 'nOut', func.x[0], 'input')

    #Set up solvers
    ksolve = moose.Ksolve('/cylinder/ksolve')
    ksolve.numThreads = nthreads
    dsolve = moose.Dsolve('/cylinder/dsolve')
    stoich = moose.Stoich('/cylinder/stoich')
    stoich.compartment = compt
    stoich.ksolve = ksolve
    stoich.dsolve = dsolve
    stoich.path = '/cylinder/##'
    for i in range(10, 18):
        moose.setClock(i, dt)

    #initialize
    x = np.arange(0, compt.x1, compt.diffLength)
    c.vec.nInit = [(q < 0.2 * compt.x1) for q in x]

    expected = [(0.2, 0.40000000000000013),
                (2.6704795776286974e-07, 1.2678976830753021e-17),
                (8.167639617309419e-14, 3.8777269301457245e-24),
                (2.498062905267963e-20, 1.1860363878961374e-30),
                (7.64029581501609e-27, 3.6273808003690943e-37)]

    # Run and plot it.
    moose.reinit()
    updateDt = 50
    runtime = updateDt * 4
    yvec = c.vec.n
    u1, m1 = np.mean(yvec), np.std(yvec)
    print(u1, m1)
    assert np.isclose((u1, m1), expected[0], atol=1e-5).all(), expected[0]
    t1 = time.time()
    for i, t in enumerate(range(0, runtime - 1, updateDt)):
        moose.start(updateDt)
        yvec = c.vec.n
        u1, m1 = np.mean(yvec), np.std(yvec)
        print(u1, m1)
        np.isclose((u1, m1), expected[i + 1], atol=1e-5).all(), expected[i + 1]
    return time.time() - t1
Example #52
0
def main():
    """
This example implements a reaction-diffusion like system which is
bistable and propagates losslessly. It is based on the NEURON example
rxdrun.py, but incorporates more compartments and runs for a longer time.
The system is implemented in a function rather than as a proper system
of chemical reactions. Please see rxdReacDiffusion.py for a variant that
uses a reaction plus a function object to control its rates.

    """

    print(('[DEBUG] Using moose from %s' % moose.__file__))

    dt = 0.1

    # define the geometry
    compt = moose.CylMesh('/cylinder')
    compt.r0 = compt.r1 = 1
    compt.x1 = 100
    compt.diffLength = 0.2
    assert (compt.numDiffCompts == compt.x1 / compt.diffLength)

    #define the molecule. Its geometry is defined by its parent volume, cylinder
    c = moose.Pool('/cylinder/pool')
    c.diffConst = 1  # define diffusion constant

    # Here we set up a function calculation
    func = moose.Function('/cylinder/pool/func')
    func.expr = "-x0 * (0.3 - x0) * (1 - x0)"
    func.x.num = 1  #specify number of input variables.

    #Connect the molecules to the func
    moose.connect(c, 'nOut', func.x[0], 'input')
    #Connect the function to the pool
    moose.connect(func, 'valueOut', c, 'increment')

    #Set up solvers
    ksolve = moose.Ksolve('/cylinder/ksolve')
    dsolve = moose.Dsolve('/cylinder/dsolve')
    stoich = moose.Stoich('/cylinder/stoich')
    stoich.ksolve = ksolve
    stoich.dsolve = dsolve
    stoich.compartment = compt
    stoich.path = '/cylinder/##'

    #initialize
    x = numpy.arange(0, compt.x1, compt.diffLength)
    c.vec.nInit = [(q < 0.2 * compt.x1) for q in x]

    # Run and plot it.
    moose.reinit()
    updateDt = 50
    runtime = updateDt * 4
    plt = pylab.plot(x, c.vec.n, label='t = 0 ')
    t1 = time.time()
    for t in range(0, runtime - 1, updateDt):
        moose.start(updateDt)
        plt = pylab.plot(x, c.vec.n, label='t = ' + str(t + updateDt))
    print(("Time = %f " % (time.time() - t1)))

    print(("Time = %s " % (time.time() - t1)))
    pylab.ylim(0, 1.05)
    pylab.legend()
    pylab.show()
Example #53
0
def buildPlots( rdes ):
    numPlots = 10
    caPsd = moose.vec( '/model/chem/psd/Ca' )
    caHead = moose.vec( '/model/chem/spine/Ca' )
    psdR = moose.vec( '/model/chem/psd/tot_PSD_R' )
    numSpines = rdes.spineCompt.mesh.num
    assert( 2 * numSpines == len( rdes.spineComptElist ) )
    if not moose.exists( '/graphs' ):
        moose.Neutral( '/graphs' )
    assert( len( caPsd ) == numSpines )
    assert( len( caHead ) == numSpines )
    if numSpines < numPlots:
        caPsdTab = moose.Table2( '/graphs/caPsdTab', numSpines ).vec
        caHeadTab = moose.Table2( '/graphs/caHeadTab', numSpines ).vec
        psdRtab = moose.Table2( '/graphs/psdRtab', numSpines ).vec
        for i in range( numSpines ):
            moose.connect( caPsdTab[i], 'requestOut', caPsd[i], 'getConc' )
            moose.connect( caHeadTab[i], 'requestOut', caHead[i], 'getConc')
            moose.connect( psdRtab[i], 'requestOut', psdR[i], 'getN' )
    else:
        caPsdTab = moose.Table2( '/graphs/caPsdTab', numPlots ).vec
        caHeadTab = moose.Table2( '/graphs/caHeadTab', numPlots ).vec
        psdRtab = moose.Table2( '/graphs/psdRtab', numPlots ).vec
        dx = numSpines / numPlots
        for i in range( numPlots ):
            moose.connect( caPsdTab[i], 'requestOut', caPsd[i*dx], 'getConc' )
            moose.connect( caHeadTab[i], 'requestOut', caHead[i*dx], 'getConc' )
            moose.connect( psdRtab[i], 'requestOut', psdR[i*dx], 'getN' )
    vtab = moose.Table( '/graphs/vtab' )
    moose.connect( vtab, 'requestOut', rdes.soma, 'getVm' )
    eSpineCaTab = moose.Table( '/graphs/eSpineCaTab' )
    path = rdes.spineComptElist[1].path + "/Ca_conc"
    moose.connect( eSpineCaTab, 'requestOut', path, 'getCa' )
    eSpineVmTab = moose.Table( '/graphs/eSpineVmTab' )
    moose.connect( eSpineVmTab, 'requestOut', rdes.spineComptElist[1], 'getVm' )
    eSpineGkTab = moose.Table( '/graphs/eSpineGkTab' )
    path = rdes.spineComptElist[1].path + "/NMDA"
    moose.connect( eSpineGkTab, 'requestOut', path, 'getGk' )
Example #54
0
def vclamp_demo(simtime=50.0, dt=1e-2):
    ## It is good practice to modularize test elements inside a
    ## container
    container = moose.Neutral('/vClampDemo')
    ## Create a compartment with properties of a squid giant axon
    comp = SquidAxon('/vClampDemo/axon')
    # Create and setup the voltage clamp object
    clamp = moose.VClamp('/vClampDemo/vclamp')
    ## The defaults should work fine
    # clamp.mode = 2
    # clamp.tau = 10*dt
    # clamp.ti = dt
    # clamp.td = 0
    # clamp.gain = comp.Cm / dt
    ## Setup command voltage time course
    command = moose.PulseGen('/vClampDemo/command')
    command.delay[0] = 10.0
    command.width[0] = 20.0
    command.level[0] = 50.0
    command.delay[1] = 1e9
    moose.connect(command, 'output', clamp, 'commandIn')
    ## Connect the Voltage Clamp to the compartemnt
    moose.connect(clamp, 'currentOut', comp, 'injectMsg')
    moose.connect(comp, 'VmOut', clamp, 'sensedIn')
    ## setup stimulus recroding - this is the command pulse
    stimtab = moose.Table('/vClampDemo/vclamp_command')
    moose.connect(stimtab, 'requestOut', command, 'getOutputValue')
    ## Set up Vm recording
    vmtab = moose.Table('/vClampDemo/vclamp_Vm')
    moose.connect(vmtab, 'requestOut', comp, 'getVm')
    ## setup command potential recording - this is the filtered input
    ## to PID controller
    commandtab = moose.Table('/vClampDemo/vclamp_filteredcommand')
    moose.connect(commandtab, 'requestOut', clamp, 'getCommand')
    ## setup current recording
    Imtab = moose.Table('/vClampDemo/vclamp_inject')
    moose.connect(Imtab, 'requestOut', clamp, 'getCurrent')
    # Scheduling
    moose.setClock(0, dt)
    moose.setClock(1, dt)
    moose.setClock(2, dt)
    moose.setClock(3, dt)
    moose.useClock(0, '%s/##[TYPE=Compartment]' % (container.path), 'init')
    moose.useClock(0, '%s/##[TYPE=PulseGen]' % (container.path), 'process')
    moose.useClock(1, '%s/##[TYPE=Compartment]' % (container.path), 'process')
    moose.useClock(2, '%s/##[TYPE=HHChannel]' % (container.path), 'process')
    moose.useClock(2, '%s/##[TYPE=VClamp]' % (container.path), 'process')
    moose.useClock(3, '%s/##[TYPE=Table]' % (container.path), 'process')
    moose.reinit()
    print 'RC filter in VClamp:: tau:', clamp.tau
    print 'PID controller in VClamp:: ti:', clamp.ti, 'td:', clamp.td, 'gain:', clamp.gain
    moose.start(simtime)
    print 'Finished simulation for %g seconds' % (simtime)
    tseries = linspace(0, simtime, len(vmtab.vector))
    subplot(211)
    title('Membrane potential and clamp voltage')
    plot(tseries, vmtab.vector, 'g-', label='Vm (mV)')
    plot(tseries, commandtab.vector, 'b-', label='Filtered command (mV)')
    plot(tseries, stimtab.vector, 'r-', label='Command (mV)')
    xlabel('Time (ms)')
    ylabel('Voltage (mV)')
    legend()
    # print len(commandtab.vector)
    subplot(212)
    title('Current through clamp circuit')
    # plot(tseries, stimtab.vector, label='stimulus (uA)')
    plot(tseries, Imtab.vector, label='injected current (uA)')
    xlabel('Time (ms)')
    ylabel('Current (uA)')
    legend()
    show()
Example #55
0
def makeNeuroMeshModel():
    diffLength = 20e-6  # But we only want diffusion over part of the model.
    numSyn = 13
    elec = loadElec()
    synInput = moose.SpikeGen('/model/elec/synInput')
    synInput.refractT = 47e-3
    synInput.threshold = -1.0
    synInput.edgeTriggered = 0
    synInput.Vm(0)

    synInput.refractT = 47e-3
    for i in range(numSyn):
        name = '/model/elec/spine_head_14_' + str(i + 1)
        r = moose.element(name + '/glu')
        r.synapse.num = 1
        syn = moose.element(r.path + '/synapse')
        moose.connect(synInput, 'spikeOut', syn, 'addSpike', 'Single')
        syn.weight = 0.2 * i * (numSyn - 1 - i)
        syn.delay = i * 1.0e-3

    neuroCompt = moose.NeuroMesh('/model/neuroMesh')
    #print 'neuroMeshvolume = ', neuroCompt.mesh[0].volume
    neuroCompt.separateSpines = 1
    neuroCompt.diffLength = diffLength
    neuroCompt.geometryPolicy = 'cylinder'
    spineCompt = moose.SpineMesh('/model/spineMesh')
    #print 'spineMeshvolume = ', spineCompt.mesh[0].volume
    moose.connect(neuroCompt, 'spineListOut', spineCompt, 'spineList',
                  'OneToOne')
    psdCompt = moose.PsdMesh('/model/psdMesh')
    #print 'psdMeshvolume = ', psdCompt.mesh[0].volume
    moose.connect(neuroCompt, 'psdListOut', psdCompt, 'psdList', 'OneToOne')
    loadChem(neuroCompt, spineCompt, psdCompt)

    # Put in the solvers, see how they fare.
    nmksolve = moose.GslStoich('/model/chem/neuroMesh/ksolve')
    nmksolve.path = '/model/chem/neuroMesh/##'
    nmksolve.compartment = moose.element('/model/chem/neuroMesh')
    nmksolve.method = 'rk5'
    nm = moose.element('/model/chem/neuroMesh/mesh')
    moose.connect(nm, 'remesh', nmksolve, 'remesh')
    #print "neuron: nv=", nmksolve.numLocalVoxels, ", nav=", nmksolve.numAllVoxels, nmksolve.numVarPools, nmksolve.numAllPools

    #print 'setting up smksolve'
    smksolve = moose.GslStoich('/model/chem/spineMesh/ksolve')
    smksolve.path = '/model/chem/spineMesh/##'
    smksolve.compartment = moose.element('/model/chem/spineMesh')
    smksolve.method = 'rk5'
    sm = moose.element('/model/chem/spineMesh/mesh')
    moose.connect(sm, 'remesh', smksolve, 'remesh')
    #print "spine: nv=", smksolve.numLocalVoxels, ", nav=", smksolve.numAllVoxels, smksolve.numVarPools, smksolve.numAllPools
    #
    #print 'setting up pmksolve'
    pmksolve = moose.GslStoich('/model/chem/psdMesh/ksolve')
    pmksolve.path = '/model/chem/psdMesh/##'
    pmksolve.compartment = moose.element('/model/chem/psdMesh')
    pmksolve.method = 'rk5'
    pm = moose.element('/model/chem/psdMesh/mesh')
    moose.connect(pm, 'remesh', pmksolve, 'remesh')
    #print "psd: nv=", pmksolve.numLocalVoxels, ", nav=", pmksolve.numAllVoxels, pmksolve.numVarPools, pmksolve.numAllPools
    #
    print 'neuroMeshvolume = ', neuroCompt.mesh[0].volume

    #print 'Assigning the cell model'
    # Now to set up the model.
    #neuroCompt.cell = elec
    neuroCompt.cellPortion(
        elec,
        '/model/elec/lat_14_#,/model/elec/spine_neck#,/model/elec/spine_head#')
    """
	ns = neuroCompt.numSegments
	#assert( ns == 11 ) # dend, 5x (shaft+head)
	ndc = neuroCompt.numDiffCompts
	#print 'numDiffCompts = ', ndc
	assert( ndc == 145 )
	ndc = neuroCompt.mesh.num
	#print 'NeuroMeshNum = ', ndc
	assert( ndc == 145 )

	sdc = spineCompt.mesh.num
	#print 'SpineMeshNum = ', sdc
	assert( sdc == 13 )
	pdc = psdCompt.mesh.num
	#print 'PsdMeshNum = ', pdc
	assert( pdc == 13 )
	"""

    mesh = moose.vec('/model/chem/neuroMesh/mesh')
    #for i in range( ndc ):
    #	print 's[', i, '] = ', mesh[i].volume
    mesh2 = moose.vec('/model/chem/spineMesh/mesh')
    #	for i in range( sdc ):
    #		print 's[', i, '] = ', mesh2[i].volume
    #print 'numPSD = ', moose.element( '/model/chem/psdMesh/mesh' ).localNumField
    mesh = moose.vec('/model/chem/psdMesh/mesh')
    #print 'psd mesh.volume = ', mesh.volume
    #for i in range( pdc ):
    #	print 's[', i, '] = ', mesh[i].volume
    #
    # We need to use the spine solver as the master for the purposes of
    # these calculations. This will handle the diffusion calculations
    # between head and dendrite, and between head and PSD.
    smksolve.addJunction(nmksolve)
    #print "spine: nv=", smksolve.numLocalVoxels, ", nav=", smksolve.numAllVoxels, smksolve.numVarPools, smksolve.numAllPools
    smksolve.addJunction(pmksolve)
    #print "psd: nv=", pmksolve.numLocalVoxels, ", nav=", pmksolve.numAllVoxels, pmksolve.numVarPools, pmksolve.numAllPools
    ndc = neuroCompt.numDiffCompts
    #print 'numDiffCompts = ', ndc
    assert (ndc == 13)
    ndc = neuroCompt.mesh.num
    #print 'NeuroMeshNum = ', ndc
    assert (ndc == 13)
    sdc = spineCompt.mesh.num
    #print 'SpineMeshNum = ', sdc
    assert (sdc == 13)
    pdc = psdCompt.mesh.num
    #print 'PsdMeshNum = ', pdc
    assert (pdc == 13)
    """
	print 'neuroCompt'
	for i in range( ndc ):
			print i, neuroCompt.stencilIndex[i]
			print i, neuroCompt.stencilRate[i]

	print 'spineCompt'
	for i in range( sdc * 3 ):
			print i, spineCompt.stencilIndex[i]
			print i, spineCompt.stencilRate[i]

	print 'psdCompt'
	for i in range( pdc ):
			print i, psdCompt.stencilIndex[i]
			print i, psdCompt.stencilRate[i]
	print 'Spine parents:'
	pavoxel = spineCompt.parentVoxel
	for i in range( sdc ):
		print i, pavoxel[i]
	"""

    # oddly, numLocalFields does not work.
    #moose.le( '/model/chem/neuroMesh' )
    ca = moose.element('/model/chem/neuroMesh/DEND/Ca')
    assert (ca.lastDimension == ndc)
    """
	CaNpsd = moose.vec( '/model/chem/psdMesh/PSD/PP1_PSD/CaN' )
	print 'numCaN in PSD = ', CaNpsd.nInit, ', vol = ', CaNpsd.volume
	CaNspine = moose.vec( '/model/chem/spineMesh/SPINE/CaN_BULK/CaN' )
	print 'numCaN in spine = ', CaNspine.nInit, ', vol = ', CaNspine.volume
	"""

    # set up adaptors
    aCa = moose.Adaptor('/model/chem/psdMesh/adaptCa', pdc)
    adaptCa = moose.vec('/model/chem/psdMesh/adaptCa')
    chemCa = moose.vec('/model/chem/psdMesh/PSD/Ca')
    assert (len(adaptCa) == pdc)
    assert (len(chemCa) == pdc)
    for i in range(pdc):
        path = '/model/elec/spine_head_14_' + str(i + 1) + '/NMDA_Ca_conc'
        elecCa = moose.element(path)
        moose.connect(elecCa, 'concOut', adaptCa[i], 'input', 'Single')
    moose.connect(adaptCa, 'outputSrc', chemCa, 'setConc', 'OneToOne')
    adaptCa.inputOffset = 0.0  #
    adaptCa.outputOffset = 80e-6  # 80 nM offset in chem.
    adaptCa.scale = 1e-5  # 520 to 0.0052 mM
Example #56
0
def writeEnz(modelpath, f, sceneitems):
    error = ""
    enzList = moose.wildcardFind(modelpath + '/##[0][ISA=EnzBase]')
    for enz in enzList:
        if findCompartment(enz) == moose.element('/'):
            error = error + " \n " + enz.path + " doesn't have compartment ignored to write to genesis"
        else:
            x = random.randrange(0, 10)
            y = random.randrange(0, 10)
            textcolor = ""
            color = ""
            k1 = 0
            k2 = 0
            k3 = 0
            nInit = 0
            concInit = 0
            n = 0
            conc = 0
            if len(moose.element(enz).neighbors['enzDest']) == 1:
                enzParent = moose.element(
                    moose.element(enz).neighbors['enzDest'][0])

            if not enzParent.isA['PoolBase']:
                print(" raise exception enz doesn't have pool as parent %s",
                      moose.element(enz).path)
                return False
            else:
                vol = enzParent.volume * NA * 1e-3
                isMichaelisMenten = 0
                enzClass = enz.className
                if (enzClass == "ZombieMMenz" or enzClass == "MMenz"):
                    k1 = enz.numKm
                    k3 = enz.kcat
                    k2 = 4.0 * k3
                    k1 = (k2 + k3) / k1
                    isMichaelisMenten = 1

                elif (enzClass == "ZombieEnz" or enzClass == "Enz"):
                    k1 = enz.k1
                    k2 = enz.k2
                    k3 = enz.k3
                    if enz.neighbors['cplx']:
                        cplx = enz.neighbors['cplx'][0]
                        nInit = cplx.nInit
                    else:
                        cplx = moose.Pool(enz.path + "/cplx")
                        moose.Annotator(cplx.path + '/info')
                        moose.connect(enz, 'cplx', cplx, 'reac')
                        nInit = cplx.nInit

                einfo = enz.path + '/info'
                if moose.exists(einfo):
                    x = sceneitems[enz]['x']
                    y = sceneitems[enz]['y']
                    color = moose.Annotator(einfo).getField('color')
                    color = getColorCheck(color, GENESIS_COLOR_SEQUENCE)

                    textcolor = moose.Annotator(einfo).getField('textColor')
                    textcolor = getColorCheck(textcolor,
                                              GENESIS_COLOR_SEQUENCE)
                else:
                    error = error + "\n x and y co-ordinates are not specified for `" + enz.name + "` zero will be assigned \n "
                if color == "" or color == " ":
                    color = getRandomColor()
                if textcolor == "" or textcolor == " ":
                    textcolor = getRandomColor()

                f.write("simundump kenz /kinetics/" + trimPath(enz) + " " +
                        str(int(0)) + " " + str(concInit) + " " + str(conc) +
                        " " + str(nInit) + " " + str(n) + " " + str(vol) +
                        " " + str(k1) + " " + str(k2) + " " + str(k3) + " " +
                        str(0) + " " + str(isMichaelisMenten) + " " + "\"\"" +
                        " " + str(textcolor) + " " + str(color) + " \"\"" +
                        " " + str(int(x)) + " " + str(int(y)) + " " +
                        str(int(0)) + "\n")
    return enzList, error
Example #57
0
def makeModel():
    # create container for model
    num = 1 # number of compartments
    model = moose.Neutral( '/model' )
    compartment = moose.CylMesh( '/model/compartment' )
    compartment.x1 = 1.0e-6 # Set it to a 1 micron single-voxel cylinder

    # create molecules and reactions
    u = moose.Pool( '/model/compartment/u' )
    #####################################################################
    # Put in endo compartment. Add molecule s
    endo = moose.EndoMesh( '/model/endo' )
    endo.isMembraneBound = True
    endo.surround = compartment
    rXfer = moose.Reac( '/model/endo/rXfer' )
    et = moose.Pool( '/model/endo/t' )
    es = moose.Pool( '/model/endo/s' )
    #####################################################################
    moose.connect( rXfer, 'sub', u, 'reac' )
    moose.connect( rXfer, 'sub', et, 'reac' )
    moose.connect( rXfer, 'prd', es, 'reac' )
    u.concInit = 1.0
    et.concInit = 1.0

    #####################################################################
    # [u0] = 1 in compt, [t0] = 1 in endo, [s0] = 0
    # [u] + [s]/8 = [u0]  ; [t] + [s] = [t0]; nu + ns = nu0, nt + ns = nt0
    # At equil, numKf*nu*nt = numKb*ns
    # Express all # in terms of ns.
    # nu = nu0-ns; nt = nt0-ns      Also, nu0 = 8*nt0
    # So  numKf*(nu0-ns)*(nt0-ns) = numKb*ns
    # Target level is nt = ns = nt0/2
    # So numKf*( 8nt0 - nt0/2)*nt0/2 = numKb*nt0/2
    # So 7.5*nt0 = numKb/numKf
    rXfer.numKb = 0.1
    rXfer.numKf = 0.1/(7.5 * et.nInit)
    #print( "Rates = {}, {}".format( rXfer.Kf, rXfer.Kb ))
    #####################################################################
    fixXreacs.fixXreacs( '/model' )
    #fixXreacs.restoreXreacs( '/model' )
    #fixXreacs.fixXreacs( '/model' )
    #####################################################################

    # Make solvers
    ksolve = moose.Ksolve( '/model/compartment/ksolve' )
    dsolve = moose.Dsolve( '/model/compartment/dsolve' )
    eksolve = moose.Ksolve( '/model/endo/ksolve' )
    edsolve = moose.Dsolve( '/model/endo/dsolve' )

    stoich = moose.Stoich( '/model/compartment/stoich' )
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.dsolve = dsolve
    stoich.path = "/model/compartment/##"
    assert( dsolve.numPools == 1 )

    estoich = moose.Stoich( '/model/endo/stoich' )
    estoich.compartment = endo
    estoich.ksolve = eksolve
    estoich.dsolve = edsolve
    estoich.path = "/model/endo/##"
    assert( edsolve.numPools == 3 )

    edsolve.buildMeshJunctions( dsolve )

    plot1 = moose.Table2( '/model/plot1' )
    plot2 = moose.Table2( '/model/plot2' )
    plot3 = moose.Table2( '/model/plot3' )
    moose.connect( '/model/plot1', 'requestOut', u, 'getN' )
    moose.connect( '/model/plot2', 'requestOut', et, 'getN' )
    moose.connect( '/model/plot3', 'requestOut', es, 'getN' )
    plot4 = moose.Table2( '/model/plot4' )
    plot5 = moose.Table2( '/model/plot5' )
    plot6 = moose.Table2( '/model/plot6' )
    moose.connect( '/model/plot4', 'requestOut', u, 'getConc' )
    moose.connect( '/model/plot5', 'requestOut', et, 'getConc' )
    moose.connect( '/model/plot6', 'requestOut', es, 'getConc' )
Example #58
0
def main():
    """
In this example we walk through creation of a vector of IntFire
elements and setting up synaptic connection between them. Synapse on
IntFire elements is an example of ElementField - elements that do not
exist on their own, but only as part of another element. This example
also illustrates various operations on `vec` objects and
ElementFields.

    """
    size = 1024  # number of IntFire objects in a vec
    delayMin = 0
    delayMax = 4
    Vmax = 1.0
    thresh = 0.8
    refractoryPeriod = 0.4
    connectionProbability = 0.1
    weightMax = 0.5
    # The above sets the constants we shall use in this example. Now we create a vector of IntFire elements of size `size`.

    net = moose.IntFire('/network', size)
    # This creates a `vec` of `IntFire`  elements of size 1024 and returns the first `element`, i.e. "/network[0]".

    net = moose.element('/network[0]')

    # You need now to provide synaptic input to the network
    synh = moose.SimpleSynHandler('/network/synh', size)

    # These need to be connected to the nodes in the network
    moose.connect(synh, 'activationOut', net, 'activation', 'OneToOne')

    # You can access the underlying vector of elements using the `vec` field on any element. This is very useful for vectorized field access:
    net.vec.Vm = [thresh / 2.0] * size
    # The right part of the assigment creates a Python list of length `size` with each element set to `thresh/2.0`, which is 0.4. You can index into the `vec` to access individual elements' field:

    print((net.vec[1].Vm))

    # `SimpleSynHandler` class has an `ElementField` called `synapse`. It is just like a `vec` above in terms of field access, but by default its size is 0.
    print((len(synh.synapse)))

    # To actually create synapses, you can explicitly assign the `num` field of this, or set the `numSynapses` field of the `IntFire` element. There are some functions which can implicitly set the size of the `ElementField`.
    synh.numSynapses = 3
    print((len(synh.synapse)))

    synh.synapse.num = 4
    print((len(synh.synapse)))

    # Now you can index into `net.synapse` as if it was an array.
    print(('Before:', synh.synapse[0].delay))
    synh.synapse[0].delay = 1.0
    print(('After:', synh.synapse[0].delay))

    # You could do the same vectorized assignment as with `vec` directly:
    synh.synapse.weight = [0.2] * len(synh.synapse)
    print((synh.synapse.weight))

    # You can create the synapses and assign the weights and delays using loops:
    for syn in synh.vec:
        syn.synapse.num = random.randint(1, 10)
    # create synapse fields with random size between 1 and 10, end points included
    # Below is one (inefficient) way of setting the individual weights of the elements in 'synapse'
    for ii in range(len(syn.synapse)):
        syn.synapse[ii].weight = random.random() * weightMax
    # This is a more efficient way - rhs of `=` is list comprehension in Python and rather fast
    syn.synapse.delay = [
        delayMin + random.random() * delayMax for ii in range(len(syn.synapse))
    ]
    # An even faster way will be to use numpy.random.rand(size) which produces array of random numbers uniformly distributed between 0 and 1
    syn.synapse.delay = delayMin + nprand.rand(len(syn.synapse)) * delayMax

    # Now display the results, we use slice notation on `vec` to show the values of delay and weight for the first 5 elements in `/network`
    for syn in synh.vec[:5]:
        print(('Delays for synapses on ', syn.path, ':', syn.synapse.delay))
        print(('Weights for synapses on ', syn.path, ':', syn.synapse.weight))
Example #59
0
def make_model():
    sinePeriod = 50
    maxFiringRate = 10
    refractT = 0.05

    for i in range(20):
        moose.setClock(i, dt)

    ############### Create objects ###############
    stim = moose.StimulusTable('stim')
    spike = moose.RandSpike('spike')
    syn = moose.SimpleSynHandler('syn')
    fire = moose.IntFire('fire')
    stats1 = moose.SpikeStats('stats1')
    stats2 = moose.Stats('stats2')
    plots = moose.Table('plots')
    plot1 = moose.Table('plot1')
    plot2 = moose.Table('plot2')
    plotf = moose.Table('plotf')

    ############### Set up parameters ###############
    stim.vector = [
        maxFiringRate * numpy.sin(x * 2 * numpy.pi / sinePeriod)
        for x in range(sinePeriod)
    ]
    stim.startTime = 0
    stim.stopTime = sinePeriod
    stim.loopTime = sinePeriod
    stim.stepSize = 0
    stim.stepPosition = 0
    stim.doLoop = 1

    spike.refractT = refractT
    syn.synapse.num = 1
    syn.synapse[0].weight = 1
    syn.synapse[0].delay = 0

    fire.thresh = 100  # Don't want it to spike, just to integrate
    fire.tau = 1.0 / maxFiringRate

    stats1.windowLength = int(1 / dt)
    stats2.windowLength = int(1 / dt)

    ############### Connect up circuit ###############
    moose.connect(stim, 'output', spike, 'setRate')
    moose.connect(spike, 'spikeOut', syn.synapse[0], 'addSpike')
    moose.connect(spike, 'spikeOut', stats1, 'addSpike')
    moose.connect(syn, 'activationOut', fire, 'activation')
    moose.connect(stats2, 'requestOut', fire, 'getVm')
    moose.connect(plots, 'requestOut', stim, 'getOutputValue')
    moose.connect(plot1, 'requestOut', stats1, 'getWmean')
    moose.connect(plot2, 'requestOut', stats2, 'getWmean')
    moose.connect(plotf, 'requestOut', fire, 'getVm')
Example #60
0
def makeModel():
    # create container for model
    num = 1  # number of compartments
    model = moose.Neutral('/model')
    compartment = moose.CylMesh('/model/compartment')
    compartment.x1 = 1.0e-6  # Set it to a 1 micron single-voxel cylinder

    # create molecules and reactions
    s = moose.Pool('/model/compartment/s')
    rXfer = moose.Reac('/model/compartment/rXfer')
    #####################################################################
    # Put in endo compartment. Add molecule s
    endo = moose.EndoMesh('/model/endo')
    endo.isMembraneBound = True
    endo.surround = compartment
    es = moose.Pool('/model/endo/s')
    erXfer = moose.Reac('/model/compartment/erXfer')
    #####################################################################
    moose.connect(erXfer, 'sub', es, 'reac')
    moose.connect(erXfer, 'prd', s, 'reac')
    moose.connect(rXfer, 'sub', s, 'reac')
    moose.connect(rXfer, 'prd', es, 'reac')
    rXfer.Kf = 0.04  # 0.04/sec
    rXfer.Kb = 0.0  # 0.02/sec
    erXfer.Kf = 0.02  # 0.04/sec
    erXfer.Kb = 0.0  # 0.02/sec

    #####################################################################
    fixXreacs.fixXreacs('/model')
    fixXreacs.restoreXreacs('/model')
    fixXreacs.fixXreacs('/model')
    #####################################################################
    rx = moose.element('/model/compartment/rXfer')
    erx = moose.element('/model/compartment/erXfer')

    # Make solvers
    ksolve = moose.Ksolve('/model/compartment/ksolve')
    dsolve = moose.Dsolve('/model/dsolve')
    eksolve = moose.Ksolve('/model/endo/ksolve')
    edsolve = moose.Dsolve('/model/endo/dsolve')

    stoich = moose.Stoich('/model/compartment/stoich')
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.dsolve = dsolve
    stoich.path = "/model/compartment/##"
    assert (dsolve.numPools == 2)
    s.vec.concInit = [1] * num

    estoich = moose.Stoich('/model/endo/stoich')
    estoich.compartment = endo
    estoich.ksolve = eksolve
    estoich.dsolve = edsolve
    estoich.path = "/model/endo/##"
    assert (edsolve.numPools == 1)

    edsolve.buildMeshJunctions(dsolve)

    plot1 = moose.Table2('/model/plot1')
    plot2 = moose.Table2('/model/plot2')
    moose.connect('/model/plot1', 'requestOut', s, 'getN')
    moose.connect('/model/plot2', 'requestOut', es, 'getN')
    plot3 = moose.Table2('/model/plot3')
    plot4 = moose.Table2('/model/plot4')
    moose.connect('/model/plot3', 'requestOut', s, 'getConc')
    moose.connect('/model/plot4', 'requestOut', es, 'getConc')