def main():
		makeModel()
                '''
                '''
		ksolve = moose.Ksolve( '/model/compartment/ksolve' )
		stoich = moose.Stoich( '/model/compartment/stoich' )
		stoich.compartment = moose.element( '/model/compartment' )
		stoich.ksolve = ksolve
		stoich.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/ksolve', 'process' )
                '''

		moose.reinit()
		moose.start( 100.0 ) # Run the model for 100 seconds.
                func = moose.element( '/model/compartment/d/func' )
                if useY:
                    func.expr = "-y0 + 10*y1"
                else:
                    func.expr = "-x0 + 10*x1"
		moose.start( 100.0 ) # Run the model for 100 seconds.
                #moose.showfields( '/model/compartment/d' )
                #moose.showfields( '/model/compartment/d/func' )
                print func.x.value
                print moose.element( '/model/compartment/b' ).n

		# Iterate through all plots, dump their contents to data.plot.
		displayPlots()

		quit()
Esempio n. 2
0
def load_axon():
    model = moose.loadModel("axon_passive.p", "/axon")
    for x in model[0].children:
        print x.path, x.class_
    pulsegen = moose.PulseGen("/pulsegen")
    pulsegen.delay[0] = simdt * 200  # The Axon.g in oldmoose flips the current every 20 pulses
    pulsegen.width[0] = simdt * 200
    pulsegen.level[0] = inject
    moose.connect(pulsegen, "outputOut", moose.element("/axon/soma"), "injectMsg")
    data = moose.Neutral("/data")
    tab = moose.Table("%s/Vm100" % (data.path))
    moose.connect(tab, "requestData", moose.ObjId("/axon/c100"), "get_Vm")
    pulsetab = moose.Table("/data/inject")
    moose.connect(pulsetab, "requestData", pulsegen, "get_output")
    solver = moose.HSolve("/hsolve")
    solver.dt = simdt
    solver.target = model.path
    return {
        "model": model,
        "Vm": tab,
        "inject": pulsetab,
        "soma": moose.element("/axon/soma"),
        "pulse": pulsegen,
        "solver": solver,
    }
Esempio n. 3
0
def make_HH_Na(name = 'HH_Na', parent='/library', vmin=-110e-3, vmax=50e-3, vdivs=3000):
    """Create a Hodhkin-Huxley Na channel under `parent`.

    vmin, vmax, vdivs: voltage range and number of divisions for gate tables

    """
    na = moose.HHChannel('%s/%s' % (parent, name))
    na.Ek = 50e-3
    na.Xpower = 3
    na.Ypower = 1
    v = np.linspace(vmin, vmax, vdivs+1) - EREST_ACT_HH
    m_alpha = per_ms * (25 - v * 1e3) / (10 * (np.exp((25 - v * 1e3) / 10) - 1))
    m_beta = per_ms * 4 * np.exp(- v * 1e3/ 18)
    m_gate = moose.element('%s/gateX' % (na.path))
    m_gate.min = vmin
    m_gate.max = vmax
    m_gate.divs = vdivs
    m_gate.tableA = m_alpha
    m_gate.tableB = m_alpha + m_beta
    h_alpha = per_ms * 0.07 * np.exp(-v / 20e-3)
    h_beta = per_ms * 1/(np.exp((30e-3 - v) / 10e-3) + 1)
    h_gate = moose.element('%s/gateY' % (na.path))
    h_gate.min = vmin
    h_gate.max = vmax
    h_gate.divs = vdivs
    h_gate.tableA = h_alpha
    h_gate.tableB = h_alpha + h_beta
    na.tick = -1
    return na
Esempio n. 4
0
def loadtree(hdfnode, moosenode):
    """Load the element tree saved under the group `hdfnode` into `moosenode`"""    
    pathclass = {}    
    basepath = hdfnode.attr['path']
    if basepath != '/':
        basepath = basepath + '/'
    emdata = hdfnode['ematrix'][:]
    sorted_paths = sorted(emdata['path'], key=lambda x: x.count('/'))
    dims = dict(emdata['path', 'dims'])
    classes = dict(emdata['path', 'class'])
    current = moose.getCwe()
    moose.setCwe(moosenode)
    # First create all the ematrices
    for path in sorted_paths:
        rpath = path[len(basepath):]
        classname = classes[path]
        shape = dims[path]
        em = moose.ematrix(rpath, shape, classname)
    wfields = {}
    for cinfo in moose__.element('/classes').children:
        cname = cinfo[0].name
        wfields[cname] = [f[len('set_'):] for f in moose__.getFieldNames(cname, 'destFinfo') 
                          if f.startswith('set_') and f not in ['set_this', 'set_name', 'set_lastDimension', 'set_runTime'] and not f.startswith('set_num_')]
        for key in hdfnode['/elements']:
            dset = hdfnode['/elements/'][key][:]
            fieldnames = dset.dtype.names
            for ii in range(len(dset)):
                obj = moose__.element(dset['path'][ii][len(basepath):])
                for f in wfields[obj.class_]:
                    obj.setField(f, dset[f][ii])
Esempio n. 5
0
def make_LCa( name = 'LCa', parent = '/library' ):
        if moose.exists( parent + '/' + name ):
                return
        Ca = moose.HHChannel( parent + '/' + name )
        Ca.Ek = ECA
        Ca.Gbar = 0
        Ca.Gk = 0
        Ca.Xpower = 2
        Ca.Ypower = 1
        Ca.Zpower = 0

        xgate = moose.element( parent + '/' + name + '/gateX' )
        xA = np.array( [ 1.6e3, 0, 1.0, -1.0 * (0.065 + EREST_ACT), -0.01389, -20e3 * (0.0511 + EREST_ACT), 20e3, -1.0, -1.0 * (0.0511 + EREST_ACT), 5.0e-3, 3000, -0.1, 0.05 ] )
        xgate.alphaParms = xA
        ygate = moose.element( parent + '/' + name + '/gateY' )
        ygate.min = -0.1
        ygate.max = 0.05
        ygate.divs = 3000
        yA = np.zeros( (ygate.divs + 1), dtype=float)
        yB = np.zeros( (ygate.divs + 1), dtype=float)


#Fill the Y_A table with alpha values and the Y_B table with (alpha+beta)
        dx = (ygate.max - ygate.min)/ygate.divs
        x = ygate.min
        for i in range( ygate.divs + 1 ):
                if ( x > EREST_ACT):
                        yA[i] = 5.0 * math.exp( -50 * (x - EREST_ACT) )
                else:
                        yA[i] = 5.0
                yB[i] = 5.0
                x += dx
        ygate.tableA = yA
        ygate.tableB = yB
        return Ca
Esempio n. 6
0
def printPsd( name ):
    # Print the vol, the path dist from soma, the electrotonic dist, and N
    psdR = moose.vec( '/model/chem/psd/tot_PSD_R' )
    neuronVoxel = moose.element( '/model/chem/spine' ).neuronVoxel
    elecComptMap = moose.element( '/model/chem/dend' ).elecComptMap
    print(("len( neuronVoxel = ", len( neuronVoxel), min( neuronVoxel), max( neuronVoxel)))
    print((len( elecComptMap), elecComptMap[0], elecComptMap[12]))
    neuron = moose.element( '/model/elec' )
    ncompts = neuron.compartments
    d = {}
    j = 0
    for i in ncompts:
        #print i
        d[i] = j
        j += 1

    f = open( name + ".txt", 'w' )
    for i in range( len( psdR ) ):
        n = psdR[i].n
        conc = psdR[i].conc
        vol = psdR[i].volume
        compt = elecComptMap[ neuronVoxel[i] ]
        #print compt
        segIndex = d[compt[0]]
        p = neuron.geometricalDistanceFromSoma[ segIndex ]
        L = neuron.electrotonicDistanceFromSoma[ segIndex ]
        s = str( i ) + "    " + str(n) + "  " + str( conc ) + "  " + str(p) + "  " + str(L) + "\n"
        f.write( s )
    f.close()
Esempio n. 7
0
def make_Na( name ):
    if moose.exists( '/library/' + name ):
        return
    Na = moose.HHChannel( '/library/' + name )
    Na.Ek = 0.055             #    V
    Na.Gbar = 300 * SOMA_A    #    S
    Na.Gk = 0                 #    S
    Na.Xpower = 2
    Na.Ypower = 1
    Na.Zpower = 0

    xgate = moose.element( Na.path + '/gateX' )
    xA = np.array( [ 320e3 * (0.0131 + EREST_ACT),
        -320e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.004, 
        -280e3 * (0.0401 + EREST_ACT), 280e3, -1.0, 
        -1.0 * (0.0401 + EREST_ACT), 5.0e-3, 
        3000, -0.1, 0.05 ] )
    xgate.alphaParms = xA

    ygate = moose.element( Na.path + '/gateY' )
    yA = np.array( [ 128.0, 0.0, 0.0, -1.0 * (0.017 + EREST_ACT), 0.018,
        4.0e3, 0.0, 1.0, -1.0 * (0.040 + EREST_ACT), -5.0e-3, 
        3000, -0.1, 0.05 ] )
    ygate.alphaParms = yA
    return Na
Esempio n. 8
0
def test_channel_gates():
    """Creates prototype channels under `/library` and plots the time
    constants (tau) and activation (minf, hinf, ninf) parameters for the
    channel gates.

    Does not execute any simulation.

    """
    lib = moose.Neutral('/library')
    na_proto = create_na_chan()
    k_proto = create_k_chan()
    m = moose.element('%s/gateX' % (na_proto.path))
    h = moose.element('%s/gateY' % (na_proto.path))
    n = moose.element('%s/gateX' % (k_proto.path))
    v = np.linspace(m.min,m.max, m.divs+1)
    plt.subplot(211)
    plt.plot(v, 1/m.tableB, label='tau_m')
    plt.plot(v, 1/h.tableB, label='tau_h')
    plt.plot(v, 1/n.tableB, label='tau_n')
    plt.legend()
    plt.subplot(212)
    plt.plot(v, m.tableA/m.tableB, label='m_inf')
    plt.plot(v, h.tableA/h.tableB, label='h_inf')
    plt.plot(v, n.tableA/n.tableB, label='n_inf')
    plt.legend()
    plt.show()
Esempio n. 9
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
Esempio n. 10
0
def make_K_A():
	if moose.exists( 'K_A' ):
		return
	K_A = moose.HHChannel( 'K_A' )
	K_A.Ek = EK				#	V
	K_A.Gbar = 50 * SOMA_A	#	S
	K_A.Gk = 0				#	S
	K_A.Xpower = 1
	K_A.Ypower = 1
	K_A.Zpower = 0

	xgate = moose.element( 'K_A/gateX' )
	xA = numpy.array( [ 20e3 * (0.0131 + EREST_ACT), 
		-20e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.01,
		-17.5e3 * (0.0401 + EREST_ACT), 
		17.5e3, -1.0, -1.0 * (0.0401 + EREST_ACT), 0.01,
		3000, -0.1, 0.05 ] )
	xgate.alphaParms = xA
	# xgate.alpha( 20e3 * (0.0131 + EREST_ACT), -20e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.01 )
	# xgate.beta( -17.5e3 * (0.0401 + EREST_ACT), 17.5e3, -1.0, -1.0 * (0.0401 + EREST_ACT), 0.01 )

	ygate = moose.element( 'K_A/gateY' )
	yA = numpy.array( [ 1.6, 0.0, 0.0, 0.013 - EREST_ACT, 0.018,
		50.0, 0.0, 1.0, -1.0 * (0.0101 + EREST_ACT), -0.005,
		3000, -0.1, 0.05 ] )
	ygate.alphaParms = yA
def makeAdaptors():
    ##################################################################
    # set up adaptor for elec model Ca -> chem model Ca
    # Here it is easy because we don't have to deal with different
    # sizes of electrical and chemical compartments. 
    adaptCa = moose.Adaptor( '/model/chem/kinetics/adaptCa' )
    chemCa = moose.element( '/model/chem/kinetics/Ca' )
    elecCa = moose.element( '/model/elec/soma/Ca_conc' )
    moose.connect( elecCa, 'concOut', adaptCa, 'input' )
    moose.connect( adaptCa, 'output', chemCa, 'setConc' )
    adaptCa.inputOffset = 0.0    # 
    adaptCa.outputOffset = 0.00008    # 80 nM offset in chem.
    adaptCa.scale = 0.0008   

    # set up adaptor for chem model chan -> elec model chan.
    adaptChan = moose.Adaptor( '/model/chem/kinetics/adaptChan' )
    chemChan = moose.element( '/model/chem/kinetics/chan' )
    elecChan = moose.element( '/model/elec/soma/K_A' )
    # The Adaptor has to request the output conc of the chemical pool,
    # since there isn't an output message to deliver this value.
    moose.connect( adaptChan, 'requestOut', chemChan, 'getConc' )
    moose.connect( adaptChan, 'output', elecChan, 'setGbar' )
    adaptChan.inputOffset = 0.0    # 
    adaptChan.outputOffset = 0.0
    adaptChan.scale = 1e-5    #
Esempio n. 12
0
def make_prototype(passive=True):
    path = '%s/rc19' % (library.path)
    pfile = 'rc19.p'
    try:
        return moose.element(path)
    except ValueError:
        pass
    if not passive:
        make_na()
        make_kv()
        make_km()
        make_kca()
        make_cat()
        make_cahva()
        make_h()
    try:
        proto = moose.element(path)
    except ValueError:
        print('Loading model %s to %s' % (pfile, path))
        proto = moose.loadModel(pfile, path, 'ee') # hsolve is not functional yet
        for comp in proto[0].children:
            comp.initVm = -75e-3
        for chan in moose.wildcardFind('%s/##[ISA=HHChannel]'):
            chan.Gbar *= tadj
    return proto
Esempio n. 13
0
def make_Na():
	if moose.exists( 'Na' ):
		return
	Na = moose.HHChannel( 'Na' )
	Na.Ek = ENA				#	V
	Na.Gbar = 300 * SOMA_A	#	S
	Na.Gk = 0				#	S
	Na.Xpower = 2
	Na.Ypower = 1
	Na.Zpower = 0

	xgate = moose.element( 'Na/gateX' )
	xA = numpy.array( [ 320e3 * (0.0131 + EREST_ACT),
		-320e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.004, 
		-280e3 * (0.0401 + EREST_ACT), 280e3, -1.0, 
		-1.0 * (0.0401 + EREST_ACT), 5.0e-3, 
		3000, -0.1, 0.05 ] )
	xgate.alphaParms = xA


	#xgate.alpha( 320e3 * (0.0131 + EREST_ACT), -320e3, -1.0, -1.0 * (0.0131 + EREST_ACT), -0.004 )
	#xgate.beta( -280e3 * (0.0401 + EREST_ACT), 280e3, -1.0, -1.0 * (0.0401 + EREST_ACT), 5.0e-3 )

	ygate = moose.element( 'Na/gateY' )
	yA = numpy.array( [ 128.0, 0.0, 0.0, -1.0 * (0.017 + EREST_ACT), 0.018,
		4.0e3, 0.0, 1.0, -1.0 * (0.040 + EREST_ACT), -5.0e-3, 
		3000, -0.1, 0.05 ] )
	ygate.alphaParms = yA
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)
def deliverStim(currTime):
	global injectionCurrent	
	global spineVm
	global somaVm
	if numpy.fabs( currTime - baselineTime ) < frameRunTime/2.0 :
		#start
		eList = moose.wildcardFind( '/model/elec/#soma#' )
		assert( len(eList) > 0 )
		eList[0].inject = injectionCurrent
		#print "1. injected current = ", injectionCurrent
		injectionCurrent += deltaCurrent
		#print "del stim first ", moose.element('/clock').currentTime
	if numpy.fabs( currTime - baselineTime - currPulseTime) < frameRunTime/2.0 :
		#end
		eList = moose.wildcardFind( '/model/elec/#soma#' )
		assert( len(eList) > 0 )
		eList[0].inject = 0.0
		#print "2. injected current = ", injectionCurrent
		#print "del stim second ", moose.element('/clock').currentTime
	if runtime - currTime < frameRunTime * 2.0 :
		#print "3. reinit-ing"
		somaVm.append( moose.element( '/graphs/VmTab' ).vector )
		spineVm.append( moose.element( '/graphs/eSpineVmTab' ).vector )
		iList.append(injectionCurrent)
		if injectionCurrent < maxCurrent :
			moose.reinit()	
Esempio n. 16
0
def loadAndRun(solver=True):
    simtime = 500e-3
    model = moose.loadModel('../data/h10.CNG.swc', '/cell')
    comp = moose.element('/cell/apical_e_177_0')
    soma = moose.element('/cell/soma')
    for i in range(10):
        moose.setClock(i, dt)
    if solver:
        solver = moose.HSolve('/cell/solver')
        solver.target = soma.path
        solver.dt = dt
    stim = moose.PulseGen('/cell/stim')
    stim.delay[0] = 50e-3
    stim.delay[1] = 1e9
    stim.level[0] = 1e-9
    stim.width[0] = 2e-3    
    moose.connect(stim, 'output', comp, 'injectMsg')
    tab = moose.Table('/cell/Vm')
    moose.connect(tab, 'requestOut', comp, 'getVm')
    tab_soma = moose.Table('/cell/Vm_soma')
    moose.connect(tab_soma, 'requestOut', soma, 'getVm')
    moose.reinit()
    print('[INFO] Running for %s' % simtime)
    moose.start(simtime )
    vec = tab_soma.vector 
    moose.delete( '/cell' )
    return vec
Esempio n. 17
0
def main():
        """
        This example illustrates loading, and running a kinetic model 
        for a bistable positive feedback system, defined in kkit format. 
        This is based on Bhalla, Ram and Iyengar, Science 2002.

        The core of this model is a positive feedback loop comprising of
        the MAPK cascade, PLA2, and PKC. It receives PDGF and Ca2+ as 
        inputs.

        This model is quite a large one and due to some stiffness in its
        equations, it runs somewhat slowly. 

        The simulation illustrated here shows how the model starts out in
        a state of low activity. It is induced to 'turn on' when a 
        a PDGF stimulus is given for 400 seconds. 
        After it has settled to the new 'on' state, model is made to 
        'turn off'
        by setting the system calcium levels to zero for a while. This
        is a somewhat unphysiological manipulation!
        """
        solver = "gsl"  # Pick any of gsl, gssa, ee..
        #solver = "gssa"  # Pick any of gsl, gssa, ee..
	mfile = '../../genesis/acc35.g'
	runtime = 2000.0
	if ( len( sys.argv ) == 2 ):
                solver = sys.argv[1]
	modelId = moose.loadModel( mfile, 'model', solver )
        # Increase volume so that the stochastic solver gssa 
        # gives an interesting output
        compt = moose.element( '/model/kinetics' )
        compt.volume = 5e-19 

	moose.reinit()
	moose.start( 500 ) 
        moose.element( '/model/kinetics/PDGFR/PDGF' ).concInit = 0.0001
	moose.start( 400 ) 
        moose.element( '/model/kinetics/PDGFR/PDGF' ).concInit = 0.0
	moose.start( 2000 ) 
        moose.element( '/model/kinetics/Ca' ).concInit = 0.0
	moose.start( 500 ) 
        moose.element( '/model/kinetics/Ca' ).concInit = 0.00008
	moose.start( 2000 ) 

	# Display all plots.
        img = mpimg.imread( 'mapkFB.png' )
        fig = plt.figure( figsize=(12, 10 ) )
        png = fig.add_subplot( 211 )
        imgplot = plt.imshow( img )
        ax = fig.add_subplot( 212 )
	x = moose.wildcardFind( '/model/#graphs/conc#/#' )
        t = numpy.arange( 0, x[0].vector.size, 1 ) * x[0].dt
        ax.plot( t, x[0].vector, 'b-', label=x[0].name )
        ax.plot( t, x[1].vector, 'c-', label=x[1].name )
        ax.plot( t, x[2].vector, 'r-', label=x[2].name )
        ax.plot( t, x[3].vector, 'm-', label=x[3].name )
        plt.ylabel( 'Conc (mM)' )
        plt.xlabel( 'Time (seconds)' )
        pylab.legend()
        pylab.show()
Esempio n. 18
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()
Esempio n. 19
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
        """
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."""
    path = container.path
    # Contrast this with
    # comps = moose.vec(path+'/soma', size, 'Compartment')
    comps = [create_compartment(path+'/soma_%d' % (ii)) for ii in range(size)]
    spikegens = []
    synchans = []
    Em = EREST_ACT + 10.613e-3
    initVm_array = [EREST_ACT] * size
    Em_array = [Em] * size
    # initVm_array = np.random.normal(EREST_ACT, np.abs(EREST_ACT) * 0.1, size)
    # Em_array = np.random.normal(Em, np.abs(Em) * 0.1, size)
    for comp, initVm, Em in zip(comps, initVm_array, Em_array):
        comp.Em = Em
        comp.initVm = initVm
        synchan = moose.element(comp.path + '/synchan')
        synchans.append(synchan)
        spikegen = moose.element(comp.path + '/spikegen')
        spikegens.append(spikegen)

    return {'compartment': comps,
            'spikegen': spikegens,
            'synchan': synchans}
Esempio n. 21
0
def showVisualization():
    makeModel()
    elec = moose.element( '/model/elec' )
    elec.setSpineAndPsdMesh( moose.element('/model/chem/spine'), moose.element('/model/chem/psd') )

    eHead = moose.wildcardFind( '/model/elec/#head#' )
    oldDia = [ i.diameter for i in eHead ]
    graphs = moose.Neutral( '/graphs' )
    #makePlot( 'psd_x', moose.vec( '/model/chem/psd/x' ), 'getN' )
    #makePlot( 'head_x', moose.vec( '/model/chem/spine/x' ), 'getN' )
    makePlot( 'dend_x', moose.vec( '/model/chem/dend/x' ), 'getN' )
    dendZ = makePlot( 'dend_z', moose.vec( '/model/chem/dend/z' ), 'getN' )
    makePlot( 'head_z', moose.vec( '/model/chem/spine/z' ), 'getN' )
    psdZ = makePlot( 'psd_z', moose.vec( '/model/chem/psd/z' ), 'getN' )
    diaTab = makePlot( 'headDia', eHead, 'getDiameter' )
    # print diaTab[0].vector[-1]
    # return
    dendrite = moose.element("/model/elec/dend")
    dendrites = [dendrite.path + "/" + str(i) for i in range(len(dendZ))]
    # print dendrites
    moose.reinit()

    spineHeads = moose.wildcardFind( '/model/elec/#head#')
    # print moose.wildcardFind( '/model/elec/##')

    # print "dendZ", readValues(dendZ)
    # print dendrite

    app = QtGui.QApplication(sys.argv)
    viewer = create_viewer("/model/elec", dendrite, dendZ, diaTab, psdZ)
    viewer.showMaximized()
    viewer.start()
    return app.exec_()
Esempio n. 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)
Esempio n. 23
0
def spinetabs(model,neuron,comps='all'):
    if not moose.exists(DATA_NAME):
        moose.Neutral(DATA_NAME)
    #creates tables of calcium and vm for spines
    spcatab = defaultdict(list)
    spvmtab = defaultdict(list)
    for typenum,neurtype in enumerate(neuron.keys()):
        if type(comps)==str and comps in {'*', 'all'}:
            spineHeads=[moose.wildcardFind(neurtype+'/##/#head#[ISA=CompartmentBase]')]
        else:
            spineHeads=[moose.wildcardFind(neurtype+'/'+c+'/#head#[ISA=CompartmentBase]') for c in comps]
        for spinelist in spineHeads:
            for spinenum,spine in enumerate(spinelist):
                compname = spine.parent.name
                sp_num=spine.name.split(NAME_HEAD)[0]
                spvmtab[typenum].append(moose.Table(vm_table_path(neurtype, spine=sp_num, comp=compname)))
                log.debug('{} {} {}',spinenum, spine.path, spvmtab[typenum][-1].path)
                moose.connect(spvmtab[typenum][-1], 'requestOut', spine, 'getVm')
                if model.calYN:
                    for child in spine.children:
                        if child.className == "CaConc" or  child.className == "ZombieCaConc" :
                            spcatab[typenum].append(moose.Table(DATA_NAME+'/%s_%s%s'% (neurtype,sp_num,compname)+child.name))
                            spcal = moose.element(spine.path+'/'+child.name)
                            moose.connect(spcatab[typenum][-1], 'requestOut', spcal, 'getCa')
                        elif child.className == 'DifShell':
                            spcatab[typenum].append(moose.Table(DATA_NAME+'/%s_%s%s'% (neurtype,sp_num,compname)+child.name))
                            spcal = moose.element(spine.path+'/'+child.name)
                            moose.connect(spcatab[typenum][-1], 'requestOut', spcal, 'getC')
    return spcatab,spvmtab
Esempio n. 24
0
def dumpPlots( fname ):
    if ( os.path.exists( fname ) ):
        os.remove( fname )
    for x in moose.wildcardFind( '/graphs/#[ISA=Table]' ):
        moose.element( x[0] ).xplot( fname, x[0].name )
    for x in moose.wildcardFind( '/graphs/elec/#[ISA=Table]' ):
        moose.element( x[0] ).xplot( fname, x[0].name + '_e' )
Esempio n. 25
0
def setup_hdf5_output(model, neuron, filename=None, compartments=DEFAULT_HDF5_COMPARTMENTS):
    # Make sure /hdf5 exists
    if not moose.exists(HDF5WRITER_NAME):
        print('creating', HDF5WRITER_NAME)
        writer = moose.HDF5DataWriter(HDF5WRITER_NAME)
        #writer = moose.NSDFWriter(HDF5WRITER_NAME)
        writer.mode = 2 # Truncate existing file
        if filename is not None:
            writer.filename = filename
        moose.useClock(8, HDF5WRITER_NAME, 'process')
    else:
        print('using', HDF5WRITER_NAME)
        writer = moose.element(HDF5WRITER_NAME)

    for typenum,neur_type in enumerate(neuron.keys()):
        for ii,compname in enumerate(compartments):  #neur_comps):
            comp=moose.element(neur_type+'/'+compname)
            moose.connect(writer, 'requestOut', comp, 'getVm')

    if model.calYN:
        for typenum,neur_type in enumerate(neuron.keys()):
            for ii,compname in enumerate(compartments):  #neur_comps):
                comp=moose.element(neur_type+'/'+compname)
                for child in comp.children:
                    if child.className in {"CaConc", "ZombieCaConc"}:
                        cal = moose.element(comp.path+'/'+child.name)
                        moose.connect(writer, 'requestOut', cal, 'getCa')
                    elif  child.className == 'DifShell':
                        cal = moose.element(comp.path+'/'+child.name)
                        moose.connect(writer, 'requestOut', cal, 'getC')
    return writer
Esempio n. 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()
Esempio n. 27
0
    def installCellFromProtos( self ):
        if self.stealCellFromLibrary:
            moose.move( self.elecid, self.model )
            if self.elecid.name != 'elec':
                self.elecid.name = 'elec'
        else:
            moose.copy( self.elecid, self.model, 'elec' )
            self.elecid = moose.element( self.model.path + '/elec' )
            self.elecid.buildSegmentTree() # rebuild: copy has happened.
        if hasattr( self, 'chemid' ):
            self.validateChem()
            if self.stealCellFromLibrary:
                moose.move( self.chemid, self.model )
                if self.chemid.name != 'chem':
                    self.chemid.name = 'chem'
            else:
                moose.copy( self.chemid, self.model, 'chem' )
                self.chemid = moose.element( self.model.path + '/chem' )

        ep = self.elecid.path
        somaList = moose.wildcardFind( ep + '/#oma#[ISA=CompartmentBase]' )
        if len( somaList ) == 0:
            somaList = moose.wildcardFind( ep + '/#[ISA=CompartmentBase]' )
        if len( somaList ) == 0:
            raise BuildError( "installCellFromProto: No soma found" )
        maxdia = 0.0
        for i in somaList:
            if ( i.diameter > maxdia ):
                self.soma = i
Esempio n. 28
0
def storePlotMsgs( tgraphs,f):
        s = ""
        if tgraphs:
                for graph in tgraphs:
                        slash = graph.path.find('graphs')
                        if not slash > -1:
                                slash = graph.path.find('graph_0')
                        if slash > -1:
                                conc = graph.path.find('conc')
                                if conc > -1 :
                                        tabPath = graph.path[slash:len(graph.path)]
                                else:
                                        slash1 = graph.path.find('/',slash)
                                        tabPath = "/graphs/conc1" +graph.path[slash1:len(graph.path)]

                                if len(element(graph).msgOut):
                                        poolPath = (element(graph).msgOut)[0].e2.path
                                        poolEle = element(poolPath)
                                        poolName = poolEle.name
                                        bgPath = (poolEle.path+'/info')
                                        bg = Annotator(bgPath).color
                                        bg = getColorCheck(bg,GENESIS_COLOR_SEQUENCE)
                                        tabPath = re.sub("\[[0-9]+\]", "", tabPath)
                                        s = s+"addmsg /kinetics/" + trimPath( poolEle ) + " " + tabPath + \
                                                " PLOT Co *" + poolName + " *" + bg +"\n";
        f.write(s)
Esempio n. 29
0
 def getChannels(self, root='/library'):
     if isinstance(root, str):
         root = moose.element(root)
     for chan in moose.wildcardFind('%s/#[ISA=HHChannel]' % (root.path)):
         channel = moose.element(chan)
         self.channels[channel.name] = channel
     return self.channels
def create_compartment(path):
    comp = moose.Compartment(path)
    comp.diameter = soma_dia
    comp.Em = EREST_ACT + 10.613e-3
    comp.initVm = EREST_ACT
    sarea = np.pi * soma_dia * soma_dia
    comp.Rm = 1/(0.3e-3 * 1e4 * sarea)
    comp.Cm = 1e-6 * 1e4 * sarea
    if moose.exists('/library/na'):
        nachan = moose.element(moose.copy('/library/na', comp, 'na'))
    else:
        nachan = create_na_chan(comp.path)
    nachan.Gbar = 120e-3 * sarea * 1e4
    moose.showfield(nachan)
    moose.connect(nachan, 'channel', comp, 'channel')
    if moose.exists('/library/k'):
        kchan = moose.element(moose.copy('/library/k', comp, 'k'))
    else:
        kchan = create_k_chan(comp.path)
    kchan.Gbar = 36e-3 * sarea * 1e4
    moose.connect(kchan, 'channel', comp, 'channel')
    synchan = moose.SynChan(comp.path + '/synchan')
    synchan.Gbar = 1e-8
    synchan.tau1 = 2e-3
    synchan.tau2 = 2e-3
    synchan.Ek = 0.0
    m = moose.connect(comp, 'channel', synchan, 'channel')
    spikegen = moose.SpikeGen(comp.path + '/spikegen')
    spikegen.threshold = 0.0
    m = moose.connect(comp, 'VmOut', spikegen, 'Vm')
    return comp
def makeYmodel():
    length = rec[0].geom
    dia = rec[3].geom
    segLen = length / numDendSeg
    cp = [['make_glu()', 'glu'], ['make_GABA()', 'GABA']]
    cp.extend(spikingProto)
    cd = [['glu', 'dend9', 'Gbar', str(rec[0].Gbar)],
          ['glu', 'branch1_9', 'Gbar',
           str(rec[1].Gbar)], ['glu', 'branch2_9', 'Gbar',
                               str(rec[2].Gbar)],
          ['GABA', 'dend9', 'Gbar', str(rec[3].Gbar)],
          ['GABA', 'branch1_9', 'Gbar',
           str(rec[4].Gbar)], ['GABA', 'branch2_9', 'Gbar',
                               str(rec[5].Gbar)]]
    cd.extend(spikingDistrib)

    rdes = rd.rdesigneur(
        elecPlotDt=elecPlotDt,
        stealCellFromLibrary=True,
        verbose=False,
        #chanProto = [['make_glu()', 'glu'],['make_GABA()', 'GABA']],
        chanProto=cp,
        # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSegments ]
        # The numerical arguments are all optional
        cellProto=[[
            'ballAndStick', 'cellBase', dia, segLen, dia, length, numDendSeg
        ]],
        passiveDistrib=[['#', 'RM',
                         str(RM), 'CM',
                         str(CM), 'RA',
                         str(RA)]],
        chanDistrib=cd,
        #chanDistrib = [
        #['glu', 'dend9', 'Gbar', str(rec[0].Gbar)],
        #['glu', 'branch1_9', 'Gbar', str(rec[1].Gbar)],
        #['glu', 'branch2_9', 'Gbar', str(rec[2].Gbar)],
        #['GABA', 'dend9', 'Gbar', str(rec[3].Gbar)],
        #['GABA', 'branch1_9', 'Gbar', str(rec[4].Gbar)],
        #['GABA', 'branch2_9', 'Gbar', str(rec[5].Gbar)],
        #],
        stimList=[
            [
                'dend9', '1', 'glu', 'periodicsyn',
                '{}*(t>{:.3f} && t<{:.3f})'.format(
                    rec[0].inputFreq, rec[0].onset,
                    rec[0].onset + rec[0].inputDuration)
            ],
            [
                'branch1_9', '1', 'glu', 'periodicsyn',
                '{}*(t>{:.3f} && t<{:.3f})'.format(
                    rec[1].inputFreq, rec[1].onset,
                    rec[1].onset + rec[1].inputDuration)
            ],
            [
                'branch2_9', '1', 'glu', 'periodicsyn',
                '{}*(t>{:.3f} && t<{:.3f})'.format(
                    rec[2].inputFreq, rec[2].onset,
                    rec[2].onset + rec[2].inputDuration)
            ],
            [
                'dend9', '1', 'GABA', 'periodicsyn',
                '{}*(t>{:.3f} && t<{:.3f})'.format(
                    rec[3].inputFreq, rec[3].onset,
                    rec[3].onset + rec[3].inputDuration)
            ],
            [
                'branch1_9', '1', 'GABA', 'periodicsyn',
                '{}*(t>{:.3f} && t<{:.3f})'.format(
                    rec[4].inputFreq, rec[4].onset,
                    rec[4].onset + rec[4].inputDuration)
            ],
            [
                'branch2_9', '1', 'GABA', 'periodicsyn',
                '{}*(t>{:.3f} && t<{:.3f})'.format(
                    rec[5].inputFreq, rec[5].onset,
                    rec[5].onset + rec[5].inputDuration)
            ],
            #['dend9,branch1_9,branch2_9', '1','glu', 'periodicsyn', '100*(t>0.01 && t<0.02)'],
        ],
        plotList=[
            ['soma,dend9,branch1_9,branch2_9', '1', '.', 'Vm'],
        ],
    )
    # Modify some library values based on the slider controls
    glu = moose.element('/library/glu')
    gaba = moose.element('/library/GABA')
    glu.tau1 = rec[0].tau1
    glu.tau2 = rec[1].tau2
    glu.Ek = rec[2].Ek
    gaba.tau1 = rec[3].tau1
    gaba.tau2 = rec[4].tau2
    gaba.Ek = rec[5].Ek
    # Build the arms of the Y for a branching cell.
    pa = moose.element('/library/cellBase')
    x1 = length
    x2 = length
    y1 = 0.0
    y2 = 0.0
    dx1 = rec[1].geom / (numDendSeg * np.sqrt(2.0))
    dx2 = rec[2].geom / (numDendSeg * np.sqrt(2.0))
    dia1 = rec[4].geom
    dia2 = rec[5].geom
    dy1 = dx1
    dy2 = -dx2
    prevc1 = moose.element('/library/cellBase/dend{}'.format(numDendSeg - 1))
    prevc2 = prevc1
    for i in range(numDendSeg):
        c1 = rd.buildCompt(pa,
                           'branch1_{}'.format(i),
                           RM=RM,
                           CM=CM,
                           RA=RA,
                           dia=dia1,
                           x=x1,
                           y=y1,
                           dx=dx1,
                           dy=dy1)
        c2 = rd.buildCompt(pa,
                           'branch2_{}'.format(i),
                           RM=RM,
                           CM=CM,
                           RA=RA,
                           dia=dia2,
                           x=x2,
                           y=y2,
                           dx=dx2,
                           dy=dy2)
        moose.connect(prevc1, 'axial', c1, 'raxial')
        moose.connect(prevc2, 'axial', c2, 'raxial')
        prevc1 = c1
        prevc2 = c2
        x1 += dx1
        y1 += dy1
        x2 += dx2
        y2 += dy2
    rdes.elecid.buildSegmentTree()  # rebuild it as we've added the branches

    rdes.buildModel()
    # Permit fast spiking input.
    #for i in moose.wildcardFind( '/model/##[ISA=RandSpike]' ):
    for i in moose.wildcardFind('/model/elec/#/#/#/#/synInput_rs'):
        #print i.path, i.refractT
        i.refractT = 0.002
    '''
