def makeModel():
    moose.Neutral('/library')
    makeCellProto('cellProto')
    makeChemProto()
    #moose.SBML.readSBML('/home/vinu/Documents/Biophysics/new_mod/detailed_models/oct01_volScale/mv1.xml','/model')
    rdes = rd.rdesigneur(
        useGssa=False,
        turnOffElec=True,
        chemDt=0.01,
        diffDt=0.01,
        chemPlotDt=0.1,
        combineSegments=False,
        stealCellFromLibrary=True,
        diffusionLength=50e-9,
        cellProto=[['cellProto', 'elec']],
        chemProto=[['hydra', 'chem']],
        chemDistrib=[["chem", "#", "install", "1"]]
        #plotList = [
        #['psd/z', '1', '.', 'n', 'z n' ]
        #['psd/z', '1', '.', 'n', 'z n' ]
        #],
    )
    moose.seed(100)
    rdes.buildModel('/model')
    moose.element('/model/chem/dend/Rad').nInit = 30e-9
    ## moose.element('/model/chem/dend/stoich').allowNegative=1
    print 'built model'
Example #2
0
def main():
    global params
    fig = plt.figure(figsize=(6, 10), facecolor='white')

    library = moose.Neutral('/library')

    for ii in range(len(sys.argv)):
        if sys.argv[ii][:2] == '--':
            argName = sys.argv[ii][2:]
            if argName in params:
                params[argName] = float(sys.argv[ii + 1])
                if argName == 'sequence':
                    params[argName] = sys.argv[ii + 1]  # Leave it as a str.

    moose.seed(int(params['seed']))
    '''
    '''
    makePassiveSoma('cell', params['dendLength'], params['dendDiameter'])
    moose.le('/library')
    panelBCsingleCompt(fig)
    moose.le('/library')
    moose.delete('/library/soma')
    params['dendLength'] = 60e-6
    makePassiveSoma('cell', params['dendLength'], params['dendDiameter'])
    panelEFspatialSeq(fig)
    plt.tight_layout()
    plt.show()
Example #3
0
def makeModel():
    moose.Neutral('/library')
    makeCellProto('cellProto')
    makeChemProto('cProto')
    rdes = rd.rdesigneur(
        useGssa=False,
        turnOffElec=True,
        chemDt=0.1,
        diffDt=0.1,
        combineSegments=False,
        stealCellFromLibrary=True,
        diffusionLength=1e-6,
        cellProto=[['cellProto', 'elec']],
        spineProto=[['makePassiveSpine()', 'spine']],
        chemProto=[['cProto', 'chem']],
        spineDistrib=[[
            'spine', '#',
            str(spineSpacing),
            str(spineSpacingDistrib),
            str(spineSize),
            str(spineSizeDistrib),
            str(spineAngle),
            str(spineAngleDistrib)
        ]],
        chemDistrib=[["chem", "#dend#,#psd#", "install", "1"]],
        adaptorList=[
            ['psd/z', 'n', 'spine', 'psdArea', 50.0e-15, 500e-15],
        ])
    moose.seed(1234)
    rdes.buildModel('/model')
    print('built model')
    x = moose.vec('/model/chem/dend/x')
    x.concInit = 0.0
    for i in range(0, 20):
        x[i].concInit = concInit