def main():
    """
    The stochasticLotkaVolterra example is almost identical to the 
    funcReacLotkaVolterra. It shows how to use function objects
    as part of differential equation systems in the framework of the MOOSE
    kinetic solvers. Here the difference is that we use a a stochastic
    solver. The system is interesting because it illustrates the 
    instability of Lotka-Volterra systems in stochastic conditions. Here we
    see exctinction of one of the species and runaway buildup of the other.
    The simulation has to be halted at this point.
    
    Here the system is set up explicitly using the 
    scripting, in normal use one would expect to use SBML.
    
    In this example we set up a Lotka-Volterra system. The equations
    are readily expressed as a pair of reactions each of whose rate is
    governed by a function::
    
            x' = x( alpha - beta.y )
            y' = -y( gamma - delta.x )
    
    This translates into two reactions::
    
            x ---> z        Kf = beta.y - alpha
            y ---> z        Kf = gamma - delta.x
            
    Here z is a dummy molecule whose concentration is buffered to zero.
    
    The model first runs using default Exponential Euler integration.
    This is not particularly accurate even with a small timestep.
    The model is then converted to use the deterministic Kinetic solver
    Ksolve. This is accurate and faster.
    Note that we cannot use the stochastic GSSA solver for this system, it
    cannot handle a reaction term whose rate keeps changing.
    """
    makeModel()

    moose.seed(1)
    # A seed of 3 will give an extinction at 79 seconds.

    for i in range(11, 18):
        moose.setClock(i, 0.001)
    moose.setClock(18, 0.1)
    moose.reinit()
    moose.start(runtime)  # Run the model

    # Iterate through all plots, dump their contents to data.plot.
    for x in moose.wildcardFind('/model/graphs/#'):
        #x.xplot( 'scriptKineticModel.plot', x.name )
        t = numpy.arange(0, x.vector.size, 1) * x.dt  # sec
        pylab.plot(t, x.vector, label=x.name)
    #pylab.ylim( 0, 2.5 )
    pylab.title("Exponential Euler solution. Note slight error buildup")
    pylab.legend()

    pylab.figure()
    compt = moose.element('/model/lotka')
    ksolve = moose.Gsolve('/model/lotka/ksolve')
    stoich = moose.Stoich('/model/lotka/stoich')
    stoich.compartment = compt
    stoich.ksolve = ksolve
    stoich.path = '/model/lotka/##'
    moose.reinit()
    moose.start(runtime)  # Run the model

    for i in range(11, 18):
        moose.setClock(i, 0.1)
    for x in moose.wildcardFind('/model/graphs/#'):
        t = numpy.arange(0, x.vector.size, 1) * x.dt  # sec
        pylab.plot(t, x.vector, label=x.name)
    #pylab.ylim( 0, 2.5 )
    pylab.title("GSSA solution.")
    pylab.legend()
    pylab.show()

    quit()
Esempio n. 33
0
def makeNeuroMeshModel():
    diffLength = 6e-6  # Aim for 2 soma compartments.
    elec = loadElec()
    loadChem(diffLength)
    neuroCompt = moose.element('/model/chem/dend')
    neuroCompt.diffLength = diffLength
    neuroCompt.cellPortion(elec, '/model/elec/#')
    for x in moose.wildcardFind('/model/chem/##[ISA=PoolBase]'):
        if (x.diffConst > 0):
            x.diffConst = 1e-11
    for x in moose.wildcardFind('/model/chem/##/Ca'):
        x.diffConst = 1e-10

    # Put in dend solvers
    ns = neuroCompt.numSegments
    ndc = neuroCompt.numDiffCompts
    print(('ns = ', ns, ', ndc = ', ndc))
    assert (neuroCompt.numDiffCompts == neuroCompt.mesh.num)
    assert (ns == 1)  # soma/dend only
    assert (ndc == 2)  # split into 2.
    nmksolve = moose.Ksolve('/model/chem/dend/ksolve')
    nmdsolve = moose.Dsolve('/model/chem/dend/dsolve')
    nmstoich = moose.Stoich('/model/chem/dend/stoich')
    nmstoich.compartment = neuroCompt
    nmstoich.ksolve = nmksolve
    nmstoich.dsolve = nmdsolve
    nmstoich.path = "/model/chem/dend/##"
    print(('done setting path, numPools = ', nmdsolve.numPools))
    assert (nmdsolve.numPools == 1)
    assert (nmdsolve.numAllVoxels == 2)
    assert (nmstoich.numAllPools == 1)
    # oddly, numLocalFields does not work.
    ca = moose.element('/model/chem/dend/DEND/Ca')
    assert (ca.numData == ndc)

    # Put in spine solvers. Note that these get info from the neuroCompt
    spineCompt = moose.element('/model/chem/spine')
    sdc = spineCompt.mesh.num
    print(('sdc = ', sdc))
    assert (sdc == 1)
    smksolve = moose.Ksolve('/model/chem/spine/ksolve')
    smdsolve = moose.Dsolve('/model/chem/spine/dsolve')
    smstoich = moose.Stoich('/model/chem/spine/stoich')
    smstoich.compartment = spineCompt
    smstoich.ksolve = smksolve
    smstoich.dsolve = smdsolve
    smstoich.path = "/model/chem/spine/##"
    assert (smstoich.numAllPools == 3)
    assert (smdsolve.numPools == 3)
    assert (smdsolve.numAllVoxels == 1)

    # Put in PSD solvers. Note that these get info from the neuroCompt
    psdCompt = moose.element('/model/chem/psd')
    pdc = psdCompt.mesh.num
    assert (pdc == 1)
    pmksolve = moose.Ksolve('/model/chem/psd/ksolve')
    pmdsolve = moose.Dsolve('/model/chem/psd/dsolve')
    pmstoich = moose.Stoich('/model/chem/psd/stoich')
    pmstoich.compartment = psdCompt
    pmstoich.ksolve = pmksolve
    pmstoich.dsolve = pmdsolve
    pmstoich.path = "/model/chem/psd/##"
    assert (pmstoich.numAllPools == 3)
    assert (pmdsolve.numPools == 3)
    assert (pmdsolve.numAllVoxels == 1)
    foo = moose.element('/model/chem/psd/Ca')
    print(('PSD: numfoo = ', foo.numData))
    print(('PSD: numAllVoxels = ', pmksolve.numAllVoxels))

    # Put in junctions between the diffusion solvers
    nmdsolve.buildNeuroMeshJunctions(smdsolve, pmdsolve)

    # set up adaptors
    aCa = moose.Adaptor('/model/chem/dend/DEND/adaptCa', ndc)
    adaptCa = moose.vec('/model/chem/dend/DEND/adaptCa')
    chemCa = moose.vec('/model/chem/dend/DEND/Ca')
    print(('aCa = ', aCa, ' foo = ', foo, "len( ChemCa ) = ", len(chemCa),
           ", numData = ", chemCa.numData, "len( adaptCa ) = ", len(adaptCa)))
    assert (len(adaptCa) == ndc)
    assert (len(chemCa) == ndc)
    path = '/model/elec/soma/Ca_conc'
    elecCa = moose.element(path)
    print("==========")
    print(elecCa)
    print(adaptCa)
    print(chemCa)
    moose.connect(elecCa, 'concOut', adaptCa[0], 'input', 'Single')
    moose.connect(adaptCa, 'output', chemCa, 'setConc', 'OneToOne')
    adaptCa.inputOffset = 0.0  #
    adaptCa.outputOffset = 0.00008  # 80 nM offset in chem.
    adaptCa.scale = 1e-3  # 520 to 0.0052 mM
Esempio n. 34
0
def testNeuroMeshMultiscale():
    elecDt = 50e-6
    chemDt = 0.01
    ePlotDt = 0.5e-3
    cPlotDt = 0.01
    plotName = 'nm.plot'

    makeNeuroMeshModel()
    print("after model is completely done")
    for i in moose.wildcardFind('/model/chem/#/#/#/transloc#'):
        print((i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb))
    """
    for i in moose.wildcardFind( '/model/chem/##[ISA=PoolBase]' ):
        if ( i[0].diffConst > 0 ):
            grandpaname = i.parent[0].parent.name + '/'
            paname = i.parent[0].name + '/'
            print grandpaname + paname + i[0].name, i[0].diffConst
    print 'Neighbors:'
    for t in moose.element( '/model/chem/spine/ksolve/junction' ).neighbors['masterJunction']:
        print 'masterJunction <-', t.path
    for t in moose.wildcardFind( '/model/chem/#/ksolve' ):
        k = moose.element( t[0] )
        print k.path + ' localVoxels=', k.numLocalVoxels, ', allVoxels= ', k.numAllVoxels
    """
    '''
    moose.useClock( 4, '/model/chem/dend/dsolve', 'process' )
    moose.useClock( 5, '/model/chem/dend/ksolve', 'process' )
    moose.useClock( 5, '/model/chem/spine/ksolve', 'process' )
    moose.useClock( 5, '/model/chem/psd/ksolve', 'process' )
    '''

    makeChemPlots()
    makeElecPlots()
    moose.setClock(0, elecDt)
    moose.setClock(1, elecDt)
    moose.setClock(2, elecDt)
    moose.setClock(4, chemDt)
    moose.setClock(5, chemDt)
    moose.setClock(6, chemDt)
    moose.setClock(7, cPlotDt)
    moose.setClock(8, ePlotDt)
    moose.useClock(0, '/model/elec/##[ISA=Compartment]', 'init')
    moose.useClock(1, '/model/elec/##[ISA=Compartment]', 'process')
    moose.useClock(1, '/model/elec/##[ISA=SpikeGen]', 'process')
    moose.useClock(
        2,
        '/model/elec/##[ISA=ChanBase],/model/##[ISA=SynBase],/model/##[ISA=CaConc]',
        'process')
    #moose.useClock( 5, '/model/chem/##[ISA=PoolBase],/model/##[ISA=ReacBase],/model/##[ISA=EnzBase]', 'process' )
    #moose.useClock( 4, '/model/chem/##[ISA=Adaptor]', 'process' )
    moose.useClock(4, '/model/chem/#/dsolve', 'process')
    moose.useClock(5, '/model/chem/#/ksolve', 'process')
    moose.useClock(6, '/model/chem/dend/DEND/adaptCa', 'process')
    moose.useClock(7, '/graphs/chem/#', 'process')
    moose.useClock(8, '/graphs/elec/#', 'process')
    #hsolve = moose.HSolve( '/model/elec/hsolve' )
    #moose.useClock( 1, '/model/elec/hsolve', 'process' )
    #hsolve.dt = elecDt
    #hsolve.target = '/model/elec/compt'
    #moose.reinit()
    moose.element('/model/elec/spine_head').inject = 5e-12
    moose.element('/model/chem/psd/Ca').concInit = 0.001
    moose.element('/model/chem/spine/Ca').concInit = 0.002
    moose.element('/model/chem/dend/DEND/Ca').concInit = 0.003
    moose.reinit()
    """
    print 'pre'
    eca = moose.vec( '/model/chem/psd/PSD/CaM/Ca' )
    for i in range( 3 ):
        print eca[i].concInit, eca[i].conc, eca[i].nInit, eca[i].n, eca[i].volume
    print 'dend'
    eca = moose.vec( '/model/chem/dend/DEND/Ca' )
    #for i in ( 0, 1, 2, 30, 60, 90, 120, 144 ):
    for i in range( 13 ):
        print i, eca[i].concInit, eca[i].conc, eca[i].nInit, eca[i].n, eca[i].volume

    print 'PSD'
    eca = moose.vec( '/model/chem/psd/PSD/CaM/Ca' )
    for i in range( 3 ):
        print eca[i].concInit, eca[i].conc, eca[i].nInit, eca[i].n, eca[i].volume
    print 'spine'
    eca = moose.vec( '/model/chem/spine/SPINE/CaM/Ca' )
    for i in range( 3 ):
        print eca[i].concInit, eca[i].conc, eca[i].nInit, eca[i].n, eca[i].volume
    """

    moose.start(0.5)
    plt.ion()
    fig = plt.figure(figsize=(8, 8))
    chem = fig.add_subplot(211)
    chem.set_ylim(0, 0.004)
    plt.ylabel('Conc (mM)')
    plt.xlabel('time (seconds)')
    for x in moose.wildcardFind('/graphs/chem/#[ISA=Table]'):
        pos = numpy.arange(0, x.vector.size, 1) * cPlotDt
        line1, = chem.plot(pos, x.vector, label=x.name)
    plt.legend()

    elec = fig.add_subplot(212)
    plt.ylabel('Vm (V)')
    plt.xlabel('time (seconds)')
    for x in moose.wildcardFind('/graphs/elec/#[ISA=Table]'):
        pos = numpy.arange(0, x.vector.size, 1) * ePlotDt
        line1, = elec.plot(pos, x.vector, label=x.name)
    plt.legend()
    fig.canvas.draw()
    eval(input())
    pylab.show()
    print('All done')