Example #4
0
def test():
    """Test 
    """
    rdes = rd.rdesigneur(
        elecDt=50e-6,
        chemDt=0.002,
        diffDt=0.002,
        chemPlotDt=0.02,
        useGssa=False,
        # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSegments ]
        cellProto=[['ballAndStick', 'soma', 12e-6, 12e-6, 4e-6, 100e-6, 2]],
        chemProto=[[
            os.path.join(sdir_, '../py_rdesigneur/chem/chanPhosph3compt.g'),
            'chem'
        ]],
        spineProto=[['makeActiveSpine()', 'spine']],
        chanProto=[['make_Na()', 'Na'], ['make_K_DR()', 'K_DR'],
                   ['make_K_A()', 'K_A'], ['make_Ca()', 'Ca'],
                   ['make_Ca_conc()', 'Ca_conc']],
        passiveDistrib=[['soma', 'CM', '0.01', 'Em', '-0.06']],
        spineDistrib=[['spine', '#dend#', '50e-6', '1e-6']],
        chemDistrib=[['chem', '#', 'install', '1']],
        chanDistrib=[['Na', 'soma', 'Gbar', '300'],
                     ['K_DR', 'soma', 'Gbar', '250'],
                     ['K_A', 'soma', 'Gbar', '200'],
                     ['Ca_conc', 'soma', 'tau', '0.0333'],
                     ['Ca', 'soma', 'Gbar', '40']],
        adaptorList=[['psd/chan_p', 'n', 'glu', 'modulation', 0.1, 1.0],
                     ['Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8]],
        # Syn input basline 1 Hz, and 40Hz burst for 1 sec at t=20. Syn weight
        # is 0.5, specified in 2nd argument as a special case stimLists.
        stimList=[[
            'head#', '0.5', 'glu', 'periodicsyn', '1 + 40*(t>10 && t<11)'
        ]],
        plotList=[
            ['soma', '1', '.', 'Vm', 'Membrane potential'],
            ['#', '1', 'spine/Ca', 'conc', 'Ca in Spine'],
            ['#', '1', 'dend/DEND/Ca', 'conc', 'Ca in Dend'],
            ['#', '1', 'spine/Ca_CaM', 'conc', 'Ca_CaM'],
            ['head#', '1', 'psd/chan_p', 'conc', 'Phosph gluR'],
            ['head#', '1', 'psd/Ca_CaM_CaMKII', 'conc', 'Active CaMKII'],
        ])
    moose.seed(123)
    rdes.buildModel()
    moose.reinit()
    moose.start(25)
    data = []
    v = moose.wildcardFind('/##[TYPE=Table]')[0].vector
    assert np.allclose(
        (v.mean(), v.std()),
        (-0.06777396715033643, 0.008550767915889)), (v.mean(), v.std())
    for t in moose.wildcardFind('/##[TYPE=Table2]'):
        data.append(t.vector)

    m = np.mean(data, axis=1)
    u = np.std(data, axis=1)
    assert m.shape[0] == 67
    assert np.allclose(m, A, atol=1e-5), m - A
    assert np.allclose(u, B, atol=1e-5), u - B
Example #5
0
def test_rand():
    moose.seed(10)
    f, t = create_func('random', 'rnd()')
    moose.reinit()
    moose.start(1000)
    print(np.mean(t.vector), np.std(t.vector), 'xxx')
    assert abs(np.mean(t.vector) - 0.5) < 0.01
    assert np.std(t.vector) < 0.3
def test():
    """
    Test CICR.

    >>> test() # doctest: +NORMALIZE_WHITESPACE
    Rdesigneur: Elec model has 5 compartments and 2 spines on 4 compartments.
        Chem part of model has the following compartments:
        | In dend, 40 voxels X 19 pools
        | In spine, 2 voxels X 1 pools
        | In psd, 2 voxels X 1 pools
        | In dend_endo, 40 voxels X 2 pools
    True
    """
    rdes = rd.rdesigneur(
        turnOffElec=False,
        chemDt=0.002,
        chemPlotDt=0.02,
        diffusionLength=1e-6,
        numWaveFrames=50,
        useGssa=False,
        addSomaChemCompt=False,
        addEndoChemCompt=True,
        # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSeg]
        cellProto=[['ballAndStick', 'soma', 10e-6, 10e-6, 2e-6, 40e-6, 4]],
        spineProto=[['makeActiveSpine()', 'spine']],
        chemProto=[[
            os.path.join(sdir_, '../py_rdesigneur/chem/CICRspineDend.g'),
            'chem'
        ]],
        spineDistrib=[['spine', '#dend#', '10e-6', '0.1e-6']],
        chemDistrib=[['chem', 'dend#,spine#,head#', 'install', '1']],
        adaptorList=[['Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8]],
        stimList=[
            ['head0', '0.5', 'glu', 'periodicsyn', '1 + 40*(t>5 && t<6)'],
            ['head0', '0.5', 'NMDA', 'periodicsyn', '1 + 40*(t>5 && t<6)'],
            ['dend#', 'g>10e-6 && g<=31e-6', 'dend/IP3', 'conc', '0.0006'],
        ],
        plotList=[
            ['head#', '1', 'spine/Ca', 'conc', 'Spine Ca conc'],
            ['dend#', '1', 'dend/Ca', 'conc', 'Dend Ca conc'],
            ['dend#', '1', 'dend/Ca', 'conc', 'Dend Ca conc', 'wave'],
            ['dend#', '1', 'dend_endo/CaER', 'conc', 'ER Ca conc', 'wave'],
            ['soma', '1', '.', 'Vm', 'Memb potl'],
        ],
    )
    moose.seed(1234)
    rdes.buildModel()
    moose.reinit()
    moose.start(2)
    data = []
    for t in moose.wildcardFind('/##[TYPE=Table2]'):
        data.append(t.vector[::20])
    res = np.mean(data, axis=1)
    assert np.allclose(res, expected, rtol=1e-4, atol=1e-4), \
            "Total error %s" % np.sum(res - expected)
    return True
Example #7
0
def test_rand( ):
    moose.seed( 10 )
    f, t = create_func( 'random', 'rnd()')
    moose.reinit()
    moose.start(1)
    expected = [0.49458993, 0.44301495, 0.58332174, 0.70920801, 0.26360285,
            0.68381843, 0.33607158, 0.19812181, 0.87761494, 0.54088093,
            0.41366738]
    assert np.isclose(t.vector, expected ).all(), t.vector
    print( 'Passed test random' )
Example #8
0
def init():
    global _inited
    if _inited:
        return
    _inited = True
    if reseed:
        if moose_rngseed:
            moose.seed(int(moose_rngseed))
        else:
            moose.seed(0)
        if numpy_rngseed:
            numpy.random.seed(int(numpy_rngseed))
def test_rand():
    moose.seed(10)
    f, t = create_func('random', 'rnd()')
    moose.reinit()
    moose.start(1)
    expected = [
        0.29876116, 0.49458993, 0.83191136, 0.02517173, 0.26556613, 0.15037787,
        0.81660184, 0.89081653, 0.03061665, 0.72743551, 0.13145815
    ]
    assert np.isclose(
        t.vector, expected).all(), "Expected %s, got %s" % (expected, t.vector)
    print('Passed test random')
Example #10
0
def init():
    global _inited
    if _inited:
        return
    _inited = True
    if reseed:
        if moose_rngseed:
            moose.seed(int(moose_rngseed))
        else:
            moose.seed(0)
        if numpy_rngseed:
            numpy.random.seed(int(numpy_rngseed))
Example #11
0
def load():
    rdes = rd.rdesigneur(
        elecDt = 50e-6,
        chemDt = 0.002,
        diffDt = 0.002,
        chemPlotDt = 0.02,
        turnOffElec = True, #FindSim needs to create Vclamp and then solver.
        useGssa = False,
        # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSegments ]
        cellProto = [['ballAndStick', 'soma', 12e-6, 12e-6, 4e-6, 100e-6, 1 ]],
        chemProto = [['models/CaMKII_MAPK_7.g', 'chem']],
        spineProto = [['makeActiveSpine()', 'spine']],
        chanProto = [
            ['make_Na()', 'Na'], 
            ['make_K_DR()', 'K_DR'], 
            ['make_K_A()', 'K_A' ],
            ['make_glu()', 'glu' ],
            ['make_Ca()', 'Ca' ],
            ['make_Ca_conc()', 'Ca_conc' ]
        ],
        passiveDistrib = [['soma', 'CM', '0.01', 'Em', '-0.06']],
        spineDistrib = [['spine', '#dend#', '100e-6', '1e-6']],
        chemDistrib = [['chem', '#', 'install', '1' ]],
        chanDistrib = [
            ['Na', 'soma', 'Gbar', '300' ],
            ['K_DR', 'soma', 'Gbar', '250' ],
            ['K_A', 'soma', 'Gbar', '200' ],
            ['glu', 'dend#', 'Gbar', '20' ],
            ['Ca_conc', 'soma', 'tau', '0.0333' ],
            ['Ca', 'soma', 'Gbar', '40' ]
        ],
        adaptorList = [
            [ 'psd/tot_phospho_R', 'n', 'glu', 'modulation', 1.0, 0.3 ],
            [ 'Ca_conc', 'Ca', 'psd/Ca', 'conc', 0.00008, 3 ]
        ],
        # Syn wt is 0.2, specified in 2nd argument
        stimList = [['head#', '0.2','glu', 'periodicsyn', '0']],
    )
    moose.seed(1234567)
    rdes.buildModel()
    #moose.element( '/model/chem/dend/ksolve' ).numThreads = 4
    #moose.showfield( '/model/chem/dend/ksolve' )
    #moose.element( '/model/chem/dend/ksolve' ).method = "rk4"
    moose.delete( '/model/stims/stim0')
    inputElm = moose.element( '/model/elec/head0/glu/sh/synapse/synInput_rs' )
    inputElm.name = 'synInput'
    moose.connect( inputElm, 'spikeOut', '/model/elec/head0/glu/sh/synapse', 'addSpike' )
    #moose.showmsg( '/model/elec/head0/glu/sh/synapse/synInput_rs' )
    #import presettle_CaMKII_MAPK7_init
    moose.reinit()
    
    return rdes.model
Example #12
0
def equal():
    rand1, rand2 = [], []
    N = 10
    moose.seed( 10 )
    for i in range( N ):
        x = moose.rand()
        rand1.append( x )

    reload( moose )
    moose.seed( 10 )
    for i in range( N ):
        x = moose.rand()
        rand2.append( x )

    assert np.equal( rand1, rand2 ).all()
Example #13
0
def test_equal():
    rand1, rand2 = [], []
    N = 10
    moose.seed(10)
    for i in range(N):
        x = moose.rand()
        rand1.append(x)

    reload(moose)
    moose.seed(10)
    for i in range(N):
        x = moose.rand()
        rand2.append(x)

    assert np.equal(rand1, rand2).all()
def main():
    compartment = makeModel()
    ksolve = moose.Ksolve( '/model/compartment/ksolve' )
    stoich = moose.Stoich( '/model/compartment/stoich' )
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState( '/model/compartment/state' )

    moose.reinit()
    state.stoich = stoich
    state.convergenceCriterion = 1e-6
    moose.seed( 111 ) # Used when generating the samples in state space
    moose.reinit()
    moose.start(10)
    plot( 10)
def main():
    compartment = makeModel()
    ksolve = moose.Ksolve('/model/compartment/ksolve')
    stoich = moose.Stoich('/model/compartment/stoich')
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState('/model/compartment/state')

    moose.reinit()
    state.stoich = stoich
    state.convergenceCriterion = 1e-6
    moose.seed(111)  # Used when generating the samples in state space
    moose.reinit()
    moose.start(10)
    plot(10)
Example #16
0
def main():
		makeModel()
                moose.seed( 11111 )
		gsolve = moose.Gsolve( '/model/compartment/gsolve' )
		stoich = moose.Stoich( '/model/compartment/stoich' )
		#gsolve.numAllVoxels = 1
		compt = moose.element( '/model/compartment' );
                stoich.compartment = compt
                stoich.ksolve = gsolve
		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/gsolve', 'process' )
		a = moose.element( '/model/compartment/a' )

		for vol in ( 1e-19, 1e-20, 1e-21, 3e-22, 1e-22, 3e-23, 1e-23 ):
			# Set the volume
			#print 'vol = ', vol, ', a.concInit = ', a.concInit, ', a.nInit = ', a.nInit
			compt.volume = vol
			print 'vol = ', vol, ', a.concInit = ', a.concInit, ', a.nInit = ', a.nInit

			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.
			displayPlots()
                        #pylab.legend()
                        pylab.show( block=False )
                        print 'vol = ', vol, 'hit enter to go to next plot'
                        raw_input()

		quit()
Example #17
0
def panelEFspatialSeq(fig):
    print "Starting Panel EF"
    moose.seed(int(params['seed']))
    diffusionLength = params['diffusionLength']
    #makeChemProto( 'spread', stimAmpl = 1,diffLength = diffusionLength )
    fhn = ame.makeFHN([])
    rdes = rd.rdesigneur(
        useGssa=False,
        turnOffElec=True,
        chemPlotDt=0.02,
        # spineProto = [['makePassiveSpine()', 'spine']],
        # spineDistrib = [['spine', '#', str(params['spineSpacing']),'1e-7','1.4','0']],
        cellProto=[['./taper.p', 'elec']],
        chemProto=[['fhn', 'chem']],
        chemDistrib=[['chem', '#', 'install', '1']],
        plotList=[['#', '1', 'dend/A', 'n', '# of A'],
                  ['#', '1', 'dend/B', 'n', '# of B'],
                  ['#', '1', 'dend/phase', 'n', '# of Phase'],
                  ['#', '1', 'dend/Ca', 'n', '# of Ca']],
        moogList=[['#', 'x>5e-6 && x<100e-6', '.', 'Vm', 'Vm']]
        #plotList = [
        #   ['#', '1', 'dend/P_MAPK', 'conc', '[dend P_MAPK]'],
        #  ['#head#', '1', 'psd/Ca', 'conc', '[PSD Ca]'],
        # ['#head#', '1', 'spine/Ca', 'conc', '[spine Ca]'],
        #['soma', '1', 'dend/DEND/Ca', 'conc', '[dend Ca]'],
        #],
    )
    # Assign parameters to the prototype model.
    #setDiffConst( 'Ca', 'diffConstCa' )
    #setDiffConst( '../../spine/Ca', 'diffConstCa' )
    #setDiffConst( '../../psd/Ca', 'diffConstCa' )
    #setDiffConst( 'P_MAPK', 'diffConstMAPK' )
    #setDiffConst( 'MAPK', 'diffConstMAPK' )
    #setDiffConst( 'reg_phosphatase', 'diffConstPP' )
    #setDiffConst( 'inact_phosphatase', 'diffConstPP' )
    #moose.element( '/library/chem/dend/DEND/Ca_activate_Raf' ).Kf = params['CaActivateRafKf']
    print "Set up rdesigneur"

    rdes.buildModel()
    print "MODEL BUILT"

    ################################################################
    # Run and display the stimulus
    runAndDisplay('01234', 'E', 1, rdes.chemPlotDt, 1.5)
    runAndDisplay('40312', 'F', 2, rdes.chemPlotDt, 1.5)
Example #18
0
def main():
    global params
    fig = plt.figure(figsize=(10, 6), facecolor='white')

    library = moose.Neutral('/library')

    for ii in range(len(sys.argv)):
        if sys.argv[ii][:2] == '--':
            argName = sys.argv[ii][2:]
            if argName in params:
                params[argName] = float(sys.argv[ii + 1])
                if argName == 'sequence':
                    params[argName] = sys.argv[ii + 1]  # Leave it as a str.

    moose.seed(int(params['seed']))
    panelEFspatialSeq(fig)
    plt.tight_layout()
    plt.show()
Example #19
0
def panelEFspatialSeq(fig):
    print "Starting Panel EF"
    moose.seed(int(params['seed']))
    rdes = rd.rdesigneur(
        useGssa=False,
        turnOffElec=True,
        chemPlotDt=0.02,
        diffusionLength=params['diffusionLength'],
        spineProto=[['makePassiveSpine()', 'spine']],
        spineDistrib=[[
            'spine', '#',
            str(params['spineSpacing']), '1e-7', '1.4', '0'
        ]],
        cellProto=[['cell', 'soma']],
        chemProto=[[params['chemModel'], 'chem']],
        chemDistrib=[['chem', 'soma', 'install', '1']],
        plotList=[
            ['soma', '1', 'dend/DEND/P_MAPK', 'conc', '[dend P_MAPK]'],
            ['#head#', '1', 'psd/Ca', 'conc', '[PSD Ca]'],
            ['#head#', '1', 'spine/Ca', 'conc', '[spine Ca]'],
            ['soma', '1', 'dend/DEND/Ca', 'conc', '[dend Ca]'],
        ],
    )
    # Assign parameters to the prototype model.
    setDiffConst('Ca', 'diffConstCa')
    setDiffConst('../../compartment_1/Ca', 'diffConstCa')
    setDiffConst('../../compartment_2/Ca', 'diffConstCa')
    setDiffConst('P_MAPK', 'diffConstMAPK')
    setDiffConst('MAPK', 'diffConstMAPK')
    setDiffConst('reg_phosphatase', 'diffConstPP')
    setDiffConst('inact_phosphatase', 'diffConstPP')
    moose.element('/library/chem/kinetics/DEND/Ca_activate_Raf'
                  ).Kf = params['CaActivateRafKf']
    print "Set up rdesigneur"

    rdes.buildModel()
    print "MODEL BUILT"

    ################################################################
    # Run and display the stimulus
    runAndDisplay('01234', 'E', (4, 0), rdes.chemPlotDt, 0.6)
    runAndDisplay('40312', 'F', (4, 1), rdes.chemPlotDt, 0.6)

    moose.delete('/model')
Example #20
0
def main():
    """
This example describes the special (and discouraged) use case where
functions provide input to a reaction system. Here we have two functions of
time which control the pool # and pool rate of change, respectively::

number of molecules of a = 1 + sin(t)
rate of change of number of molecules of b = 10 * cos(t)

In the stochastic case one must set a special flag *useClockedUpdate*
in order to achieve clock-triggered updates from the functions. This is
needed because the functions do not have reaction events to trigger them,
and even if there were reaction events they might not be frequent enough to
track the periodic updates. The use of this flag slows down the calculations,
so try to use a table to control a pool instead.

To run in stochastic mode::

	''python funcInputToPools''

To run in deterministic mode::

	''python funcInputToPools false''

    """

    makeModel()
    moose.seed()

    moose.reinit()
    moose.start( 50.0 ) # Run the model for 50 seconds.

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

    # Iterate through all plots, dump their contents to data.plot.
    for x in moose.wildcardFind( '/model/graphs/n#' ):
    	#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.legend()
	pylab.show()

    quit()
def main():
    """
    This example describes the special (and discouraged) use case where
    functions provide input to a reaction system. Here we have two functions of
    time which control the pool # and pool rate of change, respectively::

        number of molecules of a = 1 + sin(t)
        rate of change of number of molecules of b = 10 * cos(t)

    In the stochastic case one must set a special flag *useClockedUpdate*
    in order to achieve clock-triggered updates from the functions. This is
    needed because the functions do not have reaction events to trigger them,
    and even if there were reaction events they might not be frequent enough to
    track the periodic updates. The use of this flag slows down the calculations,
    so try to use a table to control a pool instead.

    To run in stochastic mode::

        >>> python funcInputToPools.py

    To run in deterministic mode::

        >>> python funcInputToPools.py false

    """

    makeModel()
    moose.seed()

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

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

    # Iterate through all plots, dump their contents to data.plot.
    for x in moose.wildcardFind('/model/graphs/n#'):
        #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.legend()
    pylab.show()

    quit()
def main():
		makeModel()
                moose.seed()

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

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

		# Iterate through all plots, dump their contents to data.plot.
		for x in moose.wildcardFind( '/model/graphs/n#' ):
				#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.legend()
		pylab.show()

		quit()
Example #23
0
def paneDlayout():
    print "Starting Panel D"
    moose.reinit()
    moose.seed(int(params['seed']))

    print "MODEL PREBUILT"
    rdes = rd.rdesigneur(useGssa=False,
                         turnOffElec=True,
                         chemPlotDt=0.02,
                         diffusionLength=params['diffusionLength'],
                         spineProto=[['makePassiveSpine()', 'spine']],
                         spineDistrib=[[
                             'spine', '#',
                             str(params['spineSpacing']), '1e-7', '1.4', '0'
                         ]],
                         cellProto=[['cell', 'soma']],
                         chemProto=[[params['chemModel'], 'chem']],
                         chemDistrib=[['chem', 'soma', 'install', '1']],
                         moogList=[
                             ['#', '1', '.', 'Vm', 'Vm', -0.1, 0.05],
                         ])
    rdes.buildModel()
    print "MODEL BUILT"
    sequence = [int(i) for i in params['sequence']]
    blanks = params['blankVoxelsAtEnd']
    step = int(round(params['seqDx'] / params['spineSpacing']))
    for i in moose.wildcardFind('/model/elec/head#,/model/elec/shaft#'):
        i.initVm = 0.0
    for i in sequence:
        e = moose.element('/model/elec/head' + str(blanks + i * step))
        e.initVm = 0.1
        e = moose.element('/model/elec/shaft' + str(blanks + i * step))
        e.initVm = 0.1

    ################################################################
    # Run and display the stimulus
    moose.reinit()
    rdes.displayMoogli(0.0001, 0.001, 0.0)
def main():
    compartment = makeModel()
    ksolve = moose.Ksolve('/model/compartment/ksolve')
    stoich = moose.Stoich('/model/compartment/stoich')
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState('/model/compartment/state')

    moose.reinit()
    state.stoich = stoich
    state.showMatrices()
    state.convergenceCriterion = 1e-6
    moose.seed(111)  # Used when generating the samples in state space

    for i in range(0, 50):
        getState(ksolve, state)

    # Now display the states of the system at more length to compare.
    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(400.0)  # Run the model for 200 seconds.

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

    quit()
def makeModel():
    moose.Neutral('/library')
    makeCellProto('cellProto')
    makeChemProto()
    rdes = rd.rdesigneur(
        useGssa=False,
        turnOffElec=False,
        chemDt=0.0025,
        diffDt=0.0025,
        chemPlotDt=0.1,
        combineSegments=False,
        stealCellFromLibrary=True,
        diffusionLength=50e-9,
        cellProto=[['cellProto', 'elec']],
        chanProto=[
            ['make_NMDA()', 'NMDA'],
            ['make_Ca_conc()', 'Ca_conc'],
        ],
        chemProto=[['hydra', 'chem']],
        chemDistrib=[["chem", "#", "install", "1"]],
        chanDistrib=[
            ['NMDA', 'dend#', 'Gbar', '1'],
            ['Ca_conc', 'dend#', 'tau', '0.033'],
        ],
        stimList=[
            [
                'dend#', '1.', 'NMDA', 'periodicsyn',
                str(args_[13]) + '*(t>0 && t<60)+' + str(args_[13]) + '*(t>' +
                str(args_[15]) + ' && t<(' + str(args_[15]) + '+60))'
            ],
        ],
        adaptorList=[['Ca_conc', 'Ca', 'dend/conv', 'conc', 0.00008, 20]],
        benchmark=True)
    moose.seed(100)
    print("[INFO ] rdes is building model ...")
    rdes.buildModel('/model')
    print("[INFO ] Model is built...")
    moose.element('/model/chem/dend/IRSpGr/Rad').nInit = 30e-9
Example #26
0
def dummy():
    print "Starting Dummy"
    makePassiveSoma('cell', 0.5e-6, params['dendDiameter'])
    moose.reinit()
    moose.seed(int(params['seed']))
    rdes = rd.rdesigneur(
        useGssa=False,
        turnOffElec=True,
        chemPlotDt=0.02,
        diffusionLength=params['diffusionLength'],
        spineProto=[['makePassiveSpine()', 'spine']],
        spineDistrib=[['spine', '#', '0.4e-6', '1e-7', '1.4', '0']],
        cellProto=[['cell', 'soma']],
        chemProto=[[params['chemModel'], 'chem']],
        chemDistrib=[['chem', 'soma', 'install', '1']],
        #moogList = [ ['soma', '1', '.', 'Vm', 'Vm', -0.1, 0.05], ]
    )
    rdes.buildModel()
    moose.le('/library')
    moose.delete('/library/soma')
    moose.delete('/library/chem')
    moose.le('/')
    moose.delete('/model')
    print "Finsihed dummy "
Example #27
0
def main():
    """
    Simulate pre and post Poisson firing for a synapse with
    Ca plasticity of Graupner and Brunel 2012.
    See the trace over time (lifetime) for the synaptic efficacy,
    similar to figure 2A of Higgins, Graupner, Brunel, 2014.

    Author: Aditya Gilra, NCBS, Bangalore, October, 2014.
    """

    numrepeats = 10  # repeat runtime for numrepeats

    frate = 1.0  # pre- and post-synaptic firing rate
    # 1 Hz gives ~300s lifetime, ~0.2 efficacy (weight)
    # 10 Hz gives ~10s lifetime, ~0.5 efficacy (weight)
    # high firing rates make synaptic efficacy go to 0.5.
    runtime = 600.0 / frate  # s

    #############################################
    # Ca Plasticity parameters: synapses (not for ExcInhNetBase)
    #############################################

    ## Cortical slice values -- Table Suppl 2 in Graupner & Brunel 2012
    ## Also used in Higgins et al 2014
    tauCa = 22.6936e-3  # s # Ca decay time scale
    tauSyn = 346.3615  # s # synaptic plasticity time scale
    ## in vitro values in Higgins et al 2014, faster plasticity
    CaPre = 0.56175  # mM
    CaPost = 1.2964  # mM
    ## in vivo values in Higgins et al 2014, slower plasticity
    #CaPre = 0.33705         # mM
    #CaPost = 0.74378        # mM
    delayD = 4.6098e-3  # s # CaPre is added to Ca after this delay
    # proxy for rise-time of NMDA
    thetaD = 1.0  # mM # depression threshold for Ca
    thetaP = 1.3  # mM # potentiation threshold for Ca
    gammaD = 331.909  # factor for depression term
    gammaP = 725.085  # factor for potentiation term

    J = 5e-3  # V            # delta function synapse, adds to Vm
    weight = 0.43  # initial synaptic weight
    # gammaP/(gammaP+gammaD) = eq weight w/o noise
    # see eqn (22), noiseSD also appears
    # but doesn't work here,
    # weights away from 0.4 - 0.5 screw up the STDP rule!!

    bistable = True  # if bistable is True, use bistable potential for weights
    noisy = True  # use noisy weight updates given by noiseSD
    noiseSD = 3.3501  # if noisy, use noiseSD (3.3501 from Higgins et al 2014)

    ##########################################

    prePoisson = moose.RandSpike('/pre')
    prePoisson.rate = frate
    postPoisson = moose.RandSpike('/post')
    postPoisson.rate = frate

    syn = moose.GraupnerBrunel2012CaPlasticitySynHandler('/syn')
    syn.numSynapses = 1  # 1 synapse
    # many pre-synaptic inputs can connect to a synapse

    # spikes from presynaptic Poisson generator
    moose.connect(prePoisson, 'spikeOut', syn.synapse[0], 'addSpike')

    # post-synaptic spikes from postsynaptic Poisson generator
    moose.connect(postPoisson, 'spikeOut', syn, 'addPostSpike')

    syn.synapse[0].delay = 0.0
    syn.synapse[0].weight = 1.0  # starting weight to decay from
    syn.CaInit = 0.0
    syn.tauCa = tauCa
    syn.tauSyn = tauSyn
    syn.CaPre = CaPre
    syn.CaPost = CaPost
    syn.delayD = delayD
    syn.thetaD = thetaD
    syn.thetaP = thetaP
    syn.gammaD = gammaD
    syn.gammaP = gammaP
    syn.weightMax = 1.0  # bounds on the weight
    syn.weightMin = 0.

    syn.noisy = noisy
    syn.noiseSD = noiseSD
    syn.bistable = bistable

    # ###########################################
    # Setting up tables
    # ###########################################

    CaTable = moose.Table('/plotCa', 1)
    moose.connect(CaTable, 'requestOut', syn, 'getCa')
    WtTable = moose.Table('/plotWeight', 1)
    moose.connect(WtTable, 'requestOut', syn.synapse[0], 'getWeight')

    # ###########################################
    # Simulate
    # ###########################################

    dt = 1e-3  # s
    # moose simulation
    #moose.useClock( 0, '/syn', 'process' )
    #moose.useClock( 1, '/pre', 'process' )
    #moose.useClock( 1, '/post', 'process' )
    # I think MOOSE uses a different clock than 3 for Tables
    # anyway, we use the default one and set all clocks to dt below
    #moose.useClock( 3, '/plotCa', 'process' )
    #moose.useClock( 3, '/plotWeight', 'process' )
    ## use setClock to set the dt different from default dt
    for i in range(10):
        moose.setClock(i, dt)

    moose.seed(100)
    moose.reinit()

    # function to make the aPlus and aMinus settle to equilibrium values
    print(("Rates of pre- and post-syanptic neurons =", frate))
    WtSeries = []
    numsteps = int(runtime / dt)
    for i in range(numrepeats):
        syn.synapse[0].weight = 1.0  # starting weight to decay from
        syn.Ca = 0.0
        print(("Repeat number", i, "running..."))
        moose.start(runtime)
        WtSeries.append(WtTable.vector[i * numsteps:(i + 1) * numsteps])
    WtSeries = array(WtSeries)
    WtMean = mean(WtSeries, axis=0)
    print("plotting...")

    # ###########################################
    # Plot the simulated weights and Ca vs time
    # ###########################################

    timeseries = linspace(0.0, runtime, numsteps)
    # Ca plots for the synapse
    # only the first repeat
    figure(facecolor='w')
    plot(timeseries, CaTable.vector[:numsteps], color='r')
    plot((timeseries[0],timeseries[-1]),(thetaP,thetaP),color='k',\
        linestyle='dashed',label='pot thresh')
    plot((timeseries[0],timeseries[-1]),(thetaD,thetaD),color='b',\
        linestyle='dashed',label='dep thresh')
    legend()
    xlabel('time (s)')
    ylabel('Ca (arb)')
    title("Ca conc in the synapse @ " + str(frate) + " Hz firing")

    # Weight plots for the synapse
    figure(facecolor='w')
    for i in range(numrepeats):
        plot(timeseries, WtSeries[i], alpha=0.5)
    plot(timeseries, WtMean, color='k', linewidth=2)
    xlabel('time (s)')
    ylabel('Efficacy')
    title("Efficacy of the synapse @ " + str(frate) + " Hz firing")

    show()
    Graupner, Michael, and Nicolas Brunel. 2012.
    Calcium-Based Plasticity Model Explains Sensitivity of Synaptic Changes to Spike Pattern, Rate, and Dendritic Location.
    Proceedings of the National Academy of Sciences, February, 201109359.
The Ca-based bistable synapse has been implemented as the GraupnerBrunel2012CaPlasticitySynHandler class.
"""

## import modules and functions to be used
import numpy as np
import matplotlib.pyplot as plt
import random
import time
import moose

np.random.seed(100)  # set seed for reproducibility of simulations
random.seed(100)  # set seed for reproducibility of simulations
moose.seed(100)  # set seed for reproducibility of simulations

#############################################
# All parameters as per:
# David Higgins, Michael Graupner, Nicolas Brunel
#     Memory Maintenance in Synapses with Calcium-Based
#     Plasticity in the Presence of Background Activity
#     PLOS Computational Biology, 2014.
#############################################

#############################################
# Neuron model
#############################################

# equation: dv/dt = (1/taum)*(-(v-el)) + inp
# with spike when v>vt, reset to vr
Example #29
0
import random
import time
import moose
from PyQt4 import Qt, QtCore, QtGui
from numpy import random as nprand
from moose.neuroml.NeuroML import NeuroML
import sys
import rdesigneur as rd
import moogli
cellname = "./cells_channels/CA1_nochans.morph.xml"
fname = "fig6bcde"

#############################################
np.random.seed(100) # set seed for reproducibility of simulations
random.seed(100) # set seed for reproducibility of simulations
moose.seed(100) # set seed for reproducibility of simulations

#############################################
# All parameters as per:
# David Higgins, Michael Graupner, Nicolas Brunel
#     Memory Maintenance in Synapses with Calcium-Based
#     Plasticity in the Presence of Background Activity
#     PLOS Computational Biology, 2014.
#############################################

#############################################
# Neuron model
#############################################

# equation: dv/dt = (1/taum)*(-(v-el)) + inp
# with spike when v>vt, reset to vr
    chemDistrib = [['chem', '#', 'install', '1' ]],
    chanDistrib = [
        ['Na', 'soma', 'Gbar', '300' ],
        ['K_DR', 'soma', 'Gbar', '250' ],
        ['K_A', 'soma', 'Gbar', '200' ],
        ['Ca_conc', 'soma', 'tau', '0.0333' ],
        ['Ca', 'soma', 'Gbar', '40' ]
    ],
    adaptorList = [
        [ 'psd/chan_p', 'n', 'glu', 'modulation', 0.1, 1.0 ],
        [ 'Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8 ]
    ],
    # Syn input basline 1 Hz, and 40Hz burst for 1 sec at t=20. Syn weight
    # is 0.5, specified in 2nd argument as a special case stimLists. 
    stimList = [['head#', '0.5','glu', 'periodicsyn', '1 + 40*(t>10 && t<11)']],
    plotList = [
        ['soma', '1', '.', 'Vm', 'Membrane potential'],
        ['#', '1', 'spine/Ca', 'conc', 'Ca in Spine'],
        ['#', '1', 'dend/DEND/Ca', 'conc', 'Ca in Dend'],
        ['#', '1', 'spine/Ca_CaM', 'conc', 'Ca_CaM'],
        ['head#', '1', 'psd/chan_p', 'conc', 'Phosph gluR'],
        ['head#', '1', 'psd/Ca_CaM_CaMKII', 'conc', 'Active CaMKII'],
    ]
)
moose.seed(123)
rdes.buildModel()
moose.reinit()
moose.start( 25 )

rdes.display()
def main():
    """
    Simulate pre and post Poisson firing for a synapse with
    Ca plasticity of Graupner and Brunel 2012.
    See the trace over time (lifetime) for the synaptic efficacy,
    similar to figure 2A of Higgins, Graupner, Brunel, 2014.

    Author: Aditya Gilra, NCBS, Bangalore, October, 2014.
    """

    numrepeats = 10         # repeat runtime for numrepeats

    frate = 1.0             # pre- and post-synaptic firing rate
                            # 1 Hz gives ~300s lifetime, ~0.2 efficacy (weight)
                            # 10 Hz gives ~10s lifetime, ~0.5 efficacy (weight)
                            # high firing rates make synaptic efficacy go to 0.5.
    runtime = 600.0/frate   # s

    #############################################
    # Ca Plasticity parameters: synapses (not for ExcInhNetBase)
    #############################################

    ## Cortical slice values -- Table Suppl 2 in Graupner & Brunel 2012
    ## Also used in Higgins et al 2014
    tauCa = 22.6936e-3      # s # Ca decay time scale
    tauSyn = 346.3615       # s # synaptic plasticity time scale
    ## in vitro values in Higgins et al 2014, faster plasticity
    CaPre = 0.56175         # mM
    CaPost = 1.2964         # mM
    ## in vivo values in Higgins et al 2014, slower plasticity
    #CaPre = 0.33705         # mM
    #CaPost = 0.74378        # mM
    delayD = 4.6098e-3      # s # CaPre is added to Ca after this delay
                            # proxy for rise-time of NMDA
    thetaD = 1.0            # mM # depression threshold for Ca
    thetaP = 1.3            # mM # potentiation threshold for Ca
    gammaD = 331.909        # factor for depression term
    gammaP = 725.085        # factor for potentiation term

    J = 5e-3 # V            # delta function synapse, adds to Vm
    weight = 0.43           # initial synaptic weight
                            # gammaP/(gammaP+gammaD) = eq weight w/o noise
                            # see eqn (22), noiseSD also appears
                            # but doesn't work here,
                            # weights away from 0.4 - 0.5 screw up the STDP rule!!

    bistable = True        # if bistable is True, use bistable potential for weights
    noisy = True           # use noisy weight updates given by noiseSD
    noiseSD = 3.3501        # if noisy, use noiseSD (3.3501 from Higgins et al 2014)

    ##########################################

    prePoisson = moose.RandSpike('/pre')
    prePoisson.rate = frate
    postPoisson = moose.RandSpike('/post')
    postPoisson.rate = frate

    syn = moose.GraupnerBrunel2012CaPlasticitySynHandler( '/syn' )
    syn.numSynapses = 1     # 1 synapse
                            # many pre-synaptic inputs can connect to a synapse

    # spikes from presynaptic Poisson generator
    moose.connect( prePoisson,'spikeOut', syn.synapse[0], 'addSpike')

    # post-synaptic spikes from postsynaptic Poisson generator
    moose.connect( postPoisson, 'spikeOut', syn, 'addPostSpike')

    syn.synapse[0].delay = 0.0
    syn.synapse[0].weight = 1.0 # starting weight to decay from
    syn.CaInit = 0.0
    syn.tauCa = tauCa
    syn.tauSyn = tauSyn
    syn.CaPre = CaPre
    syn.CaPost = CaPost
    syn.delayD = delayD
    syn.thetaD = thetaD
    syn.thetaP = thetaP
    syn.gammaD = gammaD
    syn.gammaP = gammaP
    syn.weightMax = 1.0     # bounds on the weight
    syn.weightMin = 0.

    syn.noisy = noisy
    syn.noiseSD = noiseSD
    syn.bistable = bistable

    # ###########################################
    # Setting up tables
    # ###########################################

    CaTable = moose.Table( '/plotCa', 1 )
    moose.connect( CaTable, 'requestOut', syn, 'getCa')
    WtTable = moose.Table( '/plotWeight', 1 )
    moose.connect( WtTable, 'requestOut', syn.synapse[0], 'getWeight')

    # ###########################################
    # Simulate
    # ###########################################

    dt = 1e-3 # s
    # moose simulation
    #moose.useClock( 0, '/syn', 'process' )
    #moose.useClock( 1, '/pre', 'process' )
    #moose.useClock( 1, '/post', 'process' )
    # I think MOOSE uses a different clock than 3 for Tables
    # anyway, we use the default one and set all clocks to dt below
    #moose.useClock( 3, '/plotCa', 'process' )
    #moose.useClock( 3, '/plotWeight', 'process' )
    ## use setClock to set the dt different from default dt
    for i in range(10):
        moose.setClock( i, dt )

    moose.seed(100)
    moose.reinit()

    # function to make the aPlus and aMinus settle to equilibrium values
    print(("Rates of pre- and post-syanptic neurons =",frate))
    WtSeries = []
    numsteps = int(runtime/dt)
    for i in range(numrepeats):
        syn.synapse[0].weight = 1.0 # starting weight to decay from
        syn.Ca = 0.0
        print(("Repeat number",i,"running..."))
        moose.start(runtime)
        WtSeries.append(WtTable.vector[i*numsteps:(i+1)*numsteps])
    WtSeries = array(WtSeries)
    WtMean = mean(WtSeries,axis=0)
    print("plotting...")

    # ###########################################
    # Plot the simulated weights and Ca vs time
    # ###########################################

    timeseries = linspace(0.0,runtime,numsteps)
    # Ca plots for the synapse
    # only the first repeat
    figure(facecolor='w')
    plot(timeseries,CaTable.vector[:numsteps],color='r')
    plot((timeseries[0],timeseries[-1]),(thetaP,thetaP),color='k',\
        linestyle='dashed',label='pot thresh')
    plot((timeseries[0],timeseries[-1]),(thetaD,thetaD),color='b',\
        linestyle='dashed',label='dep thresh')
    legend()
    xlabel('time (s)')
    ylabel('Ca (arb)')
    title("Ca conc in the synapse @ "+str(frate)+" Hz firing")

    # Weight plots for the synapse
    figure(facecolor='w')
    for i in range(numrepeats):
        plot(timeseries,WtSeries[i],alpha=0.5)
    plot(timeseries,WtMean,color='k',linewidth=2)
    xlabel('time (s)')
    ylabel('Efficacy')
    title("Efficacy of the synapse @ "+str(frate)+" Hz firing")

    show()
def main():
    """
Simulate pre and post Poisson firing for a synapse with
Ca plasticity of Graupner and Brunel 2012.
See the trace over time (lifetime) for the synaptic efficacy,
similar to figure 2A of Higgins, Graupner, Brunel, 2014.

Author: Aditya Gilra, NCBS, Bangalore, October, 2014.

    """

    prePoisson = moose.RandSpike('/pre')
    prePoisson.rate = frate
    postPoisson = moose.RandSpike('/post')
    postPoisson.rate = frate

    syn = moose.GraupnerBrunel2012CaPlasticitySynHandler( '/syn' )
    syn.numSynapses = 1     # 1 synapse
                            # many pre-synaptic inputs can connect to a synapse

    # spikes from presynaptic Poisson generator
    moose.connect( prePoisson,'spikeOut', syn.synapse[0], 'addSpike')

    # post-synaptic spikes from postsynaptic Poisson generator
    moose.connect( postPoisson, 'spikeOut', syn, 'addPostSpike')

    syn.synapse[0].delay = 0.0
    syn.synapse[0].weight = 1.0 # starting weight to decay from
    syn.CaInit = 0.0
    syn.tauCa = tauCa
    syn.tauSyn = tauSyn
    syn.CaPre = CaPre
    syn.CaPost = CaPost
    syn.delayD = delayD
    syn.thetaD = thetaD
    syn.thetaP = thetaP
    syn.gammaD = gammaD
    syn.gammaP = gammaP
    syn.weightMax = 1.0     # bounds on the weight
    syn.weightMin = 0.

    syn.noisy = noisy
    syn.noiseSD = noiseSD
    syn.bistable = bistable

    # ###########################################
    # Setting up tables
    # ###########################################

    CaTable = moose.Table( '/plotCa', 1 )
    moose.connect( CaTable, 'requestOut', syn, 'getCa')
    WtTable = moose.Table( '/plotWeight', 1 )
    moose.connect( WtTable, 'requestOut', syn.synapse[0], 'getWeight')

    # ###########################################
    # Simulate
    # ###########################################

    dt = 1e-3 # s
    # moose simulation
    #moose.useClock( 0, '/syn', 'process' )
    #moose.useClock( 1, '/pre', 'process' )
    #moose.useClock( 1, '/post', 'process' )
    # I think MOOSE uses a different clock than 3 for Tables
    # anyway, we use the default one and set all clocks to dt below
    #moose.useClock( 3, '/plotCa', 'process' )
    #moose.useClock( 3, '/plotWeight', 'process' )
    ## use setClock to set the dt different from default dt
    for i in range(10):
        moose.setClock( i, dt )

    moose.seed(100)
    moose.reinit()

    # function to make the aPlus and aMinus settle to equilibrium values
    print(("Rates of pre- and post-syanptic neurons =",frate))
    WtSeries = []
    numsteps = int(runtime/dt)
    for i in range(numrepeats):
        syn.synapse[0].weight = 1.0 # starting weight to decay from
        syn.Ca = 0.0
        print(("Repeat number",i,"running..."))
        moose.start(runtime)
        WtSeries.append(WtTable.vector[i*numsteps:(i+1)*numsteps])
    WtSeries = array(WtSeries)
    WtMean = mean(WtSeries,axis=0)
    print("plotting...")

    # ###########################################
    # Plot the simulated weights and Ca vs time
    # ###########################################

    timeseries = linspace(0.0,runtime,numsteps)
    # Ca plots for the synapse
    # only the first repeat
    figure(facecolor='w')
    plot(timeseries,CaTable.vector[:numsteps],color='r')
    plot((timeseries[0],timeseries[-1]),(thetaP,thetaP),color='k',\
        linestyle='dashed',label='pot thresh')
    plot((timeseries[0],timeseries[-1]),(thetaD,thetaD),color='b',\
        linestyle='dashed',label='dep thresh')
    legend()
    xlabel('time (s)')
    ylabel('Ca (arb)')
    title("Ca conc in the synapse @ "+str(frate)+" Hz firing")

    # Weight plots for the synapse
    figure(facecolor='w')
    for i in range(numrepeats):
        plot(timeseries,WtSeries[i],alpha=0.5)
    plot(timeseries,WtMean,color='k',linewidth=2)
    xlabel('time (s)')
    ylabel('Efficacy')
    title("Efficacy of the synapse @ "+str(frate)+" Hz firing")

    show()
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.\n
    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()
Example #34
0
def main():
    """
    This example sets up the kinetic solver and steady-state finder, on
    a bistable model of a chemical system. The model is set up within the
    script.
    The algorithm calls the steady-state finder 50 times with different
    (randomized) initial conditions, as follows:

    * Set up the random initial condition that fits the conservation laws
    * Run for 2 seconds. This should not be mathematically necessary, but
      for obscure numerical reasons it makes it much more likely that the
      steady state solver will succeed in finding a state.
    * Find the fixed point
    * Print out the fixed point vector and various diagnostics.
    * Run for 10 seconds. This is completely unnecessary, and is done here
      just so that the resultant graph will show what kind of state has
      been  found.

    After it does all this, the program runs for 100 more seconds on the
    last found fixed point (which turns out to be a saddle node), then
    is hard-switched in the script to the first attractor basin from which
    it runs for another 100 seconds till it settles there, and then
    is hard-switched yet again to the second attractor and runs for 400
    seconds.

    Looking at the output you will see many features of note:

    * the first attractor (stable point) and the saddle point (unstable
      fixed point) are both found quite often. But the second
      attractor is found just once.
      It has a very small basin of attraction.
    * The values found for each of the fixed points match well with the
      values found by running the system to steady-state at the end.
    * There are a large number of failures to find a fixed point. These are
      found and reported in the diagnostics. They show up on the plot
      as cases where the 10-second runs are not flat.

    If you wanted to find fixed points in a production model, you would
    not need to do the 10-second runs, and you would need to eliminate the
    cases where the state-finder failed. Then you could identify the good
    points and keep track of how many of each were found.

    There is no way to guarantee that all fixed points have been found
    using this algorithm! If there are points in an obscure corner of state
    space (as for the singleton second attractor convergence in this
    example) you may have to iterate very many times to find them.

    You may wish to sample concentration space logarithmically rather than
    linearly.
    """
    compartment = makeModel()
    ksolve = moose.Ksolve( '/model/compartment/ksolve' )
    stoich = moose.Stoich( '/model/compartment/stoich' )
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState( '/model/compartment/state' )

    moose.reinit()
    state.stoich = stoich
    state.showMatrices()
    state.convergenceCriterion = 1e-6
    moose.seed( 111 ) # Used when generating the samples in state space

    for i in range( 0, 50 ):
        getState( ksolve, state )

    # Now display the states of the system at more length to compare.
    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( 400.0 ) # Run the model for 200 seconds.

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

    quit()
Example #35
0
def main():
    """
    This example builds a dose-response of a bistable model of a chemical
    system. It uses the kinetic solver *Ksolve* and the steady-state finder
    *SteadyState*.
    The model is set up within the script.

    The basic approach is to increment the control variable, **a** in this
    case, while monitoring **b**.
    The algorithm marches through a series of values of the buffered pool 
    **a** and measures resultant values of pool **b**. At each cycle
    the algorithm calls the steady-state finder. Since **a** is incremented
    only a small amount on each step, each new steady state is 
    (usually) quite close to the previous one. The exception is when there
    is a state transition. 

    Here we plot three dose-response curves to illustrate the bistable
    nature of the system. 

    On the upward going curve in blue, **a** starts low. Here, 
    **b** follows the low arm of the curve
    and then jumps up to the high value at roughly *log( [a] ) = -0.55*.

    On the downward going curve in green, **b** follows the high arm
    of the curve forming a nice hysteretic loop.
    Eventually **b** has to fall to the low state at about 
    *log( [a] ) = -0.83*

    Through nasty concentration manipulations, we find the third arm 
    of the curve, which tracks the unstable fixed point. This is in red.
    We find this arm by
    setting an initial point close to the unstable fixed point, which
    the steady-state finder duly locates. We then follow a dose-response
    curve as with the other arms of the curve. 

    Note that the steady-state solver doesn't always succeed in finding a
    good solution, despite moving only in small steps. Nevertheless the
    resultant curves are smooth because it gives up pretty close to the
    correct value, simply because the successive points are close together.
    Overall, the system is pretty robust despite the core root-finder
    computations in GSL being temperamental.

    In doing a production dose-response series
    you may wish to sample concentration space logarithmically rather than
    linearly.
    """
    compartment = makeModel()
    ksolve = moose.Ksolve( '/model/compartment/ksolve' )
    stoich = moose.Stoich( '/model/compartment/stoich' )
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState( '/model/compartment/state' )

    moose.reinit()
    state.stoich = stoich
    state.convergenceCriterion = 1e-6
    moose.seed( 111 ) # Used when generating the samples in state space

    b = moose.element( '/model/compartment/b' )
    a = moose.element( '/model/compartment/a' )
    a.concInit = 0.1
    deltaA = 0.002
    num = 150
    avec = []
    bvec = []
    moose.reinit()

    # Now go up.
    for i in range( 0, num ):
        moose.start( 1.0 ) # Run the model for 1 seconds.
        state.settle() # This function finds the steady states.
        avec.append( a.conc )
        bvec.append( b.conc )
        a.concInit += deltaA
        print i, a.conc, b.conc
    pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a up' )
    # Now go down.
    avec = []
    bvec = []
    for i in range( 0, num ):
        moose.start( 1.0 ) # Run the model for 1 seconds.
        state.settle() # This function finds the steady states.
        avec.append( a.conc )
        bvec.append( b.conc )
        a.concInit -= deltaA
        print i, a.conc, b.conc


    pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a down' )
    # Now aim for the middle. We do this by judiciously choosing a 
    # start point that should be closer to the unstable fixed point.
    avec = []
    bvec = []
    a.concInit = 0.28
    b.conc = 0.15
    for i in range( 0, 65 ):
        moose.start( 1.0 ) # Run the model for 1 seconds.
        state.settle() # This function finds the steady states.
        avec.append( a.conc )
        bvec.append( b.conc )
        a.concInit -= deltaA
        print i, a.conc, b.conc
    pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a mid' )

    pylab.ylim( [-1.7, 1.2] )
    pylab.legend()
    pylab.show()

    quit()
Example #36
0
def main():
    """
    This example illustrates how to run a model at different volumes.
    The key line is just to set the volume of the compartment::

        compt.volume = vol

    If everything
    else is set up correctly, then this change propagates through to all
    reactions molecules.

    For a deterministic reaction one would not see any change in output 
    concentrations.
    For a stochastic reaction illustrated here, one sees the level of 
    'noise' 
    changing, even though the concentrations are similar up to a point.
    This example creates a bistable model having two enzymes and a reaction.
    One of the enzymes is autocatalytic.
    This model is set up within the script rather than using an external 
    file.
    The model is set up to run using the GSSA (Gillespie Stocahstic systems
    algorithim) method in MOOSE.

    To run the example, run the script

        ``python scaleVolumes.py``

    and hit ``enter`` every cycle to see the outcome of stochastic
    calculations at ever smaller volumes, keeping concentrations the same.
    """
    makeModel()
    moose.seed(11111)
    gsolve = moose.Gsolve('/model/compartment/gsolve')
    stoich = moose.Stoich('/model/compartment/stoich')
    compt = moose.element('/model/compartment')
    stoich.compartment = compt
    stoich.ksolve = gsolve
    stoich.path = "/model/compartment/##"
    moose.setClock(5, 1.0)  # clock for the solver
    moose.useClock(5, '/model/compartment/gsolve', 'process')
    a = moose.element('/model/compartment/a')

    for vol in (1e-19, 1e-20, 1e-21, 3e-22, 1e-22, 3e-23, 1e-23):
        # Set the volume
        compt.volume = vol
        print(('vol = ', vol, ', a.concInit = ', a.concInit, ', a.nInit = ',
               a.nInit))

        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.
        displayPlots()
        pylab.show(block=False)
        print(('vol = ', vol, 'hit enter to go to next plot'))
        input()

    quit()
    addSomaChemCompt = False,
    addEndoChemCompt = True,
    # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSeg]
    cellProto = [['ballAndStick', 'soma', 10e-6, 10e-6, 2e-6, 40e-6, 4]],
    spineProto = [['makeActiveSpine()', 'spine']],
    chemProto = [['./chem/CICRspineDend.g', 'chem']],
    spineDistrib = [['spine', '#dend#', '10e-6', '0.1e-6']],
    chemDistrib = [['chem', 'dend#,spine#,head#', 'install', '1' ]],
    adaptorList = [
        [ 'Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8 ]
    ],
    stimList = [
        ['head0', '0.5', 'glu', 'periodicsyn', '1 + 40*(t>5 && t<6)'],
        ['head0', '0.5', 'NMDA', 'periodicsyn', '1 + 40*(t>5 && t<6)'],
        ['dend#',  'g>10e-6 && g<=31e-6', 'dend/IP3', 'conc', '0.0006' ],
        ],
    plotList = [
        ['head#', '1', 'spine/Ca', 'conc', 'Spine Ca conc'],
        ['dend#', '1', 'dend/Ca', 'conc', 'Dend Ca conc'],
        ['dend#', '1', 'dend/Ca', 'conc', 'Dend Ca conc', 'wave'],
        ['dend#', '1', 'dend_endo/CaER', 'conc', 'ER Ca conc', 'wave'],
        ['soma', '1', '.', 'Vm', 'Memb potl'],
    ],
)

moose.seed( 1234 )
rdes.buildModel()
moose.reinit()
moose.start( 16 )
rdes.display()
Example #38
0
    cellProto=[['ballAndStick', 'soma', 12e-6, 12e-6, 4e-6, 100e-6, 1]],
    chemProto=[['../chem/CaMKII_MAPK_7.g', 'chem']],
    spineProto=[['makeActiveSpine()', 'spine']],
    chanProto=[['make_Na()', 'Na'], ['make_K_DR()', 'K_DR'],
               ['make_K_A()', 'K_A'], ['make_glu()', 'glu'],
               ['make_Ca()', 'Ca'], ['make_Ca_conc()', 'Ca_conc']],
    passiveDistrib=[['soma', 'CM', '0.01', 'Em', '-0.06']],
    spineDistrib=[['spine', '#dend#', '100e-6', '1e-6']],
    chemDistrib=[['chem', '#', 'install', '1']],
    chanDistrib=[['Na', 'soma', 'Gbar',
                  '300'], ['K_DR', 'soma', 'Gbar', '250'],
                 ['K_A', 'soma', 'Gbar', '200'],
                 ['glu', 'dend#', 'Gbar', '20'],
                 ['Ca_conc', 'soma', 'tau', '0.0333'],
                 ['Ca', 'soma', 'Gbar', '40']],
    adaptorList=[['psd/tot_phospho_R', 'n', 'glu', 'modulation', 1.0, 0.3],
                 ['Ca_conc', 'Ca', 'psd/Ca', 'conc', 0.00008, 3]],
    # Syn wt is 0.2, specified in 2nd argument
    stimList=[['head#', '0.2', 'glu', 'periodicsyn', '0']],
)
moose.seed(1234567)
rdes.buildModel()
moose.delete('/model/stims/stim0')
inputElm = moose.element('/model/elec/head0/glu/sh/synapse/synInput_rs')
inputElm.name = 'synInput'
moose.connect(inputElm, 'spikeOut', '/model/elec/head0/glu/sh/synapse',
              'addSpike')
#moose.showmsg( '/model/elec/head0/glu/sh/synapse/synInput_rs' )
import presettle_CaMKII_MAPK7_init
moose.reinit()
Example #39
0
def main():

    """
    This example illustrates how to run a model at different volumes.
    The key line is just to set the volume of the compartment::

        compt.volume = vol

    If everything
    else is set up correctly, then this change propagates through to all
    reactions molecules.

    For a deterministic reaction one would not see any change in output
    concentrations.
    For a stochastic reaction illustrated here, one sees the level of
    'noise'
    changing, even though the concentrations are similar up to a point.
    This example creates a bistable model having two enzymes and a reaction.
    One of the enzymes is autocatalytic.
    This model is set up within the script rather than using an external
    file.
    The model is set up to run using the GSSA (Gillespie Stocahstic systems
    algorithim) method in MOOSE.

    To run the example, run the script

        ``python scaleVolumes.py``

    and hit ``enter`` every cycle to see the outcome of stochastic
    calculations at ever smaller volumes, keeping concentrations the same.
    """
    makeModel()
    moose.seed( 11111 )
    gsolve = moose.Gsolve( '/model/compartment/gsolve' )
    stoich = moose.Stoich( '/model/compartment/stoich' )
    compt = moose.element( '/model/compartment' );
    stoich.compartment = compt
    stoich.ksolve = gsolve
    stoich.path = "/model/compartment/##"
    #moose.setClock( 5, 1.0 ) # clock for the solver
    #moose.useClock( 5, '/model/compartment/gsolve', 'process' )
    a = moose.element( '/model/compartment/a' )

    for vol in ( 1e-19, 1e-20, 1e-21, 3e-22, 1e-22, 3e-23, 1e-23 ):
        # Set the volume
        compt.volume = vol
        print(('vol = ', vol, ', a.concInit = ', a.concInit, ', a.nInit = ', a.nInit))

        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.
        displayPlots()
        pylab.show( block=False )
        print(('vol = ', vol, 'hit 0 to go to next plot'))
        eval(str(input()))

    quit()
    chanProto=[['make_Na()', 'Na'], ['make_K_DR()', 'K_DR'],
               ['make_K_A()', 'K_A'], ['make_Ca()', 'Ca'],
               ['make_Ca_conc()', 'Ca_conc']],
    passiveDistrib=[['soma', 'CM', '0.01', 'Em', '-0.06']],
    spineDistrib=[['spine', '#dend#', '50e-6', '1e-6']],
    chemDistrib=[['chem', '#', 'install', '1']],
    chanDistrib=[['Na', 'soma', 'Gbar',
                  '300'], ['K_DR', 'soma', 'Gbar', '250'],
                 ['K_A', 'soma', 'Gbar', '200'],
                 ['Ca_conc', 'soma', 'tau', '0.0333'],
                 ['Ca', 'soma', 'Gbar', '40']],
    adaptorList=[['psd/chan_p', 'n', 'glu', 'modulation', 0.1, 1.0],
                 ['Ca_conc', 'Ca', 'spine/Ca', 'conc', 0.00008, 8]],
    # Syn input basline 1 Hz, and 40Hz burst for 1 sec at t=20. Syn weight
    # is 0.5, specified in 2nd argument as a special case stimLists.
    stimList=[['head#', '0.5', 'glu', 'periodicsyn', '1 + 40*(t>10 && t<11)']],
    plotList=[
        ['soma', '1', '.', 'Vm', 'Membrane potential'],
        ['#', '1', 'spine/Ca', 'conc', 'Ca in Spine'],
        ['#', '1', 'dend/DEND/Ca', 'conc', 'Ca in Dend'],
        ['#', '1', 'spine/Ca_CaM', 'conc', 'Ca_CaM'],
        ['head#', '1', 'psd/chan_p', 'conc', 'Phosph gluR'],
        ['head#', '1', 'psd/Ca_CaM_CaMKII', 'conc', 'Active CaMKII'],
    ])
moose.seed(123)
rdes.buildModel()
moose.reinit()
moose.start(25)

rdes.display()
def main():
    """
    This example builds a dose-response of a bistable model of a chemical
    system. It uses the kinetic solver *Ksolve* and the steady-state finder
    *SteadyState*.
    The model is set up within the script.

    The basic approach is to increment the control variable, **a** in this
    case, while monitoring **b**.
    The algorithm marches through a series of values of the buffered pool 
    **a** and measures resultant values of pool **b**. At each cycle
    the algorithm calls the steady-state finder. Since **a** is incremented
    only a small amount on each step, each new steady state is 
    (usually) quite close to the previous one. The exception is when there
    is a state transition. 

    Here we plot three dose-response curves to illustrate the bistable
    nature of the system. 

    On the upward going curve in blue, **a** starts low. Here, 
    **b** follows the low arm of the curve
    and then jumps up to the high value at roughly *log( [a] ) = -0.55*.

    On the downward going curve in green, **b** follows the high arm
    of the curve forming a nice hysteretic loop.
    Eventually **b** has to fall to the low state at about 
    *log( [a] ) = -0.83*

    Through nasty concentration manipulations, we find the third arm 
    of the curve, which tracks the unstable fixed point. This is in red.
    We find this arm by
    setting an initial point close to the unstable fixed point, which
    the steady-state finder duly locates. We then follow a dose-response
    curve as with the other arms of the curve. 

    Note that the steady-state solver doesn't always succeed in finding a
    good solution, despite moving only in small steps. Nevertheless the
    resultant curves are smooth because it gives up pretty close to the
    correct value, simply because the successive points are close together.
    Overall, the system is pretty robust despite the core root-finder
    computations in GSL being temperamental.

    In doing a production dose-response series
    you may wish to sample concentration space logarithmically rather than
    linearly.
    """
    compartment = makeModel()
    ksolve = moose.Ksolve( '/model/compartment/ksolve' )
    stoich = moose.Stoich( '/model/compartment/stoich' )
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState( '/model/compartment/state' )

    moose.reinit()
    state.stoich = stoich
    state.convergenceCriterion = 1e-6
    moose.seed( 111 ) # Used when generating the samples in state space

    b = moose.element( '/model/compartment/b' )
    a = moose.element( '/model/compartment/a' )
    c = moose.element( '/model/compartment/c' )
    a.concInit = 0.1
    deltaA = 0.002
    num = 150
    avec = []
    bvec = []
    moose.reinit()

    # Now go up.
    for i in range( 0, num ):
        moose.start( 1.0 ) # Run the model for 1 seconds.
        state.settle() # This function finds the steady states.
        avec.append( a.conc )
        bvec.append( b.conc )
        a.concInit += deltaA
        #print i, a.conc, b.conc
    pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a up' )
    # Now go down.
    avec = []
    bvec = []
    for i in range( 0, num ):
        moose.start( 1.0 ) # Run the model for 1 seconds.
        state.settle() # This function finds the steady states.
        avec.append( a.conc )
        bvec.append( b.conc )
        a.concInit -= deltaA
        #print i, a.conc, b.conc


    pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a down' )
    # Now aim for the middle. We do this by judiciously choosing a 
    # start point that should be closer to the unstable fixed point.
    avec = []
    bvec = []
    a.concInit = 0.28
    b.conc = 0.15
    for i in range( 0, 65 ):
        moose.start( 1.0 ) # Run the model for 1 seconds.
        state.settle() # This function finds the steady states.
        avec.append( a.conc )
        bvec.append( b.conc )
        a.concInit -= deltaA
        #print i, a.conc, b.conc
    pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a mid' )

    pylab.ylim( [-1.7, 1.2] )
    pylab.legend()
    pylab.show()
def main():
    compartment = makeModel()
    ksolve = moose.Ksolve('/model/compartment/ksolve')
    stoich = moose.Stoich('/model/compartment/stoich')
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState('/model/compartment/state')

    moose.reinit()
    state.stoich = stoich
    state.convergenceCriterion = 1e-6
    moose.seed(111)  # Used when generating the samples in state space

    b = moose.element('/model/compartment/b')
    a = moose.element('/model/compartment/a')
    c = moose.element('/model/compartment/c')
    a.concInit = 0.1
    deltaA = 0.002
    num = 150
    avec = []
    bvec = []
    moose.reinit()

    # Now go up.
    for i in range(0, num):
        moose.start(1.0)  # Run the model for 1 seconds.
        state.settle()  # This function finds the steady states.
        avec.append(a.conc)
        bvec.append(b.conc)
        a.concInit += deltaA

    aa, bb = avec, bvec
    got = np.mean(aa), np.std(aa)
    expected = 0.24899, 0.08660
    assert np.isclose(got, expected,
                      atol=1e-4).all(), "Got %s, expected %s" % (got, expected)
    print("[INFO ] Test 1 PASSED")

    # Now go down.
    avec = []
    bvec = []
    for i in range(0, num):
        moose.start(1.0)  # Run the model for 1 seconds.
        state.settle()  # This function finds the steady states.
        avec.append(a.conc)
        bvec.append(b.conc)
        a.concInit -= deltaA

    aa, bb = avec, bvec
    got = np.mean(aa), np.std(aa)
    expected = 0.251, 0.0866
    assert np.isclose(got, expected,
                      atol=1e-4).all(), "Got %s, expected %s" % (got, expected)
    print("[INFO ] Test 2 PASSED")

    # Now aim for the middle. We do this by judiciously choosing a
    # start point that should be closer to the unstable fixed point.
    avec = []
    bvec = []
    a.concInit = 0.28
    b.conc = 0.15
    for i in range(0, 65):
        moose.start(1.0)  # Run the model for 1 seconds.
        state.settle()  # This function finds the steady states.
        avec.append(a.conc)
        bvec.append(b.conc)
        a.concInit -= deltaA

    aa, bb = avec, bvec
    got = np.mean(aa), np.std(aa)
    expected = 0.216, 0.03752
    assert np.isclose(got, expected,
                      atol=1e-4).all(), "Got %s, expected %s" % (got, expected)
    print("[INFO ] Test 3 PASSED")
    quit()
Example #43
0
# ###########################################

dt = 1e-3  # s
# moose simulation
moose.useClock(0, '/syn', 'process')
moose.useClock(1, '/pre', 'process')
moose.useClock(1, '/post', 'process')
moose.useClock(3, '/plotCa', 'process')
moose.useClock(3, '/plotWeight', 'process')
moose.setClock(0, dt)
moose.setClock(1, dt)
moose.setClock(2, dt)
moose.setClock(3, dt)
moose.setClock(9, dt)

moose.seed(100)
moose.reinit()

# function to make the aPlus and aMinus settle to equilibrium values
print "Rates of pre- and post-syanptic neurons =", frate
WtSeries = []
numsteps = int(runtime / dt)
for i in range(numrepeats):
    syn.synapse[0].weight = 1.0  # starting weight to decay from
    syn.Ca = 0.0
    print "Repeat number", i, "running..."
    moose.start(runtime)
    WtSeries.append(WtTable.vector[i * numsteps:(i + 1) * numsteps])
WtSeries = array(WtSeries)
WtMean = mean(WtSeries, axis=0)
print "plotting..."
# ###########################################

dt = 1e-3 # s
# moose simulation
#moose.useClock( 0, '/syn', 'process' )
#moose.useClock( 1, '/pre', 'process' )
#moose.useClock( 1, '/post', 'process' )
# I think MOOSE uses a different clock than 3 for Tables
# anyway, we use the default one and set all clocks to dt below
#moose.useClock( 3, '/plotCa', 'process' )
#moose.useClock( 3, '/plotWeight', 'process' )
## use setClock to set the dt different from default dt
for i in range(10):
    moose.setClock( i, dt )

moose.seed(100)
moose.reinit()

# function to make the aPlus and aMinus settle to equilibrium values
print(("Rates of pre- and post-syanptic neurons =",frate))
WtSeries = []
numsteps = int(runtime/dt)
for i in range(numrepeats):
    syn.synapse[0].weight = 1.0 # starting weight to decay from
    syn.Ca = 0.0
    print(("Repeat number",i,"running..."))
    moose.start(runtime)
    WtSeries.append(WtTable.vector[i*numsteps:(i+1)*numsteps])
WtSeries = array(WtSeries)
WtMean = mean(WtSeries,axis=0)
print("plotting...")