Esempio n. 35
0
    def connect(self, syn_name, pre_path, post_path, weight, threshold, delay):
        postcomp = moose.element(post_path)
        ## We usually try to reuse an existing SynChan & SynHandler -
        ## event based SynHandlers have an array of weights and delays and can represent multiple synapses,
        ## so a new element of the weights and delays array is created
        ## every time a 'synapse' message connects to the SynHandler (from 'event' of spikegen)
        ## BUT for a graded synapse with a lookup table output connected to 'activation' message,
        ## not to 'synapse' message, we make a new synapse everytime
        ## ALSO for a saturating synapse i.e. KinSynChan, we always make a new synapse
        ## as KinSynChan is not meant to represent multiple synapses
        libsyn = moose.SynChan('/library/' + syn_name)
        gradedchild = utils.get_child_Mstring(libsyn, 'graded')
        if libsyn.className == 'KinSynChan' or gradedchild.value == 'True':  # create a new synapse
            syn_name_full = syn_name + '_' + utils.underscorize(pre_path)
            make_new_synapse(syn_name, postcomp, syn_name_full,
                             self.nml_params)
        else:
            ## if syn doesn't exist in this compartment, create it
            syn_name_full = syn_name
            if not moose.exists(post_path + '/' + syn_name_full):
                make_new_synapse(syn_name, postcomp, syn_name_full,
                                 self.nml_params)
        ## moose.element is a function that checks if path exists,
        ## and returns the correct object, here SynChan
        syn = moose.element(
            post_path + '/' +
            syn_name_full)  # wrap the SynChan in this compartment
        synhandler = moose.element(post_path + '/' + syn_name_full +
                                   '/handler')  # wrap the SynHandler
        gradedchild = utils.get_child_Mstring(syn, 'graded')
        #### weights are set at the end according to whether the synapse is graded or event-based

        #### If graded, connect pre-comp Vm to the table which is connected to SynChan's activation
        #### If event-based, connect spikegen/timetable's spikeOut to Simple/STDP SynHandler's addSpike
        ## I rely on second term below not being evaluated if first term is None;
        ## otherwise None.value gives error.
        if gradedchild is not None and gradedchild.value == 'True':  # graded synapse
            interpol = moose.element(syn.path + "/graded_table")
            #### always connect source to input - else 'cannot create message' error.
            precomp = moose.element(pre_path)
            moose.connect(precomp, "VmOut", interpol, "input")
            try:
                tau_table = moose.element(syn.path + '/tau_table')
                tau_table_present = True
            except ValueError:
                tau_table_present = False
            # if tau_table is not found, don't connect it
            if tau_table_present:
                moose.connect(precomp, 'VmOut', tau_table, 'input')
            ## since there is no weight field for a graded synapse
            ## (no 'synapse' message connected),
            ## I set the Gbar to weight*Gbar
            syn.Gbar = weight * syn.Gbar
        else:  # Event based synapse
            ## synapse could be connected to either spikegen at pre-compartment OR to a file!
            if 'file' not in pre_path:
                ## element() can return either Compartment() or IzhikevichNrn(),
                ## since it queries and wraps the actual object
                precomp = moose.element(pre_path)
                ## if spikegen for this synapse doesn't exist in this compartment, create it
                ## spikegens for different synapse_types can have different thresholds
                ## but an integrate and fire spikegen supercedes all other spikegens
                if 'IF' in precomp.className:  # intfire LIF
                    spikegen = precomp  # LIF has a spikeOut message
                else:
                    if not moose.exists(pre_path + '/' + syn_name +
                                        '_spikegen'):
                        ## create new spikegen
                        spikegen = moose.element(pre_path + '/' + syn_name +
                                                 '_spikegen')
                        ## connect the compartment Vm to the spikegen
                        moose.connect(precomp, "VmOut", spikegen, "Vm")
                        ## spikegens for different synapse_types can have different thresholds
                        spikegen.threshold = threshold
                        spikegen.edgeTriggered = 1  # This ensures that spike is generated only on leading edge.
                        ## usually events are raised at every time step that Vm > Threshold,
                        ## can set either edgeTriggered as above or refractT
                        #spikegen.refractT = 0.25e-3
                    ## wrap the existing or newly created spikegen in this compartment
                    spikegen = moose.SpikeGen(pre_path + '/' + syn_name +
                                              '_spikegen')
                ## connect the spikegen to the SynHandler
                ## note that you need to use Synapse (auto-created) under SynHandler
                ## to get/set weights , addSpike-s etc.
                ## wrap Synapse element by moose.Synapse(synhandler.path+'/synapse') or synhandler.synapse
                ## Synpase is an array element, first add to it, to addSpike-s, get/set weights, etc.
                synhandler.numSynapses += 1
                ## see Demos/snippets/synapse.py for an example of
                ## how to connect multiple SpikeGens to the same SynChan
                m = moose.connect(spikegen, 'spikeOut', synhandler.synapse[-1],
                                  'addSpike', 'Single')
            else:
                ## if connected to a file, create a timetable,
                ## put in a field specifying the connected filenumbers to this segment,
                ## and leave it for simulation-time connection
                ## pre_path is 'file[+<glomnum>]_<filenum1>[_<filenum2>...]' i.e. glomnum could be present
                ## hack for my (Aditya's) OB model to use files in NeuroML, should not affect others
                filesplit = pre_path.split('+')
                if len(filesplit) == 2:
                    glomsplit = filesplit[1].split('_', 1)
                    glomstr = '_' + glomsplit[0]
                    filenums = glomsplit[1]
                else:
                    glomstr = ''
                    filenums = pre_path.split('_', 1)[1]
                tt_path = postcomp.path + '/' + syn_name_full + glomstr + '_tt'
                if not moose.exists(tt_path):
                    ## if timetable for this synapse doesn't exist in this compartment, create it,
                    ## and add the field 'fileNumbers'
                    tt = moose.TimeTable(tt_path)
                    tt_filenums = moose.Mstring(tt_path + '/fileNumbers')
                    tt_filenums.value = filenums
                    ## Be careful to connect the timetable only once while creating it as below:
                    ## note that you need to use Synapse (auto-created) under SynChan
                    ## to get/set weights , addSpike-s etc.
                    ## wrap Synapse element by moose.Synapse(synhandler.path+'/synapse') or synhandler.synapse
                    ## Synpase is an array element, first add to it, to addSpike-s, get/set weights, etc.
                    synhandler.numSynapses += 1
                    m = moose.connect(tt, "eventOut", synhandler.synapse[-1],
                                      "addSpike", "Single")
                else:
                    ## if it exists, append file number to the field 'fileNumbers'
                    ## append filenumbers from 'file[+<glomnum>]_<filenumber1>[_<filenumber2>...]'
                    tt_filenums = moose.Mstring(tt_path + '/fileNumbers')
                    tt_filenums.value += '_' + filenums
            #### syn.Gbar remains the same, but we play with the weight which is a factor to Gbar
            #### The delay and weight can be set only after connecting a spike event generator.
            #### delay and weight are arrays: multiple event messages can be connected to a single synapse
            ## first argument below is the array index, we connect to the latest synapse created above
            ## But KinSynChan ignores weight of the synapse, so set the Gbar for it
            if libsyn.className == 'KinSynChan':
                syn.Gbar = weight * syn.Gbar
            else:
                ## note that you need to use Synapse (auto-created) under SynHandler
                ## to get/set weights , addSpike-s etc.
                ## wrap Synpase element by moose.Synapse(synhandler.path+'/synapse') or synhandler.synapse
                synhandler.synapse[-1].weight = weight
            synhandler.synapse[-1].delay = delay  # seconds
Esempio n. 36
0
def makeNeuroMeshModel():
    diffLength = 10e-6  # Aim for 2 soma compartments.
    elec = loadElec()
    loadChem(diffLength)
    neuroCompt = moose.element('/model/chem/dend')
    neuroCompt.diffLength = diffLength
    neuroCompt.cellPortion(elec, '/model/elec/#')
    for x in moose.wildcardFind('/model/chem/##[ISA=PoolBase]'):
        if (x.diffConst > 0):
            x.diffConst = 1e-11
    for x in moose.wildcardFind('/model/chem/##/Ca'):
        x.diffConst = 1e-10

    # Put in dend solvers
    ns = neuroCompt.numSegments
    ndc = neuroCompt.numDiffCompts
    print 'ns = ', ns, ', ndc = ', ndc
    assert (neuroCompt.numDiffCompts == neuroCompt.mesh.num)
    assert (ns == 36)  #
    assert (ndc == 278)  #
    nmksolve = moose.Ksolve('/model/chem/dend/ksolve')
    nmdsolve = moose.Dsolve('/model/chem/dend/dsolve')
    nmstoich = moose.Stoich('/model/chem/dend/stoich')
    nmstoich.compartment = neuroCompt
    nmstoich.ksolve = nmksolve
    nmstoich.dsolve = nmdsolve
    nmstoich.path = "/model/chem/dend/##"
    print 'done setting path, numPools = ', nmdsolve.numPools
    assert (nmdsolve.numPools == 1)
    assert (nmdsolve.numAllVoxels == ndc)
    assert (nmstoich.numAllPools == 1)
    # oddly, numLocalFields does not work.
    ca = moose.element('/model/chem/dend/DEND/Ca')
    assert (ca.numData == ndc)

    # Put in spine solvers. Note that these get info from the neuroCompt
    spineCompt = moose.element('/model/chem/spine')
    sdc = spineCompt.mesh.num
    print 'sdc = ', sdc
    assert (sdc == 13)
    smksolve = moose.Ksolve('/model/chem/spine/ksolve')
    smdsolve = moose.Dsolve('/model/chem/spine/dsolve')
    smstoich = moose.Stoich('/model/chem/spine/stoich')
    smstoich.compartment = spineCompt
    smstoich.ksolve = smksolve
    smstoich.dsolve = smdsolve
    smstoich.path = "/model/chem/spine/##"
    print('spine num Pools = ', smstoich.numAllPools)
    assert (smstoich.numAllPools == 3)
    assert (smdsolve.numPools == 3)
    assert (smdsolve.numAllVoxels == sdc)

    # Put in PSD solvers. Note that these get info from the neuroCompt
    psdCompt = moose.element('/model/chem/psd')
    pdc = psdCompt.mesh.num
    assert (pdc == 13)
    pmksolve = moose.Ksolve('/model/chem/psd/ksolve')
    pmdsolve = moose.Dsolve('/model/chem/psd/dsolve')
    pmstoich = moose.Stoich('/model/chem/psd/stoich')
    pmstoich.compartment = psdCompt
    pmstoich.ksolve = pmksolve
    pmstoich.dsolve = pmdsolve
    pmstoich.path = "/model/chem/psd/##"
    assert (pmstoich.numAllPools == 3)
    assert (pmdsolve.numPools == 3)
    assert (pmdsolve.numAllVoxels == pdc)
    foo = moose.element('/model/chem/psd/Ca')
    print('PSD: numfoo = ', foo.numData)
    print('PSD: numAllVoxels = ', pmksolve.numAllVoxels)

    # Put in junctions between the diffusion solvers
    nmdsolve.buildNeuroMeshJunctions(smdsolve, pmdsolve)
    """
	CaNpsd = moose.vec( '/model/chem/psdMesh/PSD/PP1_PSD/CaN' )
	print 'numCaN in PSD = ', CaNpsd.nInit, ', vol = ', CaNpsd.volume
	CaNspine = moose.vec( '/model/chem/spine/SPINE/CaN_BULK/CaN' )
	print 'numCaN in spine = ', CaNspine.nInit, ', vol = ', CaNspine.volume
	"""

    ##################################################################
    # set up adaptors
    aCa = moose.Adaptor('/model/chem/spine/adaptCa', sdc)
    adaptCa = moose.vec('/model/chem/spine/adaptCa')
    chemCa = moose.vec('/model/chem/spine/Ca')
    #print 'aCa = ', aCa, ' foo = ', foo, "len( ChemCa ) = ", len( chemCa ), ", numData = ", chemCa.numData, "len( adaptCa ) = ", len( adaptCa )
    assert (len(adaptCa) == sdc)
    assert (len(chemCa) == sdc)
    for i in range(sdc):
        elecCa = moose.element('/model/elec/spine_head_14_' + str(i + 1) +
                               '/NMDA_Ca_conc')
        #print elecCa
        moose.connect(elecCa, 'concOut', adaptCa[i], 'input', 'Single')
    moose.connect(adaptCa, 'output', chemCa, 'setConc', 'OneToOne')
    adaptCa.inputOffset = 0.0  #
    adaptCa.outputOffset = 0.00008  # 80 nM offset in chem.
    adaptCa.scale = 1e-4  # 520 to 0.0052 mM
    #print adaptCa.outputOffset

    moose.le('/model/chem/dend/DEND')

    compts = neuroCompt.elecComptList
    begin = neuroCompt.startVoxelInCompt
    end = neuroCompt.endVoxelInCompt
    aCa = moose.Adaptor('/model/chem/dend/DEND/adaptCa', len(compts))
    adaptCa = moose.vec('/model/chem/dend/DEND/adaptCa')
    chemCa = moose.vec('/model/chem/dend/DEND/Ca')
    #print 'aCa = ', aCa, ' foo = ', foo, "len( ChemCa ) = ", len( chemCa ), ", numData = ", chemCa.numData, "len( adaptCa ) = ", len( adaptCa )
    assert (len(chemCa) == ndc)
    for i in zip(compts, adaptCa, begin, end):
        name = i[0].path + '/Ca_conc'
        if (moose.exists(name)):
            elecCa = moose.element(name)
            #print i[2], i[3], '   ', elecCa
            #print i[1]
            moose.connect(elecCa, 'concOut', i[1], 'input', 'Single')
            for j in range(i[2], i[3]):
                moose.connect(i[1], 'output', chemCa[j], 'setConc', 'Single')
    adaptCa.inputOffset = 0.0  #
    adaptCa.outputOffset = 0.00008  # 80 nM offset in chem.
    adaptCa.scale = 20e-6  # 10 arb units to 2 uM.
Esempio n. 37
0
cell.synapse[0].delay = 10e-3
#this cell fires only when synaptic weight reaching it exceeds threshold - resets to neg and resets to 0 in refractoryPeriod time
#else, goes back to 0 in tau time

VmVal = moose.Table(cellPath + '/Vm_cell')
print 'table>cellVm:', moose.connect(VmVal, 'requestOut', cell, 'getVm')
spikeTime = moose.Table(cellPath + '/spikeTimes')
print 'table>cellSpike:', moose.connect(cell, 'spike', spikeTime, 'input')

inSpkGen = moose.SpikeGen(cellPath + '/inSpkGen')
inSpkGen.setField('threshold', 2.0)
inSpkGen.setField('edgeTriggered', True)

if inputGiven == 1:
    print 'pulse>spike:', moose.connect(pg, 'output',
                                        moose.element(cellPath + '/inSpkGen'),
                                        'Vm')
    inTable = moose.Table(cellPath + '/inSpkGen/inTable')
    print 'table>spike:', moose.connect(inTable, 'requestOut', inSpkGen,
                                        'getHasFired')

print 'spike>cell:', moose.connect(inSpkGen, 'spikeOut', cell.synapse[0],
                                   'addSpike')
#print 'spike>cell:', moose.connect(pg, 'output', cell ,'injectDest')

moose.setClock(0, 1e-4)
moose.useClock(0, '/cell,/cell/##,/elec/##', 'process')
moose.reinit()
moose.start(0.2)

subplot(311)
Esempio n. 38
0
 def set_compartment_param(self, compartment, name, value, mechanismname):
     """ Set the param for the compartment depending on name and mechanismname. """
     if name == 'CM':
         compartment.Cm = value * math.pi * compartment.diameter * compartment.length
     elif name == 'RM':
         compartment.Rm = value / (math.pi * compartment.diameter *
                                   compartment.length)
     elif name == 'RA':
         compartment.Ra = value * compartment.length / (
             math.pi * (compartment.diameter / 2.0)**2)
     elif name == 'Em':
         compartment.Em = value
     elif name == 'initVm':
         compartment.initVm = value
     elif name == 'inject':
         # this reader converts to SI
         pu.info("Comparment %s inject %s A." % (compartment.name, value))
         compartment.inject = value
     elif name == 'v_reset':
         compartment.vReset = value  # compartment is a moose.LIF instance (intfire)
     elif name == 'threshold':
         compartment.thresh = value  # compartment is a moose.LIF instance (intfire)
     elif name == 't_refrac':
         compartment.refractoryPeriod = value  # compartment is a moose.LIF instance (intfire)
     elif name == 'g_refrac':
         pu.info("SORRY, current moose.LIF doesn't support g_refrac.")
     elif mechanismname is 'synapse':  # synapse being added to the compartment
         ## these are potential locations, we do not actually make synapses,
         ## unless the user has explicitly asked for it
         if self.createPotentialSynapses:
             syn_name = value
             if not moose.exists(compartment.path + '/' + syn_name):
                 make_new_synapse(syn_name, compartment, syn_name,
                                  self.nml_params)
         ## I assume below that compartment name has _segid at its end
         segid = string.split(
             compartment.name,
             '_')[-1]  # get segment id from compartment name
         self.segDict[segid][5].append(value)
     elif mechanismname is 'spikegen':  # spikegen being added to the compartment
         ## these are potential locations, we do not actually make the spikegens.
         ## spikegens for different synapses can have different thresholds,
         ## hence include synapse_type in its name
         ## value contains name of synapse i.e. synapse_type
         #spikegen = moose.SpikeGen(compartment.path+'/'+value+'_spikegen')
         #moose.connect(compartment,"VmSrc",spikegen,"Vm")
         pass
     ## previous were mechanism that don't need a ChannelML definition
     ## including integrate_and_fire (I ignore the ChannelML definition)
     ## thus integrate_and_fire mechanism default values cannot be used
     ## i.e. nothing needed in /library, but below mechanisms need.
     elif mechanismname is not None:
         ## if mechanism is not present in compartment, deep copy from library
         ## all mechanisms have been loaded into the library earlier
         if not moose.exists(compartment.path + '/' + mechanismname):
             neutralObj = moose.element(
                 "/library/" + mechanismname)  # gives error if not present
             if 'CaConc' == neutralObj.className:  # Ion concentration pool
                 libcaconc = moose.CaConc("/library/" + mechanismname)
                 ## deep copies the library caconc under the compartment
                 caconc = moose.copy(libcaconc, compartment, mechanismname)
                 caconc = moose.CaConc(caconc)
                 ## CaConc connections are made later using connect_CaConc()
                 ## Later, when calling connect_CaConc,
                 ## B is set for caconc based on thickness of Ca shell and compartment l and dia
                 ## OR based on the Mstring phi under CaConc path.
                 channel = None
             elif 'HHChannel2D' == neutralObj.className:  ## HHChannel2D
                 libchannel = moose.HHChannel2D("/library/" + mechanismname)
                 ## deep copies the library channel under the compartment
                 channel = moose.copy(libchannel, compartment,
                                      mechanismname)
                 channel = moose.HHChannel2D(channel)
                 moose.connect(channel, 'channel', compartment, 'channel')
             elif 'HHChannel' == neutralObj.className:  ## HHChannel
                 libchannel = moose.HHChannel("/library/" + mechanismname)
                 ## deep copies the library channel under the compartment
                 channel = moose.copy(libchannel, compartment,
                                      mechanismname)
                 channel = moose.HHChannel(channel)
                 moose.connect(channel, 'channel', compartment, 'channel')
         ## if mechanism is present in compartment, just wrap it
         else:
             neutralObj = moose.Neutral(compartment.path + '/' +
                                        mechanismname)
             if 'CaConc' == neutralObj.className:  # Ion concentration pool
                 caconc = moose.CaConc(
                     compartment.path + '/' +
                     mechanismname)  # wraps existing channel
                 channel = None
             elif 'HHChannel2D' == neutralObj.className:  ## HHChannel2D
                 channel = moose.HHChannel2D(
                     compartment.path + '/' +
                     mechanismname)  # wraps existing channel
             elif 'HHChannel' == neutralObj.className:  ## HHChannel
                 channel = moose.HHChannel(
                     compartment.path + '/' +
                     mechanismname)  # wraps existing channel
         if name == 'Gbar':
             if channel is None:  # if CaConc, neuroConstruct uses gbar for thickness or phi
                 ## If child Mstring 'phi' is present, set gbar as phi
                 ## BUT, value has been multiplied by Gfactor as a Gbar,
                 ## SI or physiological not known here,
                 ## ignoring Gbar for CaConc, instead of passing units here
                 child = moose_utils.get_child_Mstring(caconc, 'phi')
                 if child is not None:
                     #child.value = value
                     pass
                 else:
                     #caconc.thick = value
                     pass
             else:  # if ion channel, usual Gbar
                 channel.Gbar = value * math.pi * compartment.diameter * compartment.length
         elif name == 'Ek':
             channel.Ek = value
         elif name == 'thick':  # thick seems to be NEURON's extension to NeuroML level 2.
             caconc.thick = value  ## JUST THIS WILL NOT DO - HAVE TO SET B based on this thick!
             ## Later, when calling connect_CaConc,
             ## B is set for caconc based on thickness of Ca shell and compartment l and dia.
             ## OR based on the Mstring phi under CaConc path.
     if neuroml_utils.neuroml_debug:
         pu.info("Setting %s  for comparment %s to %s" %
                 (name, compartment.path, value))
Esempio n. 39
0
def countCrossings(plot, thresh):
    vec = moose.element(plot).vector
    print(vec)
    #  print (vec[:-1] <= thresh)
    return sum((vec[:-1] < thresh) * (vec[1:] >= thresh))
Esempio n. 40
0
    def readMorphML(self, cell, params={}, lengthUnits="micrometer"):
        """
        returns cellDict = { cellname: (segDict, cableDict) } # note: single cell only
        where segDict = { segid1 : [ segname,(proximalx,proximaly,proximalz),
            (distalx,distaly,distalz),diameter,length,[potential_syn1, ... ] ] , ... }
        segname is "<name>_<segid>" because 1) guarantees uniqueness,
            & 2) later scripts obtain segid from the compartment's name!
        and cableDict = { cablegroupname : [campartment1name, compartment2name, ... ], ... }
        """
        if lengthUnits in ['micrometer', 'micron']:
            self.length_factor = 1e-6
        else:
            self.length_factor = 1.0
        cellname = cell.attrib["name"]
        moose.Neutral(
            '/library')  # creates /library in MOOSE tree; elif present, wraps
        pu.info("Loading cell %s into /library ." % cellname)

        #~ moosecell = moose.Cell('/library/'+cellname)
        #using moose Neuron class - in previous version 'Cell' class Chaitanya
        moosecell = moose.Neuron('/library/' + cellname)
        self.cellDictBySegmentId[cellname] = [moosecell, {}]
        self.cellDictByCableId[cellname] = [moosecell, {}]
        self.segDict = {}
        if 'combineSegments' in list(params.keys()):
            self.combineSegments = params['combineSegments']
        else:
            self.combineSegments = False
        if 'createPotentialSynapses' in list(params.keys()):
            self.createPotentialSynapses = params['createPotentialSynapses']
        else:
            self.createPotentialSynapses = False
        pu.info("readMorphML using combineSegments = %s" %
                self.combineSegments)

        ###############################################
        #### load cablegroups into a dictionary
        self.cablegroupsDict = {}
        ## Two ways of specifying cablegroups in neuroml 1.x
        ## <cablegroup>s with list of <cable>s
        cablegroups = cell.findall(".//{" + self.mml + "}cablegroup")
        for cablegroup in cablegroups:
            cablegroupname = cablegroup.attrib['name']
            self.cablegroupsDict[cablegroupname] = []
            for cable in cablegroup.findall(".//{" + self.mml + "}cable"):
                cableid = cable.attrib['id']
                self.cablegroupsDict[cablegroupname].append(cableid)
        ## <cable>s with list of <meta:group>s
        cables = cell.findall(".//{" + self.mml + "}cable")
        for cable in cables:
            cableid = cable.attrib['id']
            cablegroups = cable.findall(".//{" + self.meta + "}group")
            for cablegroup in cablegroups:
                cablegroupname = cablegroup.text
                if cablegroupname in list(self.cablegroupsDict.keys()):
                    self.cablegroupsDict[cablegroupname].append(cableid)
                else:
                    self.cablegroupsDict[cablegroupname] = [cableid]

        ###################################################
        ## load all mechanisms in this cell into /library for later copying
        ## set which compartments have integrate_and_fire mechanism
        self.intFireCableIds = {
        }  # dict with keys as Compartments/cableIds which are IntFire
        # with mechanismnames as values
        for mechanism in cell.findall(".//{" + self.bio + "}mechanism"):
            mechanismname = mechanism.attrib["name"]
            passive = False
            if "passive_conductance" in mechanism.attrib:
                if mechanism.attrib['passive_conductance'] in [
                        "true", 'True', 'TRUE'
                ]:
                    passive = True
            if not passive:
                ## if channel does not exist in library load it from xml file
                if not moose.exists("/library/" + mechanismname):
                    pu.info("Loading mechanism %s into library." %
                            mechanismname)
                    cmlR = ChannelML(self.nml_params)
                    model_filename = mechanismname + '.xml'
                    model_path = neuroml_utils.find_first_file(
                        model_filename, self.model_dir)
                    if model_path is not None:
                        cmlR.readChannelMLFromFile(model_path)
                    else:
                        raise IOError(
                            'For mechanism {0}: files {1} not found under {2}.'
                            .format(mechanismname, model_filename,
                                    self.model_dir))

                    ## set those compartments to be LIF for which
                    ## any integrate_and_fire parameter is set
                    if not moose.exists("/library/" + mechanismname):
                        print "Mechanism doesn't exist: ", mechanismname
                        moose.le('/library')
                    moosemech = moose.element("/library/" + mechanismname)
                    if moose.exists(moosemech.path + "/integrate_and_fire"):
                        mooseIaF = moose.element(
                            moosemech.path + "/integrate_and_fire")  # Mstring
                        if mooseIaF.value in ['true', 'True', 'TRUE']:
                            mech_params = mechanism.findall(".//{" + self.bio +
                                                            "}parameter")
                            for parameter in mech_params:
                                parametername = parameter.attrib['name']
                                ## check for the integrate_and_fire parameters
                                if parametername in [
                                        'threshold', 't_refrac', 'v_reset',
                                        'g_refrac'
                                ]:
                                    for group in parameter.findall(".//{" +
                                                                   self.bio +
                                                                   "}group"):
                                        cablegroupname = group.text
                                        if cablegroupname == 'all':
                                            self.intFireCableIds = {
                                                'all': mechanismname
                                            }
                                            break
                                        else:
                                            for cableid in self.cablegroupsDict[
                                                    cablegroupname]:
                                                ## only one intfire mechanism is allowed in a cable
                                                ## the last one parsed will override others
                                                self.intFireCableIds[
                                                    cableid] = mechanismname
                                if 'all' in list(self.intFireCableIds.keys()):
                                    break

        ############################################################
        #### load morphology and connections between compartments
        ## Many neurons exported from NEURON have multiple segments in a section
        ## If self.combineSegments = True,
        ##  then combine those segments into one Compartment / section
        ##  for combining, assume segments of a compartment/section are in increasing order
        ##  and assume all segments of a compartment/section have the same cableid
        ## findall() returns elements in document order:
        running_cableid = ''
        running_segid = ''
        running_comp = None
        running_diameter = 0.0
        running_dia_nums = 0
        segments = cell.findall(".//{" + self.mml + "}segment")
        segmentstotal = len(segments)
        for segnum, segment in enumerate(segments):
            segmentname = segment.attrib['name']
            ## cable is an optional attribute. WARNING: Here I assume it is always present.
            cableid = segment.attrib['cable']
            segmentid = segment.attrib['id']
            ## if old cableid still running AND self.combineSegments == True,
            ## then don't start a new compartment, skip to next segment
            if cableid == running_cableid and self.combineSegments:
                self.cellDictBySegmentId[cellname][1][segmentid] = running_comp
                proximal = segment.find('./{' + self.mml + '}proximal')
                if proximal is not None:
                    running_diameter += float(
                        proximal.attrib["diameter"]) * self.length_factor
                    running_dia_nums += 1
                distal = segment.find('./{' + self.mml + '}distal')
                if distal is not None:
                    running_diameter += float(
                        distal.attrib["diameter"]) * self.length_factor
                    running_dia_nums += 1
            ## if (self.combineSegments and new cableid starts) or if not self.combineSegments,
            ##  then start a new compartment
            else:
                ## Create a new compartment
                ## the moose "hsolve" method assumes compartments to be
                ## asymmetric compartments and symmetrizes them
                ## but that is not what we want when translating
                ## from Neuron which has only symcompartments -- so be careful!

                ## Check if integrate_and_fire mechanism is present,
                ## if so use LIF instead of Compartment
                moosecompname = segmentname + '_' + segmentid  # just segmentname is NOT unique
                # eg: mitral bbmit exported from NEURON
                moosecomppath = moosecell.path + '/' + moosecompname
                IntFireIds = list(self.intFireCableIds.keys())
                mechanismname = None
                if 'all' in IntFireIds:
                    mechanismname = self.intFireCableIds['all']
                if cableid in IntFireIds:
                    mechanismname = self.intFireCableIds[cableid]
                if mechanismname is not None:  # this cableid is an intfire
                    ## create LIF (subclass of Compartment) and set to default values
                    moosecomp = moose.LIF(moosecomppath)
                    moosechannel = moose.Neutral('/library/' + mechanismname)
                    moosechannelval = moose.Mstring(moosechannel.path +
                                                    '/vReset')
                    moosecomp.vReset = moosechannelval.value
                    moosechannelval = moose.Mstring(moosechannel.path +
                                                    '/thresh')
                    moosecomp.thresh = moosechannelval.value
                    moosechannelval = moose.Mstring(moosechannel.path +
                                                    '/refracT')
                    moosecomp.refractoryPeriod = moosechannelval.value
                    ## refracG is currently not supported by moose.LIF
                    ## when you implement it, check if refracG or g_refrac
                    ## is a conductance density or a conductance, I think the former
                    #moosechannelval = moose.Mstring(moosechannel.path+'/refracG')
                else:
                    moosecomp = moose.Compartment(moosecomppath)
                self.cellDictBySegmentId[cellname][1][segmentid] = moosecomp
                ## cables are grouped and mechanism densities are set for cablegroups later.
                ## hence I will need to refer to segment according to which cable it belongs to.
                ## if combineSegments is False, there can be multiple segments per cable,
                ##  so make array of compartments for cellDictByCableId[cellname][1][cableid]
                if cableid in list(self.cellDictByCableId[cellname][1].keys()):
                    self.cellDictByCableId[cellname][1][cableid].append(
                        moosecomp)
                else:
                    self.cellDictByCableId[cellname][1][cableid] = [moosecomp]
                running_cableid = cableid
                running_segid = segmentid
                running_comp = moosecomp
                running_diameter = 0.0
                running_dia_nums = 0
                if 'parent' in segment.attrib:
                    parentid = segment.attrib[
                        'parent']  # I assume the parent is created before the child
                    # so that I can immediately connect the child.
                    parent = self.cellDictBySegmentId[cellname][1][parentid]
                    ## It is always assumed that axial of parent is connected to raxial of moosesegment
                    ## THIS IS WHAT GENESIS readcell() DOES!!! UNLIKE NEURON!
                    ## THIS IS IRRESPECTIVE OF WHETHER PROXIMAL x,y,z OF PARENT = PROXIMAL x,y,z OF CHILD.
                    ## THIS IS ALSO IRRESPECTIVE OF fraction_along_parent SPECIFIED IN CABLE!
                    ## THUS THERE WILL BE NUMERICAL DIFFERENCES BETWEEN MOOSE/GENESIS and NEURON.
                    ## moosesegment sends Ra and Vm to parent, parent sends only Vm
                    ## actually for symmetric compartment, both parent and moosesegment require each other's Ra/2,
                    ## but axial and raxial just serve to distinguish ends.
                    moose.connect(parent, 'axial', moosecomp, 'raxial')
                else:
                    parent = None
                proximal = segment.find('./{' + self.mml + '}proximal')
                if proximal is None:  # If proximal tag is not present,
                    # then parent attribute MUST be present in the segment tag!
                    ## if proximal is not present, then
                    ## by default the distal end of the parent is the proximal end of the child
                    moosecomp.x0 = parent.x
                    moosecomp.y0 = parent.y
                    moosecomp.z0 = parent.z
                else:
                    moosecomp.x0 = float(
                        proximal.attrib["x"]) * self.length_factor
                    moosecomp.y0 = float(
                        proximal.attrib["y"]) * self.length_factor
                    moosecomp.z0 = float(
                        proximal.attrib["z"]) * self.length_factor
                    running_diameter += float(
                        proximal.attrib["diameter"]) * self.length_factor
                    running_dia_nums += 1
                distal = segment.find('./{' + self.mml + '}distal')
                if distal is not None:
                    running_diameter += float(
                        distal.attrib["diameter"]) * self.length_factor
                    running_dia_nums += 1
                ## finished creating new compartment

            ## Update the end position, diameter and length, and segDict of this comp/cable/section
            ## with each segment that is part of this cable (assumes contiguous segments in xml).
            ## This ensures that we don't have to do any 'closing ceremonies',
            ## if a new cable is encoutered in next iteration.
            if distal is not None:
                running_comp.x = float(distal.attrib["x"]) * self.length_factor
                running_comp.y = float(distal.attrib["y"]) * self.length_factor
                running_comp.z = float(distal.attrib["z"]) * self.length_factor
            ## Set the compartment diameter as the average diameter of all the segments in this section
            running_comp.diameter = running_diameter / float(running_dia_nums)
            ## Set the compartment length
            running_comp.length = math.sqrt((running_comp.x-running_comp.x0)**2+\
                (running_comp.y-running_comp.y0)**2+(running_comp.z-running_comp.z0)**2)
            ## NeuroML specs say that if (x0,y0,z0)=(x,y,z), then round compartment e.g. soma.
            ## In Moose set length = dia to give same surface area as sphere of dia.
            if running_comp.length == 0.0:
                running_comp.length = running_comp.diameter
            ## Set the segDict
            ## the empty list at the end below will get populated
            ## with the potential synapses on this segment, in function set_compartment_param(..)
            self.segDict[running_segid] = [running_comp.name,\
                (running_comp.x0,running_comp.y0,running_comp.z0),\
                (running_comp.x,running_comp.y,running_comp.z),\
                running_comp.diameter,running_comp.length,[]]
            if neuroml_utils.neuroml_debug:
                pu.info('Set up compartment/section %s' % running_comp.name)

        ###############################################
        #### load biophysics into the compartments
        biophysics = cell.find(".//{" + self.neuroml + "}biophysics")
        if biophysics is not None:
            ## see pg 219 (sec 13.2) of Book of Genesis for Physiological Units
            if biophysics.attrib["units"] == 'Physiological Units':
                CMfactor = 1e-2  # F/m^2 from microF/cm^2
                Cfactor = 1e-6  # F from microF
                RAfactor = 1e1  # Ohm*m from KOhm*cm
                RMfactor = 1e-1  # Ohm*m^2 from KOhm*cm^2
                Rfactor = 1e-3  # Ohm from KOhm
                Efactor = 1e-3  # V from mV
                Gfactor = 1e1  # S/m^2 from mS/cm^2
                Ifactor = 1e-6  # A from microA
                Tfactor = 1e-3  # s from ms
            else:
                CMfactor = 1.0
                Cfactor = 1.0
                RAfactor = 1.0
                RMfactor = 1.0
                Rfactor = 1.0
                Efactor = 1.0
                Gfactor = 1.0
                Ifactor = 1.0
                Tfactor = 1.0

            spec_capacitance = cell.find(".//{" + self.bio +
                                         "}spec_capacitance")
            for parameter in spec_capacitance.findall(".//{" + self.bio +
                                                      "}parameter"):
                self.set_group_compartment_param(cell, cellname, parameter,\
                 'CM', float(parameter.attrib["value"])*CMfactor, self.bio)
            spec_axial_resitance = cell.find(".//{" + self.bio +
                                             "}spec_axial_resistance")
            for parameter in spec_axial_resitance.findall(".//{" + self.bio +
                                                          "}parameter"):
                self.set_group_compartment_param(cell, cellname, parameter,\
                 'RA', float(parameter.attrib["value"])*RAfactor, self.bio)
            init_memb_potential = cell.find(".//{" + self.bio +
                                            "}init_memb_potential")
            for parameter in init_memb_potential.findall(".//{" + self.bio +
                                                         "}parameter"):
                self.set_group_compartment_param(cell, cellname, parameter,\
                 'initVm', float(parameter.attrib["value"])*Efactor, self.bio)
            for mechanism in cell.findall(".//{" + self.bio + "}mechanism"):
                mechanismname = mechanism.attrib["name"]
                passive = False
                if "passive_conductance" in mechanism.attrib:
                    if mechanism.attrib['passive_conductance'] in [
                            "true", 'True', 'TRUE'
                    ]:
                        passive = True
                pu.info("Loading mechanism %s " % mechanismname)
                ## ONLY creates channel if at least one parameter (like gmax) is specified in the xml
                ## Neuroml does not allow you to specify all default values.
                ## However, granule cell example in neuroconstruct has Ca ion pool without
                ## a parameter, applying default values to all compartments!
                mech_params = mechanism.findall(".//{" + self.bio +
                                                "}parameter")
                ## if no params, apply all default values to all compartments
                if len(mech_params) == 0:
                    for compartment_list in list(
                            self.cellDictByCableId[cellname][1].values()):
                        for compartment in compartment_list:
                            self.set_compartment_param(compartment, None,
                                                       'default',
                                                       mechanismname)
                ## if params are present, apply params to specified cable/compartment groups
                for parameter in mech_params:
                    parametername = parameter.attrib['name']
                    if passive:
                        if parametername in ['gmax']:
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'RM', RMfactor*1.0/float(parameter.attrib["value"]), self.bio)
                        elif parametername in ['e', 'erev']:
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'Em', Efactor*float(parameter.attrib["value"]), self.bio)
                        elif parametername in ['inject']:
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'inject', Ifactor*float(parameter.attrib["value"]), self.bio)
                        else:
                            pu.warn([
                                "Yo programmer of MorphML! You didn't",
                                " implement parameter %s " % parametername,
                                " in mechanism %s " % mechanismname
                            ])
                    else:
                        if parametername in ['gmax']:
                            gmaxval = float(
                                eval(parameter.attrib["value"],
                                     {"__builtins__": None}, {}))
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'Gbar', Gfactor*gmaxval, self.bio, mechanismname)
                        elif parametername in ['e', 'erev']:
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'Ek', Efactor*float(parameter.attrib["value"]), self.bio, mechanismname)
                        elif parametername in [
                                'depth'
                        ]:  # has to be type Ion Concentration!
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'thick', self.length_factor*float(parameter.attrib["value"]),\
                             self.bio, mechanismname)
                        elif parametername in ['v_reset']:
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'v_reset', Efactor*float(parameter.attrib["value"]),\
                             self.bio, mechanismname)
                        elif parametername in ['threshold']:
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             'threshold', Efactor*float(parameter.attrib["value"]),\
                             self.bio, mechanismname)
                        elif parametername in ['t_refrac']:
                            self.set_group_compartment_param(cell, cellname, parameter,\
                             't_refrac', Tfactor*float(parameter.attrib["value"]),\
                             self.bio, mechanismname)
                        else:
                            pu.warn([
                                "Yo programmer of MorphML import! You didn't",
                                " implement parameter %s " % parametername,
                                " in mechanism %s " % mechanismname
                            ])
            #### Connect the Ca pools and channels
            #### Am connecting these at the very end so that all channels and pools have been created
            #### Note: this function is in moose.utils not moose.neuroml.utils !
            for compartment_list in list(
                    self.cellDictByCableId[cellname][1].values()):
                moose_utils.connect_CaConc(compartment_list,\
                    self.temperature+neuroml_utils.ZeroCKelvin) # temperature should be in Kelvin for Nernst

        ##########################################################
        #### load connectivity / synapses into the compartments
        connectivity = cell.find(".//{" + self.neuroml + "}connectivity")
        if connectivity is not None:
            for potential_syn_loc in cell.findall(".//{" + self.nml +
                                                  "}potential_syn_loc"):
                if 'synapse_direction' in list(
                        potential_syn_loc.attrib.keys()):
                    if potential_syn_loc.attrib['synapse_direction'] in [
                            'post', 'preAndOrPost'
                    ]:
                        self.set_group_compartment_param(cell, cellname, potential_syn_loc,\
                            'synapse_type', potential_syn_loc.attrib['synapse_type'],\
                            self.nml, mechanismname='synapse')
                    if potential_syn_loc.attrib['synapse_direction'] in [
                            'pre', 'preAndOrPost'
                    ]:
                        self.set_group_compartment_param(cell, cellname, potential_syn_loc,\
                            'spikegen_type', potential_syn_loc.attrib['synapse_type'],\
                            self.nml, mechanismname='spikegen')

        ##########################################################
        #### annotate each compartment with the cablegroups it belongs to
        self.cableDict = {}
        for cablegroupname in list(self.cablegroupsDict.keys()):
            comp_list = []
            for cableid in self.cablegroupsDict[cablegroupname]:
                for compartment in self.cellDictByCableId[cellname][1][
                        cableid]:
                    cableStringPath = compartment.path + '/cable_groups'
                    cableString = moose.Mstring(cableStringPath)
                    if cableString.value == '':
                        cableString.value += cablegroupname
                    else:
                        cableString.value += ',' + cablegroupname
                    comp_list.append(compartment.name)
            self.cableDict[cablegroupname] = comp_list

        pu.info("Finished loading into library, cell: %s " % cellname)
        return {cellname: (self.segDict, self.cableDict)}
Esempio n. 41
0
KDR_SGbar_list = 50
KA_SGbar_list = 5
KMGbar_list = 9
hGbar_list = 0.18
CaTGbar_list = 0.5
CaRGbar_list = 0.5
CaLGbar_list = 1
KsAHPGbar_list = 150
KmAHPGbar_list = 10

j = 1
for RM in RM_list:
    exec(
        open('/home/analkumar2/Thesis/Thesis work/Bianchi2002_WT_CA1/CA1_WT.py'
             ).read())
    V_trace = moose.element('/model/graphs/plot0').vector
    start = False
    sp_start = []
    sp_end = []
    for i in range(0, len(V_trace)):
        if V_trace[i] > 0 and start == False:
            start = True
            sp_start.append(V_trace[i])
        if V_trace[i] < 0 and start == True:
            start = False
            sp_end.append(V_trace[i])
    sp_peak = np.add(sp_start, sp_end) / 2
    #if len(sp_peak)>2:
    # ax =plt.subplot(1,1,1)
    # ax.plot(V_trace)
    # plt.draw()
Esempio n. 42
0
 def setVal(self, val):
     moose.element(self.path).setField(self.field, val * self.scale)
     self.val = val
     updateDisplay()
Esempio n. 43
0
def xyPosition(objInfo, xory):
    try:
        return (float(moose.element(objInfo).getField(xory)))
    except ValueError:
        return (float(0))
Esempio n. 44
0
print 'a=', a
for i in range(10):
    syn = moose.SimpleSynHandler('alpha[' + str(i) + ']/sh')
    moose.connect(syn, 'activationOut', a.vec[i], 'activation')

syn = moose.SimpleSynHandler('alpha/sh', 10)
moose.connect(syn, 'activationOut', a, 'activation', 'OneToOne')
###############################
# FieldElement identity
###############################
x = syn.synapse  # x is an ElementField alpha[0].synapse
print 'x=', x
print 'x.num=', x.num  # Initially there are no synapses, so this will be 0
syn.synapse.num = 3  # We set number of field elements to 3
print 'x.num=', x.num  # x refers to a.synapse, so this should be 3
b = moose.element('alpha[0]/sh/synapse[1]')  # We access x[1]
print 'b=', b
print 'x[1]=', x[1]
print 'b==x[1]?', b == x[1]

###############################
# Check fieldIndex and dataId
###############################
print 'syn.synapse[0]=', syn.synapse[0]
print 'syn.synapse[1]=', syn.synapse[
    1]  # The fieldIndex should change, not dataId

#########################
# setVec call example
#########################
print 'alpha[0].synapse.delay=', x.delay
Esempio n. 45
0
def setupMeshObj(modelRoot):
    ''' Setup compartment and its members pool,reaction,enz cplx under self.meshEntry dictionaries \ 
    self.meshEntry with "key" as compartment, 
    value is key2:list where key2 represents moose object type,list of objects of a perticular type
    e.g self.meshEntry[meshEnt] = { 'reaction': reaction_list,'enzyme':enzyme_list,'pool':poollist,'cplx': cplxlist }
    '''
    xmin = 0.0
    xmax = 1.0
    ymin = 0.0
    ymax = 1.0
    listOfitems = {}
    positionInfoExist = True
    meshEntry = {}
    if meshEntry:
        meshEntry.clear()
    else:
        meshEntry = {}
    xcord = []
    ycord = []
    meshEntryWildcard = '/##[ISA=ChemCompt]'
    if modelRoot != '/':
        meshEntryWildcard = modelRoot + meshEntryWildcard
    for meshEnt in moose.wildcardFind(meshEntryWildcard):
        mollist = []
        realist = []
        enzlist = []
        cplxlist = []
        tablist = []
        funclist = []

        mol_cpl = moose.wildcardFind(meshEnt.path + '/##[ISA=PoolBase]')
        funclist = moose.wildcardFind(meshEnt.path + '/##[ISA=Function]')
        enzlist = moose.wildcardFind(meshEnt.path + '/##[ISA=EnzBase]')
        realist = moose.wildcardFind(meshEnt.path + '/##[ISA=ReacBase]')
        tablist = moose.wildcardFind(meshEnt.path + '/##[ISA=StimulusTable]')
        if mol_cpl or funclist or enzlist or realist or tablist:
            for m in mol_cpl:
                if isinstance(moose.element(m.parent), moose.CplxEnzBase):
                    cplxlist.append(m)
                    objInfo = m.parent.path + '/info'
                elif isinstance(moose.element(m), moose.PoolBase):
                    mollist.append(m)
                    objInfo = m.path + '/info'
                if moose.exists(objInfo):
                    listOfitems[moose.element(
                        moose.element(objInfo).parent)] = {
                            'x': xyPosition(objInfo, 'x'),
                            'y': xyPosition(objInfo, 'y')
                        }

                xcord.append(xyPosition(objInfo, 'x'))
                ycord.append(xyPosition(objInfo, 'y'))

            getxyCord(xcord, ycord, funclist, listOfitems)
            getxyCord(xcord, ycord, enzlist, listOfitems)
            getxyCord(xcord, ycord, realist, listOfitems)
            getxyCord(xcord, ycord, tablist, listOfitems)

            meshEntry[meshEnt] = {
                'enzyme': enzlist,
                'reaction': realist,
                'pool': mollist,
                'cplx': cplxlist,
                'table': tablist,
                'function': funclist
            }
            positionInfoExist = not(len(np.nonzero(xcord)[0]) == 0 \
                and len(np.nonzero(ycord)[0]) == 0)
            if positionInfoExist:
                xmin = min(xcord)
                xmax = max(xcord)
                ymin = min(ycord)
                ymax = max(ycord)
    return meshEntry, xmin, xmax, ymin, ymax, positionInfoExist, listOfitems
Esempio n. 46
0
def mooseWriteKkit(modelpath, filename, sceneitems={}):
    if filename.rfind('.') != -1:
        filename = filename[:filename.rfind('.')]
    else:
        filename = filename[:len(filename)]
    filename = filename + '.g'
    global NA
    NA = 6.0221415e23
    global cmin, cmax, xmin, xmax, ymin, ymax
    cmin, xmin, ymin = 0, 0, 0
    cmax, xmax, ymax = 1, 1, 1

    compt = moose.wildcardFind(modelpath + '/##[ISA=ChemCompt]')
    maxVol = estimateDefaultVol(compt)
    positionInfoExist = True
    if compt:
        if bool(sceneitems):
            cmin, cmax, xmin1, xmax1, ymin1, ymax1 = findMinMax(sceneitems)
        elif not bool(sceneitems):
            srcdesConnection = {}
            setupItem(modelpath, srcdesConnection)
            meshEntry, xmin, xmax, ymin, ymax, positionInfoExist, sceneitems = setupMeshObj(
                modelpath)
            if not positionInfoExist:
                #cmin,cmax,sceneitems = autoCoordinates(meshEntry,srcdesConnection)
                sceneitems = autoCoordinates(meshEntry, srcdesConnection)

        if not positionInfoExist:
            # if position are not from kkit, then zoom factor is applied while
            # writing to genesis. Like if position is from pyqtSceneItem or auto-coordinates
            cmin, cmax, xmin1, xmax1, ymin1, ymax1 = findMinMax(sceneitems)
            for k, v in list(sceneitems.items()):
                anno = moose.element(k.path + '/info')
                x1 = calPrime(v['x'])
                y1 = calPrime(v['y'])
                sceneitems[k]['x'] = x1
                sceneitems[k]['y'] = y1

        f = open(filename, 'w')
        writeHeader(f, maxVol)

        gtId_vol = writeCompartment(modelpath, compt, f)
        writePool(modelpath, f, gtId_vol, sceneitems)
        reacList = writeReac(modelpath, f, sceneitems)
        enzList = writeEnz(modelpath, f, sceneitems)
        writeSumtotal(modelpath, f)
        f.write("simundump xgraph /graphs/conc1 0 0 99 0.001 0.999 0\n"
                "simundump xgraph /graphs/conc2 0 0 100 0 1 0\n")
        tgraphs = moose.wildcardFind(modelpath + '/##[ISA=Table2]')
        first, second = " ", " "
        if tgraphs:
            first, second = writeplot(tgraphs, f)
        if first:
            f.write(first)
        f.write("simundump xgraph /moregraphs/conc3 0 0 100 0 1 0\n"
                "simundump xgraph /moregraphs/conc4 0 0 100 0 1 0\n")
        if second:
            f.write(second)
        f.write(
            "simundump xcoredraw /edit/draw 0 -6 4 -2 6\n"
            "simundump xtree /edit/draw/tree 0 \\\n"
            "  /kinetics/#[],/kinetics/#[]/#[],/kinetics/#[]/#[]/#[][TYPE!=proto],/kinetics/#[]/#[]/#[][TYPE!=linkinfo]/##[] \"edit_elm.D <v>; drag_from_edit.w <d> <S> <x> <y> <z>\" auto 0.6\n"
            "simundump xtext /file/notes 0 1\n")
        storeReacMsg(reacList, f)
        storeEnzMsg(enzList, f)
        if tgraphs:
            storePlotMsgs(tgraphs, f)
        writeFooter1(f)
        writeNotes(modelpath, f)
        writeFooter2(f)
        print('Written to file ' + filename)
        return True
    else:
        print(("Warning: writeKkit:: No model found on ", modelpath))
        return False
Esempio n. 47
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')
Esempio n. 48
0
def countitems(mitems, objtype):
    items = []
    items = moose.element(mitems).neighbors[objtype]
    uniqItems = set(items)
    countuniqItems = Counter(items)
    return (uniqItems, countuniqItems)
def makeCubeMultiscale():
    makeSpinyCompt()
    model = moose.Neutral('/model')
    elec = moose.element('/n')
    elec.name = 'elec'
    moose.move(elec, model)
    synInput = moose.element('/model/elec/compt/synInput')
    synInput.refractT = 47e-3
    makeChemInCubeMesh()
    # set up a reaction to fake diffusion between compts.
    headCa = moose.element('/model/chem/spineMesh/Ca')
    dendCa = moose.element('/model/chem/neuroMesh/Ca')
    diffReac = moose.Reac('/model/chem/spineMesh/diff')
    moose.connect(diffReac, 'sub', headCa, 'reac')
    moose.connect(diffReac, 'prd', dendCa, 'reac')
    diffReac.Kf = 1
    diffReac.Kb = headCa.volume / dendCa.volume

    # set up adaptors
    headCa = moose.element('/model/chem/spineMesh/Ca')
    dendCa = moose.element('/model/chem/neuroMesh/Ca')
    adaptCa = moose.Adaptor('/model/chem/adaptCa')
    elecCa = moose.element('/model/elec/head2/ca')
    # There are 5 spine heads in the electrical model. Average their input.
    for i in range(5):
        path = '/model/elec/head' + str(i) + '/ca'
        elecCa = moose.element(path)
        moose.connect(elecCa, 'concOut', adaptCa, 'input', 'Single')
    moose.connect(adaptCa, 'output', headCa, 'setConc')
    adaptCa.outputOffset = 0.0001  # 100 nM offset in chem.
    adaptCa.scale = 0.05  # 0.06 to 0.003 mM

    adaptGluR = moose.Adaptor('/model/chem/psdMesh/adaptGluR')
    chemR = moose.element('/model/chem/psdMesh/psdGluR')
    # Here we connect up the chem adaptors to only 3 of the spine
    # heads in the elec model, just to make it interesting.
    elec1R = moose.element('/model/elec/head1/gluR')
    elec2R = moose.element('/model/elec/head2/gluR')
    elec3R = moose.element('/model/elec/head3/gluR')
    moose.connect(adaptGluR, 'requestOut', chemR, 'getN', 'OneToAll')
    moose.connect(adaptGluR, 'output', elec1R, 'setGbar', 'OneToAll')
    moose.connect(adaptGluR, 'output', elec2R, 'setGbar', 'OneToAll')
    moose.connect(adaptGluR, 'output', elec3R, 'setGbar', 'OneToAll')
    adaptGluR.outputOffset = 1e-9  # pS
    adaptGluR.scale = 1e-8 / 100  # from n to pS

    adaptK = moose.Adaptor('/model/chem/neuroMesh/adaptK')
    chemK = moose.element('/model/chem/neuroMesh/kChan')
    elecK = moose.element('/model/elec/compt/K')
    moose.connect(adaptK, 'requestOut', chemK, 'getConc', 'OneToAll')
    moose.connect(adaptK, 'output', elecK, 'setGbar', 'OneToAll')
    adaptK.scale = 0.3  # from mM to Siemens
Esempio n. 50
0
def setupItem(modelPath, cntDict):
    '''This function collects information of what is connected to what. \
    eg. substrate and product connectivity to reaction's and enzyme's \
    sumtotal connectivity to its pool are collected '''
    #print " setupItem"
    sublist = []
    prdlist = []
    zombieType = ['ReacBase', 'EnzBase', 'Function', 'StimulusTable']
    for baseObj in zombieType:
        path = '/##[ISA=' + baseObj + ']'
        if modelPath != '/':
            path = modelPath + path
        if ((baseObj == 'ReacBase') or (baseObj == 'EnzBase')):
            for items in moose.wildcardFind(path):
                sublist = []
                prdlist = []
                uniqItem, countuniqItem = countitems(items, 'subOut')
                subNo = uniqItem
                for sub in uniqItem:
                    sublist.append(
                        (moose.element(sub), 's', countuniqItem[sub]))

                uniqItem, countuniqItem = countitems(items, 'prd')
                prdNo = uniqItem
                if (len(subNo) == 0 or len(prdNo) == 0):
                    print("Substrate Product is empty ", path, " ", items)

                for prd in uniqItem:
                    prdlist.append(
                        (moose.element(prd), 'p', countuniqItem[prd]))

                if (baseObj == 'CplxEnzBase'):
                    uniqItem, countuniqItem = countitems(items, 'toEnz')
                    for enzpar in uniqItem:
                        sublist.append((moose.element(enzpar), 't',
                                        countuniqItem[enzpar]))

                    uniqItem, countuniqItem = countitems(items, 'cplxDest')
                    for cplx in uniqItem:
                        prdlist.append(
                            (moose.element(cplx), 'cplx', countuniqItem[cplx]))

                if (baseObj == 'EnzBase'):
                    uniqItem, countuniqItem = countitems(items, 'enzDest')
                    for enzpar in uniqItem:
                        sublist.append((moose.element(enzpar), 't',
                                        countuniqItem[enzpar]))
                cntDict[items] = sublist, prdlist
        elif baseObj == 'Function':
            for items in moose.wildcardFind(path):
                sublist = []
                prdlist = []
                item = items.path + '/x[0]'
                uniqItem, countuniqItem = countitems(item, 'input')
                for funcpar in uniqItem:
                    sublist.append((moose.element(funcpar), 'sts',
                                    countuniqItem[funcpar]))

                uniqItem, countuniqItem = countitems(items, 'valueOut')
                for funcpar in uniqItem:
                    prdlist.append((moose.element(funcpar), 'stp',
                                    countuniqItem[funcpar]))
                cntDict[items] = sublist, prdlist

        # elif baseObj == 'Function':
        #     #ZombieSumFunc adding inputs
        #     inputlist = []
        #     outputlist = []
        #     funplist = []
        #     nfunplist = []
        #     for items in moose.wildcardFind(path):
        #         for funplist in moose.element(items).neighbors['valueOut']:
        #             for func in funplist:
        #                 funcx = moose.element(items.path+'/x[0]')
        #                 uniqItem,countuniqItem = countitems(funcx,'input')
        #                 for inPut in uniqItem:
        #                     inputlist.append((inPut,'st',countuniqItem[inPut]))
        #             cntDict[func] = inputlist
        else:
            for tab in moose.wildcardFind(path):
                tablist = []
                uniqItem, countuniqItem = countitems(tab, 'output')
                for tabconnect in uniqItem:
                    tablist.append((moose.element(tabconnect), 'tab',
                                    countuniqItem[tabconnect]))
                cntDict[tab] = tablist
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
Esempio n. 52
0
def main():
    """
    This example illustrates a **Relaxation Oscillator**. This is an 
    oscillator built around a switching reaction, which tends to flip 
    into one or other state and stay there. The relaxation bit comes 
    in because once it is in state 1, a slow (relaxation) process begins 
    which eventually flips it into state 2, and vice versa.
    
    The model is based on Bhalla, Biophys J. 2011. It is defined in 
    kkit format. It uses the deterministic gsl solver by default.
    You can specify the stochastic Gillespie solver on the command line 
    ``python relaxationOsc.py gssa``
    
    Things to do with the model:
    
        * Figure out what determines its frequency. You could change
          the initial concentrations of various model entities::
            
            ma = moose.element( '/model/kinetics/A/M' )
            ma.concInit *= 1.5
    
          Alternatively, you could scale the rates of molecular traffic
          between the compartments::
    
            exo = moose.element( '/model/kinetics/exo' )
            endo = moose.element( '/model/kinetics/endo' )
            exo.Kf *= 1.0
            endo.Kf *= 1.0
    
        * Play with stochasticity. The standard thing here is to scale the
          volume up and down::
    
            compt.volume = 1e-18 
            compt.volume = 1e-20 
            compt.volume = 1e-21 
    
    """
    solver = "gsl"  # Pick any of gsl, gssa, ee..
    #solver = "gssa"  # Pick any of gsl, gssa, ee..
    mfile = '../../genesis/OSC_Cspace.g'
    runtime = 4000.0
    if (len(sys.argv) >= 2):
        solver = sys.argv[1]
    modelId = moose.loadModel(mfile, 'model', solver)
    # Increase volume so that the stochastic solver gssa
    # gives an interesting output
    compt = moose.element('/model/kinetics')
    compt.volume = 1e-19
    dt = moose.element('/clock').tickDt[18]  # 18 is the plot clock.

    moose.reinit()
    moose.start(runtime)

    # Display all plots.
    img = mpimg.imread('relaxOsc_tut.png')
    fig = plt.figure(figsize=(12, 10))
    png = fig.add_subplot(211)
    imgplot = plt.imshow(img)
    ax = fig.add_subplot(212)
    x = moose.wildcardFind('/model/#graphs/conc#/#')
    t = numpy.arange(0, x[0].vector.size, 1) * dt
    ax.plot(t, x[0].vector, 'b-', label=x[0].name)
    ax.plot(t, x[1].vector, 'c-', label=x[1].name)
    ax.plot(t, x[2].vector, 'r-', label=x[2].name)
    ax.plot(t, x[3].vector, 'm-', label=x[3].name)
    plt.ylabel('Conc (mM)')
    plt.xlabel('Time (seconds)')
    pylab.legend()
    pylab.show()
Esempio n. 53
0
def main():
    library = moose.Neutral('/library')
    #makePassiveSoma( 'cell', params['dendL'], params['dendDia'] )
    makeDendProto()
    makeChemProto()
    rdes = rd.rdesigneur(
        turnOffElec=True,
        chemPlotDt=0.1,
        diffusionLength=params['diffusionL'],
        #cellProto=[['cell','soma']],
        cellProto=[['elec', 'dend']],
        chemProto=[['hydra', 'hydra']],
        chemDistrib=[['hydra', '#soma#,#dend#', 'install', '1']],
        #stimList=[['soma','1','.','inject','(t>0.01&&t<0.2)*1e-10']],
        plotList=[['soma', '1', 'dend/A', 'n', '# of A'],
                  ['soma', '1', 'dend/B', 'n', '# of B']],
    )
    moose.le('/library')
    moose.le('/library/hydra')
    rdes.buildModel()

    A = moose.element('/model/chem/dend/A')
    B = moose.element('/model/chem/dend/B')
    S = moose.element('/model/chem/dend/S')
    space = moose.element('/model/chem/dend/space')
    A.diffConst = 1e-13
    B.diffConst = 1e-11
    S.diffConst = 0
    space.diffConst = 0
    #moose.element('/model/chem/dend/A').vec[50].nInit=1.2
    #moose.element('/model/chem/dend/B').vec[50].nInit=1.2
    totLen = len(moose.vec('/model/chem/dend/A').n)
    sourceApply = range(int(totLen * 0.1) + 1)
    xl = 0
    for j in range(totLen):
        moose.element('/model/chem/dend/A').vec[j].concInit = 0.268331
        moose.element('/model/chem/dend/B').vec[j].concInit = 2.0

    for i in sourceApply:
        #moose.element('/model/chem/dend/A').vec[i].concInit=0.268331
        #moose.element('/model/chem/dend/B').vec[i].concInit=2
        moose.element('/model/chem/dend/S').vec[i].concInit = 1
        moose.element('/model/chem/dend/space').vec[i].concInit = xl * 0.1
        print moose.element('/model/chem/dend/space').vec[i].concInit, xl
        print moose.element('/model/chem/dend/S').vec[i].concInit
        xl = xl + 1

    #randper=np.random.uniform(1,2,savec)
    print 'simulation start'
    dtSol = 0.01
    moose.setClock(16, dtSol)
    moose.setClock(10, dtSol)
    moose.reinit()
    #avec=moose.vec('/model/chem/dend/A').n
    #bvec=moose.vec('/model/chem/dend/B').n
    #source=moose.vec('/model/chem/dend/S').n
    storeAvec = []
    numSteps = 2500
    time = 0
    t1 = 20
    t2 = 25
    maxs = 0.05
    space = moose.vec('/model/chem/dend/space').n
    # print 'coordinates are', space, np.cos(np.pi)

    for i in range(0, numSteps):
        #if t<20:
        #  source = maxs/2
        #elif t > 20 and t < 25:
        #  s = (maxs/4)*(1+np.cos(np.pi*(t-t1)/(t2-t1)))
        #else:
        #  s = 0
        avec = moose.vec('/model/chem/dend/A').conc
        #print moose.vec('/model/chem/dend/S').n
        bvec = moose.vec('/model/chem/dend/B').conc
        source = moose.vec('/model/chem/dend/S').conc
        space = moose.vec('/model/chem/dend/space').conc
        moose.start(dtSol)
        storeAvec.append(avec)
        time = time + dtSol
        print time

    #plt.ion()
    #fig = plt.figure(figsize=(6,6))
    trialNum = '1'
    fileName = 'Mori.xml'
    writeXML(storeAvec, trialNum, fileName)
    plt.plot(avec)
    plt.show()
    raw_input()
    print 'press any key to exit'

    return bvec, avec, source, space, storeAvec
def createPool(compt, name, concInit):
    meshEntries = moose.element(compt.path + '/mesh')
    pool = moose.Pool(compt.path + '/' + name)
    pool.concInit = concInit
    pool.diffConst = 1e-11
    return pool
def test_diffusion_gsolve_dsolve():
    """
    This example illustrates how to set up a diffusion/transport model with
    a simple reaction-diffusion system in a tapering cylinder:

    | Molecule **a** diffuses with diffConst of 10e-12 m^2/s.
    | Molecule **b** diffuses with diffConst of 5e-12 m^2/s.
    | Molecule **b** also undergoes motor transport with a rate of 10e-6 m/s
    |   Thus it 'piles up' at the end of the cylinder.
    | Molecule **c** does not move: diffConst = 0.0
    | Molecule **d** does not move: diffConst = 10.0e-12 but it is buffered.
    |   Because it is buffered, it is treated as non-diffusing.

    All molecules other than **d** start out only in the leftmost (first)
    voxel, with a concentration of 1 mM. **d** is present throughout
    at 0.2 mM, except in the last voxel, where it is at 1.0 mM.

    The cylinder has a starting radius of 2 microns, and end radius of
    1 micron. So when the molecule undergoing motor transport gets to the
    narrower end, its concentration goes up.

    There is a little reaction in all compartments: ``b + d <===> c``

    As there is a high concentration of **d** in the last compartment,
    when the molecule **b** reaches the end of the cylinder, the reaction
    produces lots of **c**.

    Note that molecule **a** does not participate in this reaction.

    The concentrations of all molecules are displayed in an animation.
    """
    runtime = 20.0
    diffdt = 0.005
    plotdt = 0.1
    makeModel()
    # Set up clocks. The dsolver to know before assigning stoich
    moose.setClock(10, diffdt)  # 10 is the standard clock for Dsolve.
    moose.setClock(16, plotdt)  # 16 is the standard clock for Ksolve.

    a = moose.element('/model/compartment/a')
    b = moose.element('/model/compartment/b')
    c = moose.element('/model/compartment/c')
    d = moose.element('/model/compartment/d')

    moose.reinit()
    atot = sum(a.vec.n)
    btot = sum(b.vec.n)
    ctot = sum(c.vec.n)
    dtot = sum(d.vec.n)
    for t in np.arange(0, runtime, plotdt):
        moose.start(plotdt)

    atot2 = sum(a.vec.n)
    btot2 = sum(b.vec.n)
    ctot2 = sum(c.vec.n)
    dtot2 = sum(d.vec.n)

    msg = 'Ratio of initial to final total numbers of '
    got = np.array((atot2 / atot, btot2 / btot, ctot2 / ctot, dtot2 / dtot))
    msg += 'a=%f b=%f, c=%f, d=%f' % (tuple(got))
    print(msg)
    print('Initial to final (b+c)=%f' % (float(btot2 + ctot2) / (btot + ctot)))
    expected = np.array((1.00003087, 1.39036644, 0.92191184, 1.11427514))
    error = got - expected
    rerror = np.abs(error) / expected
    assert np.allclose(got, expected,
                       atol=1e-3), "Got %s, expected %s" % (got, expected)
Esempio n. 56
0
        # ['soma', '1', 'CaT_chan', 'Gk', 'Soma CaT conductance'],
        # ['soma', '1', 'CaR_Schan', 'Gk', 'Soma CaR_S conductance'],
        # ['soma', '1', 'CaL_Schan', 'Gk', 'Soma CaL_S conductance'],

        # ['soma', '1', 'Na_Schan', 'Ik', 'Soma Sodium current'],
        # ['soma', '1', 'KDR_Schan', 'Ik', 'Soma Kdr current'],
        # ['soma', '1', 'KsAHP_chan', 'Ik', 'Soma KsAHP current'],
        # ['soma', '1', 'KSK_chan', 'Ik', 'Soma KSK current'],
        # ['soma', '1', 'CaT_chan', 'Ik', 'Soma CaT current'],
        # ['soma', '1', 'CaR_Schan', 'Ik', 'Soma CaR_S current'],
        # ['soma', '1', 'CaL_Schan', 'Ik', 'Soma CaL_S current'],
    ],
)

rdes.buildModel()
moose.element('/model/elec/soma/Ca_conc').B = CaConc_B
moose.element('/model/elec/soma/Ca_conc').tau = CaConc_tau
moose.reinit()

# data = moose.Neutral('/data')
# somaNa_SXgate = moose.Table('/data/somaNa_SXgate')
# somaNa_S = moose.element('/model/elec/soma/Na_Schan')
# moose.connect(somaNa_SXgate, 'requestOut', somaNa_S, 'getX')
# somaNa_SYgate = moose.Table('/data/somaNa_SYgate')
# moose.connect(somaNa_SYgate, 'requestOut', somaNa_S, 'getY')
# somaNa_SZgate = moose.Table('/data/somaNa_SZgate')
# moose.connect(somaNa_SZgate, 'requestOut', somaNa_S, 'getZ')

moose.start(6)

# plt.figure(100)
Esempio n. 57
0
def mergeChemModel(src, des):
    """ Merges two model or the path """
    A = src
    B = des
    sfile = src
    dfile = des
    loadedA = False
    loadedB = False
    modelA = moose.element('/')
    modelB = moose.element('/')
    modelA, loadedA = checkFile_Obj_str(A)
    modelB, loadedB = checkFile_Obj_str(B)

    if loadedA and loadedB:
        ## yet deleteSolver is called to make sure all the moose object are off from solver
        deleteSolver(modelA)
        deleteSolver(modelB)

        global poolListina
        poolListina = {}
        grpNotcopiedyet = []
        dictComptA = dict([
            (i.name, i)
            for i in moose.wildcardFind(modelA + '/##[ISA=ChemCompt]')
        ])
        dictComptB = dict([
            (i.name, i)
            for i in moose.wildcardFind(modelB + '/##[ISA=ChemCompt]')
        ])
        poolNotcopiedyet = []
        if len(dictComptA):
            for key in list(dictComptA.keys()):
                if key not in dictComptB:
                    # if compartmentname from modelB does not exist in modelA, then copy
                    copy = moose.copy(dictComptA[key], moose.element(modelB))
                    dictComptB[key] = moose.element(copy)
                else:
                    #if compartmentname from modelB exist in modelA,
                    #volume is not same, then change volume of ModelB same as ModelA
                    if abs(dictComptB[key].volume - dictComptA[key].volume):
                        #hack for now
                        while (abs(dictComptB[key].volume -
                                   dictComptA[key].volume) != 0.0):
                            dictComptA[key].volume = float(
                                dictComptB[key].volume)
                    dictComptB = dict([
                        (i.name, i)
                        for i in moose.wildcardFind(modelB +
                                                    '/##[ISA=ChemCompt]')
                    ])

                    #Mergering pool
                    poolMerge(dictComptB[key], dictComptA[key],
                              poolNotcopiedyet)

            if grpNotcopiedyet:
                # objA = moose.element(comptA).parent.name
                # if not moose.exists(objA+'/'+comptB.name+'/'+bpath.name):
                #   print bpath
                #   moose.copy(bpath,moose.element(objA+'/'+comptB.name))
                pass
            comptBdict = comptList(modelB)
            poolListinb = {}
            poolListinb = updatePoolList(comptBdict)
            R_Duplicated, R_Notcopiedyet, R_Daggling = [], [], []
            E_Duplicated, E_Notcopiedyet, E_Daggling = [], [], []
            for key in list(dictComptA.keys()):
                funcExist, funcNotallowed = [], []
                funcExist, funcNotallowed = functionMerge(
                    dictComptB, dictComptA, key)

                poolListinb = updatePoolList(dictComptB)
                R_Duplicated, R_Notcopiedyet, R_Daggling = reacMerge(
                    dictComptB, dictComptA, key, poolListinb)

                poolListinb = updatePoolList(dictComptB)
                E_Duplicated, E_Notcopiedyet, E_Daggling = enzymeMerge(
                    dictComptB, dictComptA, key, poolListinb)
            '''
            if isinstance(src, str):
                if os.path.isfile(src) == True:
                    spath, sfile = os.path.split(src)
                else:
                    sfile = src
            else:
                sfile = src
            if isinstance(des, str):
                print " A str",des
                if os.path.isfile(des) == True:
                    dpath, dfile = os.path.split(des)
                else:
                    dfile = des
            else:
                dfile = des
            '''
            print("\nThe content of %s (src) model is merged to %s (des)." %
                  (sfile, dfile))
            # Here any error or warning during Merge is written it down
            if funcExist:
                print(
                    "\nIn model \"%s\" pool already has connection from a function, these function from model \"%s\" is not allowed to connect to same pool,\n since no two function are allowed to connect to same pool:"
                    % (dfile, sfile))
                for fl in list(funcExist):
                    print("\t [Pool]:  %s [Function]:  %s \n" %
                          (str(fl.parent.name), str(fl.path)))
            if funcNotallowed:
                print(
                    "\nThese functions is not to copied, since pool connected to function input are from different compartment:"
                )
                for fl in list(funcNotallowed):
                    print("\t [Pool]:  %s [Function]:  %s \n" %
                          (str(fl.parent.name), str(fl.path)))
            if R_Duplicated or E_Duplicated:
                print(
                    "These Reaction / Enzyme are \"Duplicated\" into destination file \"%s\", due to "
                    "\n 1. If substrate / product name's are different for a give reaction/Enzyme name "
                    "\n 2. If product belongs to different compartment "
                    "\n Models have to decide to keep or delete these reaction/enzyme in %s"
                    % (dfile, dfile))
                if E_Duplicated:
                    print("Reaction: ")
                for rd in list(R_Duplicated):
                    print("%s " % str(rd.name))

                if E_Duplicated:
                    print("Enzyme:")
                    for ed in list(E_Duplicated):
                        print("%s " % str(ed.name))

            if R_Notcopiedyet or E_Notcopiedyet:

                print(
                    "\nThese Reaction/Enzyme in model are not dagging but while copying the associated substrate or product is missing"
                )
                if R_Notcopiedyet:
                    print("Reaction: ")
                for rd in list(R_Notcopiedyet):
                    print("%s " % str(rd.name))
                if E_Notcopiedyet:
                    print("Enzyme:")
                    for ed in list(E_Notcopiedyet):
                        print("%s " % str(ed.name))

            if R_Daggling or E_Daggling:
                print(
                    "\n Daggling reaction/enzyme are not allowed in moose, these are not merged to %s from %s"
                    % (dfile, sfile))
                if R_Daggling:
                    print("Reaction: ")
                    for rd in list(R_Daggling):
                        print("%s " % str(rd.name))
                if E_Daggling:
                    print("Enzyme:")
                    for ed in list(E_Daggling):
                        print("%s " % str(ed.name))
            ## Model is saved
            print("\n ")
            print('\nMerged model is available under moose.element(\'%s\')' %
                  (modelB))
            print(
                '  From the python terminal itself \n to save the model in to genesis format use \n   >moose.mooseWriteKkit(\'%s\',\'filename.g\')'
                % (modelB))
            print(
                '  to save into SBML format \n   >moose.mooseWriteSBML(\'%s\',\'filename.xml\')'
                % (modelB))
            return modelB
            # savemodel = raw_input("Do you want to save the model?  \"YES\" \"NO\" ")
            # if savemodel.lower() == 'yes' or savemodel.lower() == 'y':
            #     mergeto = raw_input("Enter File name ")
            #     if mergeto and mergeto.strip():
            #         filenameto = 'merge.g'
            #     else:
            #         if str(mergeto).rfind('.') != -1:
            #             mergeto = mergeto[:str(mergeto).rfind('.')]
            #         if str(mergeto).rfind('/'):
            #             mergeto = mergeto+'merge'

            #         filenameto = mergeto+'.g'

            #     error,written = moose.mooseWriteKkit(modelB, filenameto)
            #     if written == False:
            #         print('Could not save the Model, check the files')
            #     else:
            #         if error == "":
            #             print(" \n The merged model is saved into \'%s\' " %(filenameto))
            #         else:
            #             print('Model is saved but these are not written\n %s' %(error))

            # else:
            #     print ('\nMerged model is available under moose.element(\'%s\')' %(modelB))
            #     print ('  If you are in python terminal you could save \n   >moose.mooseWriteKkit(\'%s\',\'filename.g\')' %(modelB))
            #     print ('  If you are in python terminal you could save \n   >moose.mooseWriteSBML(\'%s\',\'filename.g\')' %(modelB))
            #return modelB
    else:
        print('\nSource file has no objects to copy(\'%s\')' % (modelA))
        return moose.element('/')
Esempio n. 58
0
        ],
        # ['soma', '1', '.', 'inject', f'(t>={preStimTime} && t<={preStimTime+injectTime}) ? {Injectcurr} : 0'],
    ],
    plotList=[
        ['soma', '1', '.', 'Vm', 'Soma Membrane potential MOOSE'],
        ['soma', '1', 'vclamp', 'current', 'Soma holding current MOOSE'],
        # ['soma', '1', ',', 'inject', 'Injected current MOOSE'],
        ['soma', '1', 'Ca_conc', 'Ca', 'soma calcium conc MOOSE'],
        ['soma', '1', Chan, 'Ik', 'Channel current MOOSE'],
    ],
)

rdes.buildModel()

try:
    moose.element('/model/elec/soma/vclamp').gain = CM * sm_area / elecPlotDt
    moose.element('/model/elec/soma/vclamp').tau = 5 * elecPlotDt
    moose.element('/model/elec/soma/vclamp').ti = elecPlotDt
    moose.element('/model/elec/soma/vclamp').td = 0
except:
    pass

try:
    moose.element('/model/elec/soma/Ca_conc').B = 1000e3 / (
        2 * F * depth * np.pi * sm_diam * sm_len * 2)
    # moose.element('/model/elec/soma/Ca_conc').B *= 2
    # moose.element('/model/elec/soma/Ca_conc').B = 0
except:
    pass

moose.reinit()
Esempio n. 59
0
def mooseIsInstance(element, classNames):
    return moose.element(element).__class__.__name__ in classNames
Esempio n. 60
0
def make_K_C():
    if moose.exists('K_C'):
        return

    K_C = moose.HHChannel('K_C')
    K_C.Ek = EK  #	V
    K_C.Gbar = 100.0 * SOMA_A  #	S
    K_C.Gk = 0  #	S
    K_C.Xpower = 1
    K_C.Zpower = 1
    K_C.instant = 4  # Flag: 0x100 means Z gate is instant.

    # Now make a X-table for the voltage-dependent activation parameter.
    xgate = moose.element('K_C/gateX')
    xgate.min = -0.1
    xgate.max = 0.05
    xgate.divs = 3000
    xA = numpy.zeros((xgate.divs + 1), dtype=float)
    xB = numpy.zeros((xgate.divs + 1), dtype=float)
    dx = (xgate.max - xgate.min) / xgate.divs
    x = xgate.min
    for i in range(xgate.divs + 1):
        alpha = 0.0
        beta = 0.0
        if (x < EREST_ACT + 0.05):
            alpha = math.exp(53.872 * (x - EREST_ACT) - 0.66835) / 0.018975
            beta = 2000 * (math.exp((EREST_ACT + 0.0065 - x) / 0.027)) - alpha
        else:
            alpha = 2000 * math.exp((EREST_ACT + 0.0065 - x) / 0.027)
            beta = 0.0
        xA[i] = alpha
        xB[i] = alpha + beta
        x = x + dx
    xgate.tableA = xA
    xgate.tableB = xB

    # Create a table for the function of concentration, allowing a
    # concentration range of 0 to 1000, with 50 divisions.  This is done
    # using the Z gate, which can receive a CONCEN message.  By using
    # the "instant" flag, the A and B tables are evaluated as lookup tables,
    #  rather than being used in a differential equation.
    zgate = moose.element('K_C/gateZ')
    zgate.min = 0.0
    xmax = 500.0
    zgate.max = xmax
    zgate.divs = 3000
    zA = numpy.zeros((zgate.divs + 1), dtype=float)
    zB = numpy.zeros((zgate.divs + 1), dtype=float)
    dx = (zgate.max - zgate.min) / zgate.divs
    x = zgate.min
    for i in range(xgate.divs + 1):
        if (x < (xmax / 4.0)):
            zA[i] = x * 4.0 / xmax
        else:
            zA[i] = 1.0
        zB[i] = 1.0
        x += dx
    zgate.tableA = zA
    zgate.tableB = zB

    # Now we need to provide for messages that link to external elements.
    # The message that sends the Ca concentration to the Z gate tables is stored
    # in an added field of the channel, so that it may be found by the cell
    # reader.
    addmsg1 = moose.Mstring('/library/K_C/addmsg1')
    addmsg1.value = '../Ca_conc	concOut	. concen'