コード例 #1
0
ファイル: test_pymoose_2.py プロジェクト: dilawar/moose
def library1():
    import moose.genesis
    import moose.SBML
    import moose.chemMerge
    import moose.utils
    import moose.network_utils
    print('done')

    p1 = moose.le()
    a = moose.Pool('/a')
    for i in range(10):
        moose.Pool('/a/p%d' % i)
    p2 = moose.le()
    assert set(p2) - set(p1) == set(['/a'])
    aa = moose.le(a)
    assert len(aa) == 10

    try:
        moose.syncDataHandler('/a')
    except NotImplementedError:
        pass

    try:
        moose.showfield('/x')
    except ValueError:
        pass

    moose.showfield('/a')
    moose.showfields('/a')
コード例 #2
0
def main():
        """
        This example illustrates loading and running a reaction system that
        spans two volumes, that is, is in different compartments. It uses a
        kkit model file. You can tell if it is working if you see nice 
        relaxation oscillations.
        """
        # the kkit reader doesn't know how to do multicompt solver setup.
        solver = "ee"  
	mfile = '../Genesis_files/OSC_diff_vols.g'
	runtime = 3000.0
        simDt = 1.0
	modelId = moose.loadModel( mfile, 'model', solver )
        #moose.delete( '/model/kinetics/A/Stot' )
        compt0 = moose.element( '/model/kinetics' )
        compt1 = moose.element( '/model/compartment_1' )
        assert( deq( compt0.volume, 2e-20 ) )
        assert( deq( compt1.volume, 1e-20 ) )
        dy = compt0.dy
        compt1.y1 += dy
        compt1.y0 = dy
        assert( deq( compt1.volume, 1e-20 ) )
        # We now have two cubes adjacent to each other. Compt0 has 2x vol.
        # Compt1 touches it.
        stoich0 = moose.Stoich( '/model/kinetics/stoich' )
        stoich1 = moose.Stoich( '/model/compartment_1/stoich' )
        ksolve0 = moose.Ksolve( '/model/kinetics/ksolve' )
        ksolve1 = moose.Ksolve( '/model/compartment_1/ksolve' )
        stoich0.compartment = compt0
        stoich0.ksolve = ksolve0
        stoich0.path = '/model/kinetics/##'
        stoich1.compartment = compt1
        stoich1.ksolve = ksolve1
        stoich1.path = '/model/compartment_1/##'
        #stoich0.buildXreacs( stoich1 )
        print ksolve0.numLocalVoxels, ksolve0.numPools, stoich0.numAllPools
        assert( ksolve0.numLocalVoxels == 1 )
        assert( ksolve0.numPools == 7 )
        assert( stoich0.numAllPools == 6 )
        print len( stoich0.proxyPools[stoich1] ),
        print len( stoich1.proxyPools[stoich0] )
        assert( len( stoich0.proxyPools[stoich1] ) == 1 )
        assert( len( stoich1.proxyPools[stoich0] ) == 1 )
        print ksolve1.numLocalVoxels, ksolve1.numPools, stoich1.numAllPools
        assert( ksolve1.numLocalVoxels == 1 )
        assert( ksolve1.numPools == 6 )
        assert( stoich1.numAllPools == 5 )
        stoich0.buildXreacs( stoich1 )
        print moose.element( '/model/kinetics/endo' )
        print moose.element( '/model/compartment_1/exo' )
        moose.le( '/model/compartment_1' )
	moose.reinit()
	moose.start( runtime ) 

	# Display all plots.
	for x in moose.wildcardFind( '/model/#graphs/conc#/#' ):
            t = numpy.arange( 0, x.vector.size, 1 ) * simDt
            pylab.plot( t, x.vector, label=x.name )
        pylab.legend()
        pylab.show()
コード例 #3
0
ファイル: testSigNeur.py プロジェクト: Vivek-sagar/moose-1
def testChemAlone():
    nid = makeChemInCubeMesh()
    moose.le( '/n' )
    makeChemPlots()
    moose.setClock( 5, 1e-2 )
    moose.setClock( 6, 1e-2 )
    moose.setClock( 7, 1.0 )
    moose.setClock( 8, 1.0 )
    moose.setClock( 9, 1.0 )
    moose.useClock( 5, '/n/##', 'init' )
    moose.useClock( 6, '/n/##', 'process' )
    #moose.useClock( 7, '/graphs/#', 'process' )
    moose.useClock( 8, '/graphs/#', 'process' )
    moose.reinit()
    moose.start( 100 )
    dumpPlots( 'chem.plot' )
    # Make ksolver and rerun.
    ksolve = moose.GslStoich( '/n/solver' )
    ksolve.path = '/n/##'
    ksolve.method = 'rk5'
    moose.useClock( 5, '/n/solver', 'process' )
    moose.setClock( 5, 1 )
    moose.setClock( 6, 1 )
    moose.reinit()
    moose.start( 100 )
    dumpPlots( 'kchem.plot' )
コード例 #4
0
ファイル: hw9.py プロジェクト: golddove/neur634
def main():
    simtime = 1
    simdt = 0.25e-5
    plotdt = 0.25e-3
    for i in range(10):
        moose.setClock(i, simdt)
    moose.setClock(8, plotdt)

    model = moose.Neutral('/model')
    comp = create_1comp_neuron('/model/neuron')
    sh, preSyns = createRandomSynapse(comp, "excitatory", 0, 10)
    sh2, preSyns2 = createRandomSynapse(comp, "inhibitory", -80, 2)
    moose.le("/model/neuron")

    # stim = create_pulse("/model/stimulus", 20e-3, 40e-3, 1e-9, comp)

    data = moose.Neutral('/data')
    preTables = []
    for i, preSyn in enumerate(preSyns):
        print(i)
        print(preSyn)
        preTables.append(create_spike_table("/data/pre" + str(i), preSyn))

    moose.reinit()
    moose.start(simtime)

    plot_spike_tables(preTables)

    # current_tab = create_table("/data/current", stim, "getOutputValue")
    vm_tab = create_table("/data/Vm", comp, "getVm")
    moose.reinit()
    moose.start(simtime)
    #ts = np.linspace(0, simtime, len(vm_tab.vector))
    plot_table(vm_tab)  #, current_tab
コード例 #5
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()
コード例 #6
0
ファイル: testHsolve.py プロジェクト: AdrianW15/moose
def test_elec_alone():
    eeDt = 2e-6
    hSolveDt = 2e-5
    runTime = 0.02

    make_spiny_compt()
    make_elec_plots()
    head2 = moose.element( '/n/head2' )
    moose.setClock( 0, 2e-6 )
    moose.setClock( 1, 2e-6 )
    moose.setClock( 2, 2e-6 )
    moose.setClock( 8, 0.1e-3 )
    moose.useClock( 0, '/n/##[ISA=Compartment]', 'init' )
    moose.useClock( 1, '/n/##[ISA=Compartment]', 'process' )
    moose.useClock( 2, '/n/##[ISA=ChanBase],/n/##[ISA=SynBase],/n/##[ISA=CaConc],/n/##[ISA=SpikeGen]','process')
    moose.useClock( 8, '/graphs/elec/#', 'process' )
    moose.reinit()
    moose.start( runTime )
    dump_plots( 'instab.png' )
    # make Hsolver and rerun
    hsolve = moose.HSolve( '/n/hsolve' )
    moose.useClock( 1, '/n/hsolve', 'process' )
    hsolve.dt = 20e-6
    hsolve.target = '/n/compt'
    moose.le( '/n' )
    for dt in ( 20e-6, 50e-6, 100e-6 ):
        print(('running at dt =', dt))
        moose.setClock( 0, dt )
        moose.setClock( 1, dt )
        moose.setClock( 2, dt )
        hsolve.dt = dt
        moose.reinit()
        moose.start( runTime )
        dump_plots( 'h_instab' + str( dt ) + '.png' )
コード例 #7
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']],
        plotList=[
            ['soma', '1', 'dend/A', 'n', '# of A'],
            ['soma', '1', 'dend/B', 'n', '# of B'],
        ],
        #    moogList = [['soma', '1', 'dend/A', 'n', 'num of A (number)']]
    )
    moose.le('/library')
    moose.le('/library/hydra')
    #moose.showfield( '/library/soma/soma' )
    rdes.buildModel()
    #moose.element('/model/chem/dend/B').vec[50].nInit=15.5

    A = moose.element('/model/chem/dend/A')
    B = moose.element('/model/chem/dend/B')
    C = moose.element('/model/chem/dend/C')

    A.diffConst = 1e-13
    B.diffConst = 50 * 1e-12
    C.diffConst = 0.8 * 1e-12
    avec = moose.vec('/model/chem/dend/A').n
    savec = avec.size
    randper = np.random.uniform(1, 2, savec)
    #for i in range(0,savec-1,1):
    #moose.element('/model/chem/dend/A').vec[i].nInit = randper[i]

    moose.element('/model/chem/dend/A').vec[50].nInit = 100
    moose.element('/model/chem/dend/B').vec[50].nInit = 100
    moose.element('/model/chem/dend/C').vec.nInit = 0
    storeAvec = []
    storeBvec = []
    storeCvec = []

    moose.reinit()
    for i in range(1, 4000, 10):
        moose.start(10)
        avec = moose.vec('/model/chem/dend/A').n
        bvec = moose.vec('/model/chem/dend/B').n
        cvec = moose.vec('/model/chem/dend/C').n
        storeAvec.append(avec)
        storeBvec.append(bvec)
        storeCvec.append(cvec)

    trialNum = '1'
    fileName = 'mechano.xml'
    writeXML(storeAvec, trialNum, fileName)

    return storeAvec, storeBvec, storeCvec
コード例 #8
0
ファイル: testHsolve.py プロジェクト: csiki/MOOSE
def test_elec_alone():
    eeDt = 2e-6
    hSolveDt = 2e-5
    runTime = 0.02

    make_spiny_compt()
    make_elec_plots()
    head2 = moose.element( '/n/head2' )
    moose.setClock( 0, 2e-6 )
    moose.setClock( 1, 2e-6 )
    moose.setClock( 2, 2e-6 )
    moose.setClock( 8, 0.1e-3 )
    moose.useClock( 0, '/n/##[ISA=Compartment]', 'init' )
    moose.useClock( 1, '/n/##[ISA=Compartment]', 'process' )
    moose.useClock( 2, '/n/##[ISA=ChanBase],/n/##[ISA=SynBase],/n/##[ISA=CaConc],/n/##[ISA=SpikeGen]','process')
    moose.useClock( 8, '/graphs/elec/#', 'process' )
    moose.reinit()
    moose.start( runTime )
    dump_plots( 'instab.plot' )
    print "||||", len(moose.wildcardFind('/##[ISA=HHChannel]'))
    # make Hsolver and rerun
    hsolve = moose.HSolve( '/n/hsolve' )
    moose.useClock( 1, '/n/hsolve', 'process' )
    hsolve.dt = 20e-6
    hsolve.target = '/n/compt'
    moose.le( '/n' )
    for dt in ( 20e-6, 50e-6, 100e-6 ):
        print 'running at dt =', dt
        moose.setClock( 0, dt )
        moose.setClock( 1, dt )
        moose.setClock( 2, dt )
        hsolve.dt = dt
        moose.reinit()
        moose.start( runTime )
        dump_plots( 'h_instab' + str( dt ) + '.plot' )
コード例 #9
0
def main():
    """
        This example illustrates loading and running a reaction system that
        spans two volumes, that is, is in different compartments. It uses a
        kkit model file. You can tell if it is working if you see nice 
        relaxation oscillations.
        """
    # the kkit reader doesn't know how to do multicompt solver setup.
    solver = "ee"
    mfile = '../Genesis_files/OSC_diff_vols.g'
    runtime = 3000.0
    simDt = 1.0
    modelId = moose.loadModel(mfile, 'model', solver)
    #moose.delete( '/model/kinetics/A/Stot' )
    compt0 = moose.element('/model/kinetics')
    compt1 = moose.element('/model/compartment_1')
    assert (deq(compt0.volume, 2e-20))
    assert (deq(compt1.volume, 1e-20))
    dy = compt0.dy
    compt1.y1 += dy
    compt1.y0 = dy
    assert (deq(compt1.volume, 1e-20))
    # We now have two cubes adjacent to each other. Compt0 has 2x vol.
    # Compt1 touches it.
    stoich0 = moose.Stoich('/model/kinetics/stoich')
    stoich1 = moose.Stoich('/model/compartment_1/stoich')
    ksolve0 = moose.Ksolve('/model/kinetics/ksolve')
    ksolve1 = moose.Ksolve('/model/compartment_1/ksolve')
    stoich0.compartment = compt0
    stoich0.ksolve = ksolve0
    stoich0.path = '/model/kinetics/##'
    stoich1.compartment = compt1
    stoich1.ksolve = ksolve1
    stoich1.path = '/model/compartment_1/##'
    #stoich0.buildXreacs( stoich1 )
    print ksolve0.numLocalVoxels, ksolve0.numPools, stoich0.numAllPools
    assert (ksolve0.numLocalVoxels == 1)
    assert (ksolve0.numPools == 7)
    assert (stoich0.numAllPools == 6)
    print len(stoich0.proxyPools[stoich1]),
    print len(stoich1.proxyPools[stoich0])
    assert (len(stoich0.proxyPools[stoich1]) == 1)
    assert (len(stoich1.proxyPools[stoich0]) == 1)
    print ksolve1.numLocalVoxels, ksolve1.numPools, stoich1.numAllPools
    assert (ksolve1.numLocalVoxels == 1)
    assert (ksolve1.numPools == 6)
    assert (stoich1.numAllPools == 5)
    stoich0.buildXreacs(stoich1)
    print moose.element('/model/kinetics/endo')
    print moose.element('/model/compartment_1/exo')
    moose.le('/model/compartment_1')
    moose.reinit()
    moose.start(runtime)

    # Display all plots.
    for x in moose.wildcardFind('/model/#graphs/conc#/#'):
        t = numpy.arange(0, x.vector.size, 1) * simDt
        pylab.plot(t, x.vector, label=x.name)
    pylab.legend()
    pylab.show()
コード例 #10
0
def scanDistDtGrid():
    seqList, seqScore = makeSequence( numSpine )
    #moose.setClock(18, 0.02 )
    #print "DT = ", moose.element( '/model/graphs/plot0').dt
    seqDtRange = ( 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0 ) # Interval between stimuli, in sec
    drange = ( 5, 10, 15, 20, 25, 30 ) # Distance covered, in diffLen.
    if displayMoogli:
        seqDtRange = ( moogliDt, )
        drange = ( moogliDistance, )
        # seqDtRange = ( 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0 ) # Interval between stimuli, in sec
        # drange = ( 5, 10, 15, 20, 25, 30 )
    allSimOutput = []

    ampl = moose.vec( '/model/chem/dend/ampl' )
    print("ampl: ", len(ampl))
    ampl.nInit = params['stimAmplitude']
    blanks = params['blankVoxelsAtEnd']
    preStim = params['preStimTime']
    postStim = params['postStimTime']
    diffusionLength = params['diffusionLength']
    
    for seqDt in seqDtRange:
        temp2 = []
        temp3 = []
        for d in drange:
            # compt = moose.Compartment( '/model/chem/soma')
            # compt.diameter = params['dendDiameter']/8 
            dend = moose.element( '/model/chem/dend')
            # print("dend diameter: ", dend.diameter)
            moose.le( '/model/chem/dend' )

            phase = moose.vec( '/model/chem/dend/phase' )
            ampl = moose.vec( '/model/chem/dend/ampl' )

            # Old version. Assumes we activate density * d compartments.
            #ampl.nInit = float(v)/float(d)  

            ampl.nInit = params['stimAmplitude']
            Z = moose.vec( '/model/chem/dend/Z' )
            stride = int(d) / numSpine
            Z.nInit = 0
            phase.nInit = 10000.0

            temp = []
            slopes = []
            for seq in seqList:
                print '.',
                sys.stdout.flush()
                for j in range( numSpine ):
                    k = (blanks + j * stride) 
                    Z[ k ].nInit = 1
                    phase[ k ].nInit = preStim + seq[j] * seqDt
                temp.append( runTrial( diffusionLength, seqDt, d, blanks, preStim, postStim ))
                #print temp
            simOut = np.array( temp )
            temp3.append( simOut )
            print seqDt, d #temp[-1], temp[-2], 
        allSimOutput.append( temp3 )
    return allSimOutput, seqDtRange, drange
コード例 #11
0
ファイル: funcInputToPools.py プロジェクト: asiaszmek/moose
def makeModel():
                if len( sys.argv ) == 1:
                        useGsolve = True
                else:
                        useGsolve = ( sys.argv[1] == 'True' )
                # create container for model
                model = moose.Neutral( 'model' )
                compartment = moose.CubeMesh( '/model/compartment' )
                compartment.volume = 1e-22
                # the mesh is created automatically by the compartment
                moose.le( '/model/compartment' )
                mesh = moose.element( '/model/compartment/mesh' )

                # create molecules and reactions
                a = moose.Pool( '/model/compartment/a' )
                b = moose.Pool( '/model/compartment/b' )

                # create functions of time
                f1 = moose.Function( '/model/compartment/f1' )
                f2 = moose.Function( '/model/compartment/f2' )

                # connect them up for reactions
                moose.connect( f1, 'valueOut', a, 'setConc' )
                moose.connect( f2, 'valueOut', b, 'increment' )

                # Assign parameters
                a.concInit = 0
                b.concInit = 1
                #f1.numVars = 1
                #f2.numVars = 1
                f1.expr = '1 + sin(t)'
                f2.expr = '10 * cos(t)'

                # Create the output tables
                graphs = moose.Neutral( '/model/graphs' )
                outputA = moose.Table2 ( '/model/graphs/nA' )
                outputB = moose.Table2 ( '/model/graphs/nB' )

                # connect up the tables
                moose.connect( outputA, 'requestOut', a, 'getN' );
                moose.connect( outputB, 'requestOut', b, 'getN' );

                # Set up the solvers
                if useGsolve:
                    gsolve = moose.Gsolve( '/model/compartment/gsolve' )
                    gsolve.useClockedUpdate = True
                else:
                    gsolve = moose.Ksolve( '/model/compartment/gsolve' )
                stoich = moose.Stoich( '/model/compartment/stoich' )
                stoich.compartment = compartment
                stoich.ksolve = gsolve
                stoich.path = '/model/compartment/##'
                '''
                '''

                # We need a finer timestep than the default 0.1 seconds,
                # in order to get numerical accuracy.
                for i in range (10, 19 ):
                    moose.setClock( i, 0.1 ) # for computational objects
コード例 #12
0
def makeModel():
    if len(sys.argv) == 1:
        useGsolve = True
    else:
        useGsolve = (sys.argv[1] == 'True')
    # create container for model
    model = moose.Neutral('model')
    compartment = moose.CubeMesh('/model/compartment')
    compartment.volume = 1e-22
    # the mesh is created automatically by the compartment
    moose.le('/model/compartment')
    mesh = moose.element('/model/compartment/mesh')

    # create molecules and reactions
    a = moose.Pool('/model/compartment/a')
    b = moose.Pool('/model/compartment/b')

    # create functions of time
    f1 = moose.Function('/model/compartment/f1')
    f2 = moose.Function('/model/compartment/f2')

    # connect them up for reactions
    moose.connect(f1, 'valueOut', a, 'setConc')
    moose.connect(f2, 'valueOut', b, 'increment')

    # Assign parameters
    a.concInit = 0
    b.concInit = 1
    #f1.numVars = 1
    #f2.numVars = 1
    f1.expr = '1 + sin(t)'
    f2.expr = '10 * cos(t)'

    # Create the output tables
    graphs = moose.Neutral('/model/graphs')
    outputA = moose.Table2('/model/graphs/nA')
    outputB = moose.Table2('/model/graphs/nB')

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

    # Set up the solvers
    if useGsolve:
        gsolve = moose.Gsolve('/model/compartment/gsolve')
        gsolve.useClockedUpdate = True
    else:
        gsolve = moose.Ksolve('/model/compartment/gsolve')
    stoich = moose.Stoich('/model/compartment/stoich')
    stoich.compartment = compartment
    stoich.ksolve = gsolve
    stoich.path = '/model/compartment/##'
    '''
    '''

    # We need a finer timestep than the default 0.1 seconds,
    # in order to get numerical accuracy.
    for i in range(10, 19):
        moose.setClock(i, 0.1)  # for computational objects
コード例 #13
0
def main():
    library = moose.Neutral('/library')
    makePassiveSoma('cell', params['dendL'], params['dendDia'])
    makeChemProto()
    rdes = rd.rdesigneur(
        turnOffElec=True,
        chemPlotDt=0.1,
        diffusionLength=params['diffusionL'],
        cellProto=[['cell', 'soma']],
        chemProto=[['hydra', 'hydra']],
        chemDistrib=[['hydra', 'soma', 'install', '1']],
        plotList=[['soma', '1', 'dend/A', 'n', '# of A'],
                  ['soma', '1', 'dend/B', 'n', '# of B']],
        #    moogList = [['soma', '1', 'dend/A', 'n', 'num of A (number)']]
    )
    moose.le('/library')
    moose.le('/library/hydra')
    moose.showfield('/library/soma/soma')
    rdes.buildModel()
    #moose.element('/model/chem/dend/B').vec[50].nInit=15.5

    A = moose.vec('/model/chem/dend/A')
    #B = moose.vec('/model/chem/dend/B')
    #    A.concInit=1
    #    B.concInit=10
    moose.element('/model/chem/dend/B').vec[50].nInit = 100
    #moose.element('/model/chem/dend/B').vec[25].nInit=0
    #A.nInit=1
    #B.nInit=15

    #Adot = moose.element('/model/chem/dend/A/Adot')
    #Bdot = moose.element('/model/chem/dend/B/Bdot')

    #print "\n\n\t\t Before Run", Adot, Bdot, A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit

    moose.reinit()
    moose.start(500)

    #print "\n\n\t\t After Run", A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit

    # rdes.display()
    # rdes.displayMoogli( 1, 400, 0.001 )
    avec = moose.vec('/model/chem/dend/A').n
    bvec = moose.vec('/model/chem/dend/B').n
    #tab = moose.element( '/model/graphs/plot0')
    #dt = tab.dt
    #tvec=[]
    #tvec.append( tab.vector )
    # xplot = []
    # xplot.append( avec )
    ##  t = np.arange( 0, len( tvec[0] ), 1.0 ) * dt
    plt.plot(avec)

    #print bvec, len(bvec), bvec

    return bvec, avec
コード例 #14
0
def setup_clocks(simdt, plotdt):
    print 'Setting up clocks: simdt', simdt, 'plotdt', plotdt
    moose.setClock(INITCLOCK, simdt)
    moose.setClock(ELECCLOCK, simdt)
    moose.setClock(CHANCLOCK, simdt)
    moose.setClock(POOLCLOCK, simdt)
    moose.setClock(LOOKUPCLOCK, simdt)
    moose.setClock(STIMCLOCK, simdt)
    moose.setClock(PLOTCLOCK, plotdt)
    moose.le('/clock')
コード例 #15
0
ファイル: testutils.py プロジェクト: BhallaLab/moose
def setup_clocks(simdt, plotdt):
    print("Setting up clocks: simdt", simdt, "plotdt", plotdt)
    moose.setClock(INITCLOCK, simdt)
    moose.setClock(ELECCLOCK, simdt)
    moose.setClock(CHANCLOCK, simdt)
    moose.setClock(POOLCLOCK, simdt)
    moose.setClock(LOOKUPCLOCK, simdt)
    moose.setClock(STIMCLOCK, simdt)
    moose.setClock(PLOTCLOCK, plotdt)
    moose.le("/clock")
コード例 #16
0
def test_le():
    # see issue BhallaLab/moose-core#423
    x = moose.le('/')
    assert len(x) > 5, x
    try:
        moose.le('/abrakadabra')
    except ValueError:
        pass
    else:
        raise RuntimeError("This should have raised ValueError")
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']],
        plotList=[['soma', '1', 'dend/A', 'n', '# of A'],
                  ['soma', '1', 'dend/B', 'n', '# of B']],
        #    moogList = [['soma', '1', 'dend/A', 'n', 'num of A (number)']]
    )
    moose.le('/library')
    moose.le('/library/hydra')
    #moose.showfield( '/library/soma/soma' )
    rdes.buildModel()
    #moose.element('/model/chem/dend/B').vec[50].nInit=15.5

    A = moose.element('/model/chem/dend/A')
    B = moose.element('/model/chem/dend/B')
    C = moose.element('/model/chem/dend/C')
    A.diffConst = 1e-13
    B.diffConst = 0
    C.diffConst = 0
    B.motorConst = 1e-06
    C.motorConst = -1e-06
    #    A.concInit=1
    #    B.concInit=10
    avec = moose.vec('/model/chem/dend/A').n
    savec = avec.size
    for i in range(0, savec - 1, 1):
        moose.element('/model/chem/dend/A').vec[i].nInit = np.random.uniform(
            0, 1)
        print moose.element('/model/chem/dend/A').vec[i].nInit

    print 'simulation start'
    moose.reinit()
    #moose.start(2)
    for t in range(0, 4000, 500):
        moose.start(500)
        print 'in loop', t
        avec = moose.vec('/model/chem/dend/A').n
        plt.plot(avec)

    avec = moose.vec('/model/chem/dend/A').n
    bvec = moose.vec('/model/chem/dend/B').n
    cvec = moose.vec('/model/chem/dend/C').n
    #plt.plot(bvec)

    return bvec, avec, cvec
コード例 #18
0
 def _setup_network(self):
     """Sets up the network (_init_network is enough)"""
     self.network = moose.LIF( 'network', self.N );
     moose.le( '/network' )
     self.network.vec.Em = self.el
     self.network.vec.thresh = self.vt
     self.network.vec.refractoryPeriod = self.refrT
     self.network.vec.Rm = self.Rm
     self.network.vec.vReset = self.vr
     self.network.vec.Cm = self.Cm
     self.network.vec.inject = self.Iinject
コード例 #19
0
 def _setup_network(self):
     """Sets up the network (_init_network is enough)"""
     self.network = moose.LIF('network', self.N)
     moose.le('/network')
     self.network.vec.Em = self.el
     self.network.vec.thresh = self.vt
     self.network.vec.refractoryPeriod = self.refrT
     self.network.vec.Rm = self.Rm
     self.network.vec.vReset = self.vr
     self.network.vec.Cm = self.Cm
     self.network.vec.inject = self.Iinject
コード例 #20
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']],
        plotList=[['soma', '1', 'dend/A', 'n', '# of A'],
                  ['soma', '1', 'dend/B', 'n', '# of B']],
        #    moogList = [['soma', '1', 'dend/A', 'n', 'num of A (number)']]
    )
    moose.le('/library')
    moose.le('/library/hydra')
    #moose.showfield( '/library/soma/soma' )
    rdes.buildModel()
    #moose.element('/model/chem/dend/B').vec[50].nInit=15.5

    A = moose.element('/model/chem/dend/A')
    B = moose.element('/model/chem/dend/B')
    A.diffConst = 1e-13
    B.diffConst = 1e-12
    moose.element('/model/chem/dend/A').vec[25].nInit = 0.1
    moose.element('/model/chem/dend/B').vec[25].nInit = 0.1
    moose.element('/model/chem/dend/A').vec[30].nInit = 0.1
    moose.element('/model/chem/dend/B').vec[30].nInit = 0.1
    moose.element('/model/chem/dend/A').vec[45].nInit = 0.1
    moose.element('/model/chem/dend/B').vec[45].nInit = 0.1
    storeAvec = []
    storeBvec = []
    for i in range(50):
        moose.element('/model/chem/dend/space').vec[i].nInit = moose.element(
            '/model/chem/dend/mesh').vec[i].Coordinates[0]
        print moose.element('/model/chem/dend/space').vec[i].nInit

    moose.reinit()
    for i in range(1, 5000, 10):
        moose.start(10)
        avec = moose.vec('/model/chem/dend/A').n
        bvec = moose.vec('/model/chem/dend/B').n
        storeAvec.append(avec)
        storeBvec.append(bvec)
    bvec = moose.vec('/model/chem/dend/B').n
    avec = moose.vec('/model/chem/dend/A').n
    svec = moose.vec('/model/chem/dend/space').n

    return svec, bvec, avec, storeAvec, storeBvec
コード例 #21
0
def main():
		# Schedule the whole lot
		moose.setClock( 4, 0.1 ) # for the computational objects
		moose.setClock( 5, 0.1 ) # clock for the solver
		moose.setClock( 8, 1.0 ) # for the plots
		# The wildcard uses # for single level, and ## for recursive.
		#compartment = makeModel()
                moose.loadModel( '../Genesis_files/M1719.cspace', '/model', 'ee' )
                compartment = moose.element( 'model/kinetics' )
                compartment.name = 'compartment'
		ksolve = moose.Ksolve( '/model/compartment/ksolve' )
		stoich = moose.Stoich( '/model/compartment/stoich' )
		stoich.compartment = compartment
		stoich.ksolve = ksolve
		#ksolve.stoich = stoich
		stoich.path = "/model/compartment/##"
		state = moose.SteadyState( '/model/compartment/state' )
		moose.useClock( 5, '/model/compartment/ksolve', 'process' )
		moose.useClock( 8, '/model/graphs/#', 'process' )

		moose.reinit()
		state.stoich = stoich
		#state.showMatrices()
		state.convergenceCriterion = 1e-7

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

		for i in range( 0, 100 ):
			getState( ksolve, state )
		
		moose.start( 100.0 ) # Run the model for 100 seconds.

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

		# move most molecules over to b
		b.conc = b.conc + c.conc * 0.95
		c.conc = c.conc * 0.05
		moose.start( 100.0 ) # Run the model for 100 seconds.

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

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

		quit()
コード例 #22
0
def main():
    """
    Demonstrates how one can visualise morphology of a neuron using the MOOSE.
    """
    app = QtGui.QApplication(sys.argv)
    filename = 'barrionuevo_cell1zr.CNG.swc'
    moose.Neutral('/library')
    moose.Neutral('/model')
    cell = moose.loadModel(filename, '/model/testSwc')
    for i in range(8):
        moose.setClock(i, simdt)
    hsolve = moose.HSolve('/model/testSwc/hsolve')
    hsolve.dt = simdt
    hsolve.target = '/model/testSwc/soma'
    moose.le(cell)
    moose.reinit()

    # Now we set up the display
    compts = moose.wildcardFind("/model/testSwc/#[ISA=CompartmentBase]")
    compts[0].inject = inject
    ecomptPath = [x.path for x in compts]
    morphology = moogli.extensions.moose.read(path="/model/testSwc",
                                              vertices=15)
    viewer = moogli.Viewer("Viewer")
    viewer.attach_shapes(morphology.shapes.values())
    view = moogli.View("main-view")
    viewer.attach_view(view)

    # morphology = moogli.read_morphology_from_moose(name = "", path = "/model/testSwc")
    # morphology.create_group( "group_all", ecomptPath, -0.08, 0.02, \
    #         [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 0.9] )

    # viewer = moogli.DynamicMorphologyViewerWidget(morphology)
    def callback(morphology, viewer):
        moose.start(frameRunTime)
        Vm = [moose.element(x).Vm for x in compts]
        morphology.set_color("group_all", Vm)
        currTime = moose.element('/clock').currentTime
        #print currTime, compts[0].Vm
        if (currTime < runtime):
            return True
        return False

    #viewer.set_callback( callback, idletime = 0 )
    #viewer.showMaximized()
    viewer.show()
    app.exec_()
コード例 #23
0
 def _setup_network(self):
     """Sets up the network (_init_network is enough)"""
     self.network = moose.LIF("network", self.N)
     moose.le("/network")
     self.network.vec.Em = self.el
     self.network.vec.thresh = self.vt
     self.network.vec.refractoryPeriod = self.refrT
     self.network.vec.Rm = self.Rm
     self.network.vec.vReset = self.vr
     self.network.vec.Cm = self.Cm
     if not noiseInj:
         self.network.vec.inject = self.Iinject
     else:
         ## inject a constant + noisy current
         ## values are set in self.simulate()
         self.noiseTables = moose.StimulusTable("noiseTables", self.N)
         moose.connect(self.noiseTables, "output", self.network, "setInject", "OneToOne")
コード例 #24
0
def main():
    # The wildcard uses # for single level, and ## for recursive.
    #compartment = makeModel()
    moose.loadModel('../Genesis_files/M1719.cspace', '/model', 'ee')
    compartment = moose.element('model/kinetics')
    compartment.name = 'compartment'
    ksolve = moose.Ksolve('/model/compartment/ksolve')
    stoich = moose.Stoich('/model/compartment/stoich')
    stoich.compartment = compartment
    stoich.ksolve = ksolve
    #ksolve.stoich = stoich
    stoich.path = "/model/compartment/##"
    state = moose.SteadyState('/model/compartment/state')

    moose.reinit()
    state.stoich = stoich
    #state.showMatrices()
    state.convergenceCriterion = 1e-7

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

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

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

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

    # move most molecules over to b
    b.conc = b.conc + c.conc * 0.95
    c.conc = c.conc * 0.05
    moose.start(100.0)  # Run the model for 100 seconds.

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

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

    quit()
コード例 #25
0
def main():
    """
    Demonstrates how one can visualise morphology of a neuron using the MOOSE.
    """
    app = QtGui.QApplication(sys.argv)
    filename = 'barrionuevo_cell1zr.CNG.swc'
    moose.Neutral( '/library' )
    moose.Neutral( '/model' )
    cell = moose.loadModel( filename, '/model/testSwc' )
    for i in range( 8 ):
        moose.setClock( i, simdt )
    hsolve = moose.HSolve( '/model/testSwc/hsolve' )
    hsolve.dt = simdt
    hsolve.target = '/model/testSwc/soma'
    moose.le( cell )
    moose.reinit()

    # Now we set up the display
    compts = moose.wildcardFind( "/model/testSwc/#[ISA=CompartmentBase]" )
    compts[0].inject = inject
    ecomptPath = [x.path for x in compts]
    morphology = moogli.extensions.moose.read(path="/model/testSwc", vertices=15)
    viewer = moogli.Viewer("Viewer")
    viewer.attach_shapes( morphology.shapes.values() )
    view = moogli.View("main-view")
    viewer.attach_view( view )
    # morphology = moogli.read_morphology_from_moose(name = "", path = "/model/testSwc")
    # morphology.create_group( "group_all", ecomptPath, -0.08, 0.02, \
    #         [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 0.9] )

    # viewer = moogli.DynamicMorphologyViewerWidget(morphology)
    def callback( morphology, viewer ):
        moose.start( frameRunTime )
        Vm = [moose.element( x ).Vm for x in compts]
        morphology.set_color( "group_all", Vm )
        currTime = moose.element( '/clock' ).currentTime
        #print currTime, compts[0].Vm
        if ( currTime < runtime ):
            return True
        return False

    #viewer.set_callback( callback, idletime = 0 )
    #viewer.showMaximized()
    viewer.show()
    app.exec_()
コード例 #26
0
 def _setup_network(self):
     """Sets up the network (_init_network is enough)"""
     self.network = moose.LIF( 'network', self.N );
     moose.le( '/network' )
     self.network.vec.Em = self.el
     self.network.vec.thresh = self.vt
     self.network.vec.refractoryPeriod = self.refrT
     self.network.vec.Rm = self.Rm
     self.network.vec.vReset = self.vr
     self.network.vec.Cm = self.Cm
     if not noiseInj:
         self.network.vec.inject = self.Iinject
     else:
         ## inject a constant + noisy current
         ## values are set in self.simulate()
         self.noiseTables = moose.StimulusTable('noiseTables',self.N)
         moose.connect( self.noiseTables, 'output', \
             self.network, 'setInject', 'OneToOne')
コード例 #27
0
ファイル: rdesigneur.py プロジェクト: Vio8023/moose
    def addSpineProto( self, name, RM, RA, CM, \
            shaftLen = 1.e-6 , shaftDia = 0.2e-6, \
            headLen = 0.5e-6, headDia = 0.5e-6, \
            synList = ( ['glu', 0.0, 2e-3, 9e-3, 200.0, False],
                        ['NMDA', 0.0, 20e-3, 20e-3, 40.0, True] ),
            chanList = ( ['LCa', 40.0, True ], ),
            caTau = 13.333e-3
            ):
        if not moose.exists('/library'):
            library = moose.Neutral('/library')
        spine = moose.Neutral('/library/spine')
        shaft = self._buildCompt(spine, 'shaft', shaftLen, shaftDia, 0.0, RM,
                                 RA, CM)
        head = self._buildCompt(spine, 'head', headLen, headDia, shaftLen, RM,
                                RA, CM)
        moose.connect(shaft, 'raxial', head, 'axial')

        if caTau > 0.0:
            conc = moose.CaConc(head.path + '/Ca_conc')
            conc.tau = caTau
            # B = 1/(ion_charge * Faraday * volume)
            vol = head.length * head.diameter * head.diameter * PI / 4.0
            conc.B = 1.0 / (2.0 * FaradayConst * vol)
            conc.Ca_base = 0.0
        for i in synList:
            syn = self._buildSyn(i[0], head, i[1], i[2], i[3], i[4], CM)
            if i[5] and caTau > 0.0:
                moose.connect(syn, 'IkOut', conc, 'current')
        for i in chanList:
            if (moose.exists('/library/' + i[0])):
                chan = moose.copy('/library/' + i[0], head)
                chan.Gbar = i[1] * head.Cm / CM
                print "CHAN = ", chan, chan.tick
                moose.connect(head, 'channel', chan, 'channel')
                if i[2] and caTau > 0.0:
                    moose.connect(chan, 'IkOut', conc, 'current')
            else:
                print "Warning: addSpineProto: channel '", i[0], \
                    "' not found on /library."
                moose.le('/library')
        self._transformNMDAR('/library/spine')
        return spine
コード例 #28
0
ファイル: test_api.py プロジェクト: sanjayankur31/moose-core
def test_vec():
    a = moose.Pool('/p111', 100)
    v = moose.vec(a)

    # le can cause segfault in some cases.
    moose.le(v)

    assert len(v) == 100, len(v)
    assert v == v.vec
    assert v[0] == v.vec[0], (v[0], v.vec[0])
    x = [random.random() for i in range(100)]
    v.conc = x
    assert sum(v.conc) == sum(x)
    assert np.allclose(v.conc, x), (v.conc, x)

    # assign bool to double.
    y = [float(x < 5) for x in range(100)]
    v.concInit = y
    assert (v.concInit[:5] == 1.0).all(), v.concInit[:5]
    assert (v.concInit[5:] == 0.0).all(), v.concInit[5:]
コード例 #29
0
ファイル: rdesigneur.py プロジェクト: iampritishpatil/moose
    def addSpineProto( self, name = 'spine', \
            RM = 1.0, RA = 1.0, CM = 0.01, \
            shaftLen = 1.e-6 , shaftDia = 0.2e-6, \
            headLen = 0.5e-6, headDia = 0.5e-6, \
            synList = ( ['glu', 0.0, 2e-3, 9e-3, 200.0, False],
                        ['NMDA', 0.0, 20e-3, 20e-3, 40.0, True] ),
            chanList = ( ['LCa', 40.0, True ], ),
            caTau = 13.333e-3
            ):
        if not moose.exists( '/library' ):
            library = moose.Neutral( '/library' )
        spine = moose.Neutral( '/library/spine' )
        shaft = self._buildCompt( spine, 'shaft', shaftLen, shaftDia, 0.0, RM, RA, CM )
        head = self._buildCompt( spine, 'head', headLen, headDia, shaftLen, RM, RA, CM )
        moose.connect( shaft, 'raxial', head, 'axial' )

        if caTau > 0.0:
            conc = moose.CaConc( head.path + '/Ca_conc' )
            conc.tau = caTau
            # B = 1/(ion_charge * Faraday * volume)
            vol = head.length * head.diameter * head.diameter * PI / 4.0
            conc.B = 1.0 / ( 2.0 * FaradayConst * vol )
            conc.Ca_base = 0.0
        for i in synList:
            syn = self._buildSyn( i[0], head, i[1], i[2], i[3], i[4], CM )
            if i[5] and caTau > 0.0:
                moose.connect( syn, 'IkOut', conc, 'current' )
        for i in chanList:
            if ( moose.exists( '/library/' + i[0] ) ):
                chan = moose.copy( '/library/' + i[0], head )
                chan.Gbar = i[1] * head.Cm / CM
                #print "CHAN = ", chan, chan.tick
                moose.connect( head, 'channel', chan, 'channel' )
                if i[2] and caTau > 0.0:
                    moose.connect( chan, 'IkOut', conc, 'current' )
            else:
                print "Warning: addSpineProto: channel '", i[0], \
                    "' not found on /library."
                moose.le( '/library' )
        self._transformNMDAR( '/library/spine' )
        return spine
コード例 #30
0
def main():
    neuron = moose.Neutral("/neuron")
    inputs = moose.Neutral("/inputs")
    outputs = moose.Neutral("/outputs")

    

    soma = create_spherical_compartment("/neuron/soma",25e-6,20e-6,2.8,4.0,0.03)
    dend = create_spherical_compartment("/neuron/dendrite",25e-6,20e-6,2.8,4.0,0.03)
    #cell = moose.loadModel(fileName, cellPath)moose.connect(soma)

    pulse = create_pulse("/inputs/somaPulse",50e-3,100e-3,1e-9,soma)
    vmtable = create_table('outputs/somaVmTable',soma,"getVm")
    print(soma.tick)
    print(soma.dt)
    #moose.reinit()
    #moose.start(900e-3)
    #moose.showfields(vmtable)
    #moose.showmsg(soma)
    #moose.showmsg(pulse)
    #moose.showmsg(vmtable)

    plot_table(vmtable)
    pyplot.show()

    pNeuron = load_genesis_file("layer2.p", "/pNeuron")
    swcNeuron = load_neuron_file("538ser3sl5-cell1-2-a.CNG.swc", "/swcNeuron", 0.678, 2.0, 0.0295)

    moose.le(neuron)
    moose.le(pNeuron)
    moose.le(swcNeuron)
コード例 #31
0
def main():
    app = QtGui.QApplication(sys.argv)
    filename = 'barrionuevo_cell1zr.CNG.swc'
    moose.Neutral('/library')
    moose.Neutral('/model')
    cell = moose.loadModel(filename, '/model/testSwc')
    for i in range(8):
        moose.setClock(i, simdt)
    hsolve = moose.HSolve('/model/testSwc/hsolve')
    hsolve.dt = simdt
    hsolve.target = '/model/testSwc/soma'
    moose.le(cell)
    moose.reinit()

    # Now we set up the display
    compts = moose.wildcardFind("/model/testSwc/#[ISA=CompartmentBase]")
    compts[0].inject = inject
    ecomptPath = map(lambda x: x.path, compts)
    morphology = moogli.read_morphology_from_moose(name="",
                                                   path="/model/testSwc")
    morphology.create_group( "group_all", ecomptPath, -0.08, 0.02, \
            [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 0.9] )

    viewer = moogli.DynamicMorphologyViewerWidget(morphology)

    def callback(morphology, viewer):
        moose.start(frameRunTime)
        Vm = map(lambda x: moose.element(x).Vm, compts)
        morphology.set_color("group_all", Vm)
        currTime = moose.element('/clock').currentTime
        #print currTime, compts[0].Vm
        if (currTime < runtime):
            return True
        return False

    viewer.set_callback(callback, idletime=0)
    viewer.showMaximized()
    viewer.show()
    app.exec_()
コード例 #32
0
def attachStimulus2( fname ):
    ampar = moose.wildcardFind( '/model/elec/#/glu' )
    nmdar = moose.wildcardFind( '/model/elec/#/NMDA' )
    numSyn = len( ampar )
    assert( numSyn == len( nmdar ) );
    moose.le( '/model' )

    moose.RandSpike( '/model/elec/spike', len( ampar ) )
    spikes = moose.vec( '/model/elec/spike' )
    spikes.rate = params['meanSpikeRate']
    spikes.refractT = params['refractoryPeriod']
    amparSynWeight = params['amparSynapseWeight']
    nmdarSynWeight = params['nmdarSynapseWeight']
    for i in range( numSyn ):
        sh = moose.element( ampar[i].path + '/sh' )
        sh.numSynapses = 1
        sh.synapse[0].weight = amparSynWeight
        moose.connect( spikes[i], 'spikeOut', sh.synapse[0], 'addSpike' )
        sh = moose.element( nmdar[i].path + '/sh' )
        sh.numSynapses = 1
        sh.synapse[0].weight = nmdarSynWeight
        moose.connect( spikes[i], 'spikeOut', sh.synapse[0], 'addSpike' )
コード例 #33
0
 def createCell(self, name):
     model_container = moose.Neutral('/model')
     data_container = moose.Neutral('/data')        
     moose.le(model_container)
     moose.le(data_container)
     for ch in model_container.children:            
         moose.delete(ch)
     for ch in data_container.children:
         moose.delete(ch)
     params = setup_current_step_model(model_container,
                                       data_container,
                                       name,
                                       [[0, 0, 0],
                                        [1e9, 0, 0]])
     # moose.le(model_container)
     # moose.le(data_container)
     print '11111'
     print model_container.path, data_container.path
     params['modelRoot'] = model_container.path
     params['dataRoot'] = data_container.path
     print 'here'
     return params
コード例 #34
0
def main():
    app = QtGui.QApplication(sys.argv)
    filename = 'barrionuevo_cell1zr.CNG.swc'
    moose.Neutral( '/library' )
    moose.Neutral( '/model' )
    cell = moose.loadModel( filename, '/model/testSwc' )
    for i in range( 8 ):
        moose.setClock( i, simdt )
    hsolve = moose.HSolve( '/model/testSwc/hsolve' )
    hsolve.dt = simdt
    hsolve.target = '/model/testSwc/soma'
    moose.le( cell )
    moose.reinit()

    # Now we set up the display
    compts = moose.wildcardFind( "/model/testSwc/#[ISA=CompartmentBase]" )
    compts[0].inject = inject
    ecomptPath = map( lambda x : x.path, compts )
    morphology = moogli.read_morphology_from_moose(name = "", path = "/model/testSwc")
    morphology.create_group( "group_all", ecomptPath, -0.08, 0.02, \
            [0.0, 0.5, 1.0, 1.0], [1.0, 0.0, 0.0, 0.9] ) 

    viewer = moogli.DynamicMorphologyViewerWidget(morphology)
    def callback( morphology, viewer ):
        moose.start( frameRunTime )
        Vm = map( lambda x: moose.element( x ).Vm, compts )
        morphology.set_color( "group_all", Vm )
        currTime = moose.element( '/clock' ).currentTime
        #print currTime, compts[0].Vm
        if ( currTime < runtime ):
            return True
        return False

    viewer.set_callback( callback, idletime = 0 )
    viewer.showMaximized()
    viewer.show()
    app.exec_()
コード例 #35
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 "
コード例 #36
0
def load():
    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, 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()
    print "asdfasdfasf", moose.le('/')
    #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
コード例 #37
0
ファイル: test_api.py プロジェクト: sanjayankur31/moose-core
def test_children():
    a1 = moose.Neutral('/a')
    a2 = moose.Neutral('/a/b')
    a3 = moose.Neutral('/a/b/c1')
    moose.Neutral('/a/b/c2')
    assert len(a1.children) == 1
    assert len(a2.children) == 2
    moose.le(a1)
    moose.le(a2)
    moose.le(a3)
    moose.setCwe(a3)
    s = moose.getCwe()
    assert s == a3, (s, a3)
    a11 = a1.children[0]
    ax = moose.element(a1)
    ax1 = ax.children[0]
    assert ax == a1
    assert ax1 == a11
    assert a11[0].isA['Neutral'], a11.isA
    assert ax1[0].isA['Neutral'], a11.isA
    print("test_children is done")
コード例 #38
0
def make_network():
        size = 1024
        dt = 0.2
        runsteps = 50
        delayMin = 0
        delayMax = 4
        weightMax = 1
        Vmax = 1.0
        thresh = 0.4
        refractoryPeriod = 0.4
        tau = 0.5
        connectionProbability = 0.01
        random.seed( 123 )
        nprand.seed( 456 )
        t0 = time.time()

        network = moose.IntFire( 'network', size );
        syns = moose.SimpleSynHandler( '/network/syns', size );
        moose.connect( syns, 'activationOut', network, 'activation', 'OneToOne' )
        moose.le( '/network' )
        syns.vec.numSynapses = [1] * size
        sv = moose.vec( '/network/syns/synapse' )
        print(('before connect t = ', time.time() - t0))
        mid = moose.connect( network, 'spikeOut', sv, 'addSpike', 'Sparse')
        print(('after connect t = ', time.time() - t0))
        #print mid.destFields
        m2 = moose.element( mid )
        m2.setRandomConnectivity( connectionProbability, 5489 )
        print(('after setting connectivity, t = ', time.time() - t0))
        #network.vec.Vm = [(Vmax*random.random()) for r in range(size)]
        network.vec.Vm = nprand.rand( size ) * Vmax
        network.vec.thresh = thresh
        network.vec.refractoryPeriod = refractoryPeriod
        network.vec.tau = tau
        numSynVec = syns.vec.numSynapses
        print(('Middle of setup, t = ', time.time() - t0))
        numTotSyn = sum( numSynVec )
        print((numSynVec.size, ', tot = ', numTotSyn,  ', numSynVec = ', numSynVec))
        for item in syns.vec:
                sh = moose.element( item )
                sh.synapse.delay = delayMin +  (delayMax - delayMin ) * nprand.rand( len( sh.synapse ) )
                #sh.synapse.delay = [ (delayMin + random.random() * (delayMax - delayMin ) for r in range( len( sh.synapse ) ) ] 
                sh.synapse.weight = nprand.rand( len( sh.synapse ) ) * weightMax
        print(('after setup, t = ', time.time() - t0))

        numStats = 100
        stats = moose.SpikeStats( '/stats', numStats )
        stats.vec.windowLength = 1 # timesteps to put together.
        plots = moose.Table( '/plot', numStats )
        convergence = size / numStats
        for i in range( numStats ):
            for j in range( size/numStats ):
                k = i * convergence + j
                moose.connect( network.vec[k], 'spikeOut', stats.vec[i], 'addSpike' )
        moose.connect( plots, 'requestOut', stats, 'getMean', 'OneToOne' )

        #moose.useClock( 0, '/network/syns,/network', 'process' )
        moose.useClock( 0, '/network/syns', 'process' )
        moose.useClock( 1, '/network', 'process' )
        moose.useClock( 2, '/stats', 'process' )
        moose.useClock( 3, '/plot', 'process' )
        moose.setClock( 0, dt )
        moose.setClock( 1, dt )
        moose.setClock( 2, dt )
        moose.setClock( 3, dt )
        moose.setClock( 9, dt )
        t1 = time.time()
        moose.reinit()
        print(('reinit time t = ', time.time() - t1))
        network.vec.Vm = nprand.rand( size ) * Vmax
        print(('setting Vm , t = ', time.time() - t1))
        t1 = time.time()
        print('starting')
        moose.start(runsteps * dt)
        print(('runtime, t = ', time.time() - t1))
        print((network.vec.Vm[99:103], network.vec.Vm[900:903]))
        t = [i * dt for i in range( plots.vec[0].vector.size )]
        i = 0
        for p in plots.vec:
            pylab.plot( t, p.vector, label=str( i) )
            i += 1
        pylab.xlabel( "Time (s)" )
        pylab.ylabel( "Vm (mV)" )
        pylab.legend()
        pylab.show()
コード例 #39
0
ファイル: MorphML.py プロジェクト: hrani/moose-core
    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, ... ], ... }.
        params is dict which can contain, combineSegments and/or createPotentialSynapses,
         both boolean.
        """
        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
        _logger.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 params:
            self.combineSegments = params['combineSegments']
        else:
            self.combineSegments = False
        if 'createPotentialSynapses' in params:
            self.createPotentialSynapses = params['createPotentialSynapses']
        else:
            self.createPotentialSynapses = False
        _logger.info("readMorphML using combineSegments = %s" % self.combineSegments)

        ###############################################
        #### load cablegroups into a dictionary
        self.cablegroupsDict = {}
        self.cablegroupsInhomoparamsDict = {}
        ## 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] = []
            self.cablegroupsInhomoparamsDict[cablegroupname] = []
            for cable in cablegroup.findall(".//{"+self.mml+"}cable"):
                cableid = cable.attrib['id']
                self.cablegroupsDict[cablegroupname].append(cableid)
            # parse inhomogenous_params
            for inhomogeneous_param in cablegroup.findall(".//{"+self.mml+"}inhomogeneous_param"):
                metric = inhomogeneous_param.find(".//{"+self.mml+"}metric")
                if metric.text == 'Path Length from root':
                    inhomoparamname = inhomogeneous_param.attrib['name']
                    inhomoparamvar = inhomogeneous_param.attrib['variable']
                    self.cablegroupsInhomoparamsDict[cablegroupname].append(\
                                (inhomoparamname,inhomoparamvar))
                else:
                    _logger.warning('Only "Path Length from root" metric is '
                            ' supported currently, ignoring %s ' % metric.text
                            )

        ## <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 self.cablegroupsDict:
                    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):
                    _logger.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):
                        _logger.warn("Mechanism doesn't exist: %s " % 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 self.intFireCableIds:
                                    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
                mechanismname = None
                if 'all' in self.intFireCableIds:
                    mechanismname = self.intFireCableIds['all']
                if cableid in self.intFireCableIds:
                    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)
                    mname = '/library/' + mechanismname
                    moosechannel = moose.element(mname) if moose.exists(mname) else moose.Neutral(mname)
                    # Mstring values are 'string'; make sure to convert them to
                    # float else it will seg-fault with python3+
                    moosechannelval = moose.Mstring(moosechannel.path+'/vReset')
                    moosecomp.vReset = float(moosechannelval.value)
                    moosechannelval = moose.Mstring(moosechannel.path+'/thresh')
                    moosecomp.thresh = float( moosechannelval.value )
                    moosechannelval = moose.Mstring(moosechannel.path+'/refracT')
                    moosecomp.refractoryPeriod = eval(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 self.cellDictByCableId[cellname][1]:
                    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:
                _logger.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)
            chan_distrib = [] # the list for moose to parse inhomogeneous params (filled below)
            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
                _logger.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 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:
                            _logger.warning(["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:
                            _logger.warning(["Yo programmer of MorphML import! You didn't"
                                    , " implement parameter %s " % parametername
                                    , " in mechanism %s " % mechanismname ]
                                    )

                ## variable parameters:
                ##  varying with:
                ##  p, g, L, len, dia
                ##	p: path distance from soma, measured along dendrite, in metres.
                ##	g: geometrical distance from soma, in metres.
                ##	L: electrotonic distance (# of lambdas) from soma, along dend. No units.
                ##	len: length of compartment, in metres.
                ##	dia: for diameter of compartment, in metres.
                var_params = mechanism.findall(".//{"+self.bio+"}variable_parameter")
                if len(var_params) > 0:
                    ## if variable params are present
                    ##  and use MOOSE to apply the variable formula
                    for parameter in var_params:
                        parametername = parameter.attrib['name']
                        cablegroupstr4moose = ""
                        ## the neuroml spec says there should be a single group in a variable_parameter
                        ##  of course user can always have multiple variable_parameter tags,
                        ##  if user wants multiple groups conforming to neuroml specs.
                        group = parameter.find(".//{"+self.bio+"}group")
                        cablegroupname = group.text
                        if cablegroupname == 'all':
                            cablegroupstr4moose = "#"
                        else:
                            for cableid in self.cablegroupsDict[cablegroupname]:
                                for compartment in self.cellDictByCableId[cellname][1][cableid]:
                                    cablegroupstr4moose += "#"+compartment.name+"#,"
                            if cablegroupstr4moose[-1] == ',':
                                cablegroupstr4moose = cablegroupstr4moose[:-1] # remove last comma
                        inhomo_value = parameter.find(".//{"+self.bio+"}inhomogeneous_value")
                        inhomo_value_name = inhomo_value.attrib['param_name']
                        inhomo_value_value = inhomo_value.attrib['value']
                        if parametername == 'gmax':
                            inhomo_eqn = '('+inhomo_value_value+')*'+str(Gfactor)
                                        # careful about physiol vs SI units
                        else:
                            inhomo_eqn = inhomo_value_value
                            _logger.warning('Physiol. vs SI units translation not'
                            ' implemented for parameter '+parametername+
                            'in channel '+mechanismname)+'. Use SI units'
                            'or ask for implementation.'
                        chan_distrib.extend((mechanismname,cablegroupstr4moose,parametername,inhomo_eqn,""))
                                    # use extend, not append, moose wants it this way
            ## get mooose to parse the variable parameter gmax channel distributions
            #pu.info("Some channel parameters distributed as per "+str(chan_distrib))
            moosecell.channelDistribution = chan_distrib
            #### 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 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 potential_syn_loc.attrib:
                    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 self.cablegroupsDict:
            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

        _logger.info("Finished loading into library, cell: %s " % cellname)
        return {cellname:(self.segDict,self.cableDict)}
コード例 #40
0
## Leaky integrate and fire neuron
Vrest = -65e-3  # V      # resting potential
Vt_base = -45e-3  # V    # threshold
Vreset = -55e-3  # V     # in current steps, Vreset is same as pedestal
R = 1e8  # Ohm
tau = 10e-3  # s
refrT = 2e-3  # s

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

## two neurons: index 0 will be presynaptic, 1 will be postsynaptic
network = moose.LIF('network', 2)
moose.le('/network')
network.vec.Em = Vrest
network.vec.thresh = Vt_base
network.vec.refractoryPeriod = refrT
network.vec.Rm = R
network.vec.vReset = Vreset
network.vec.Cm = tau / R
network.vec.inject = 0.
network.vec.initVm = Vrest

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

### Cortical slice values -- Table Suppl 2 in Graupner & Brunel 2012
### Also used in Higgins et al 2014
コード例 #41
0
ファイル: IntegrateFireZoo.py プロジェクト: asiaszmek/moose
def main():
    """
Simulate current injection into various Integrate and Fire neurons.

All integrate and fire (IF) neurons are subclasses of compartment,
so they have all the fields of a passive compartment. Multicompartmental neurons can be created.
Even ion channels and synaptic channels can be added to them, say for sub-threshold behaviour.

The key addition is that they have a reset mechanism when the membrane potential Vm crosses a threshold.
On each reset, a spikeOut message is generated, and the membrane potential is reset to Vreset.
The threshold may be the spike generation threshold as for LIF and AdThreshIF,
or it may be the peak of the spike as for QIF, ExIF, AdExIF, and IzhIF.
The adaptive IFs have an extra adapting variable apart from membrane potential Vm.

Details of the IFs are given below.
The fields of the MOOSE objects are named exactly as the parameters in the equations below.

 LIF:      Leaky Integrate and Fire:
           Rm*Cm * dVm/dt = -(Vm-Em) + Rm*I

 QIF:      Quadratic LIF:
           Rm*Cm * dVm/dt = a0*(Vm-Em)*(Vm-vCritical) + Rm*I

 ExIF:     Exponential leaky integrate and fire:
           Rm*Cm * dVm/dt = -(Vm-Em) + deltaThresh * exp((Vm-thresh)/deltaThresh) + Rm*I

 AdExIF:   Adaptive Exponential LIF:
           Rm*Cm * dVm/dt = -(Vm-Em) + deltaThresh * exp((Vm-thresh)/deltaThresh) + Rm*I - w,

           tau_w * dw/dt = a0*(Vm-Em) - w,

           At each spike, w -> w + b0 "

 AdThreshIF: Adaptive threshold LIF:
           Rm*Cm * dVm/dt = -(Vm-Em) + Rm*I,

           tauThresh * d threshAdaptive / dt = a0*(Vm-Em) - threshAdaptive,

           At each spike, threshAdaptive is increased by threshJump
           the spiking threshold adapts as thresh + threshAdaptive

 IzhIF:    Izhikevich:
           d Vm /dt = a0 * Vm^2 + b0 * Vm + c0 - u + I/Cm,

           d u / dt = a * ( b * Vm - u ),

           At each spike, u -> u + d,

           By default, a0 = 0.04e6/V/s, b0 = 5e3/s, c0 = 140 V/s are set to SI units,
           so use SI consistently, or change a0, b0, c0 also if you wish to use other units.
           Rm from Compartment is not used here, vReset is same as c in the usual formalism.
           At rest, u0 = b V0, and V0 = ( -(-b0-b) +/- sqrt((b0-b)^2 - 4*a0*c0)) / (2*a0).

On the command-line, in moose-examples/snippets directory, run ``python IntegrateFireZoo.py``.
The script will ask you which neuron you want to simulate and you can choose and run what you want.
Play with the parameters of the IF neurons in the source code.

    """
    neuronChoices = {'LIF':moose.LIF, 'QIF':moose.QIF, 'ExIF':moose.ExIF, 'AdExIF':moose.AdExIF,
                    'AdThreshIF':moose.AdThreshIF, 'IzhIF':moose.IzhIF}
    #### CHOOSE ONE OF THE NEURON KEYS AS choiceKey FROM BELOW DICTIONARY ####
    #choiceKey = 'LIF'
    #### No need, am inputting it from the user on the terminal
    choiceKeys = list(neuronChoices.keys()) # keys() does not retain the order in dict defn above!
    choiceIndex = eval(str(input('Choose a number corresponding to your desired neuron: '+str([(i,key) for (i,key) in enumerate(choiceKeys)])+' -- ')))
    choiceKey = choiceKeys[choiceIndex]
    neuronChoice = neuronChoices[choiceKey]

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

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

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

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

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

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

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

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

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

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

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

    plt.show()
コード例 #42
0
def main():
    """
    Simulate a pseudo-STDP protocol and plot the STDP kernel
    that emerges from Ca plasticity of Graupner and Brunel 2012.

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

    # ###########################################
    # Neuron models
    # ###########################################

    ## Leaky integrate and fire neuron
    Vrest = -65e-3 # V      # resting potential
    Vt_base = -45e-3 # V    # threshold
    Vreset = -55e-3 # V     # in current steps, Vreset is same as pedestal
    R = 1e8 # Ohm
    tau = 10e-3 # s
    refrT = 2e-3 # s

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

    ## two neurons: index 0 will be presynaptic, 1 will be postsynaptic
    network = moose.LIF( 'network', 2 );
    moose.le( '/network' )
    network.vec.Em = Vrest
    network.vec.thresh = Vt_base
    network.vec.refractoryPeriod = refrT
    network.vec.Rm = R
    network.vec.vReset = Vreset
    network.vec.Cm = tau/R
    network.vec.inject = 0.
    network.vec.initVm = Vrest

    #############################################
    # 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 = False          # use noisy weight updates given by noiseSD
    #noiseSD = 3.3501        # if noisy, use noiseSD (3.3501 from Higgins et al 2014)

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

    ## DP STDP curve (Fig 2C) values -- Table Suppl 1 in Graupner & Brunel 2012
    tauCa = 20e-3           # s # Ca decay time scale
    tauSyn = 150.0          # s # synaptic plasticity time scale
    CaPre = 1.0             # arb
    CaPost = 2.0            # arb
    delayD = 13.7e-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 = 200.0          # factor for depression term
    gammaP = 321.808        # factor for potentiation term

    J = 5e-3 # V            # delta function synapse, adds to Vm
    weight = 0.5            # 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 = False          # use noisy weight updates given by noiseSD
    noiseSD = 2.8284        # if noisy, use noiseSD (3.3501 in Higgins et al 2014)

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

    syn = moose.GraupnerBrunel2012CaPlasticitySynHandler( '/network/syn' )
    syn.numSynapses = 1     # 1 synapse
                            # many pre-synaptic inputs can connect to a synapse
    # synapse onto postsynaptic neuron
    moose.connect( syn, 'activationOut', network.vec[1], 'activation' )

    # synapse from presynaptic neuron
    moose.connect( network.vec[0],'spikeOut', syn.synapse[0], 'addSpike')

    # post-synaptic spikes also needed for STDP
    moose.connect( network.vec[1], 'spikeOut', syn, 'addPostSpike')

    syn.synapse[0].delay = 0.0
    syn.synapse[0].weight = weight
    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.weightScale = J        # weight ~1, weightScale ~ J
                               # weight*weightScale is activation,
                               # i.e. delta-fn added to postsynaptic Vm

    syn.weightMax = 1.0        # bounds on the weight
    syn.weightMin = 0.

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

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

    Vms = moose.Table( '/plotVms', 2 )
    moose.connect( network, 'VmOut', Vms, 'input', 'OneToOne')
    spikes = moose.Table( '/plotSpikes', 2 )
    moose.connect( network, 'spikeOut', spikes, 'input', 'OneToOne')
    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 the STDP curve with spaced pre-post spike pairs
    # ###########################################

    dt = 1e-3 # s
    # moose simulation
    moose.useClock( 0, '/network/syn', 'process' )
    moose.useClock( 1, '/network', 'process' )
    moose.useClock( 2, '/plotSpikes', 'process' )
    moose.useClock( 3, '/plotVms', '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.reinit()

    # function to make the aPlus and aMinus settle to equilibrium values
    settletime = 100e-3 # s
    def reset_settle():
        """ Call this between every pre-post pair
        to reset the neurons and make them settle to rest.
        """
        syn.synapse[0].weight = weight
        syn.Ca = 0.0
        moose.start(settletime)
        # Ca gets a jump at pre-spike+delayD
        # So this event can occur during settletime
        # So set Ca and weight once more after settletime
        syn.synapse[0].weight = weight
        syn.Ca = 0.0

    # function to inject a sharp current pulse to make neuron spike
    # immediately at a given time step
    def make_neuron_spike(nrnidx,I=1e-7,duration=1e-3):
        """ Inject a brief current pulse to
        make a neuron spike
        """
        network.vec[nrnidx].inject = I
        moose.start(duration)
        network.vec[nrnidx].inject = 0.

    dwlist_neg = []
    ddt = 2e-3 # s
    # since CaPlasticitySynHandler is event based
    # multiple pairs are needed for Ca to be registered above threshold
    # Values from Fig 2, last line of legend
    numpairs = 60           # number of spike parts per deltat
    t_between_pairs = 1.0   # time between each spike pair
    t_extent = 100e-3       # s  # STDP kernel extent,
                            # t_extent > t_between_pairs/2 inverts pre-post pairing!
    # dt = tpost - tpre
    # negative dt corresponds to post before pre
    print('-----------------------------------------------')
    for deltat in arange(t_extent,0.0,-ddt):
        reset_settle()
        for i in range(numpairs):
            # post neuron spike
            make_neuron_spike(1)
            moose.start(deltat)
            # pre neuron spike after deltat
            make_neuron_spike(0)
            moose.start(t_between_pairs)  # weight changes after pre-spike+delayD
                                          # must run for at least delayD after pre-spike
        dw = ( syn.synapse[0].weight - weight ) / weight
        print(('post before pre, dt = %1.3f s, dw/w = %1.3f'%(-deltat,dw)))
        dwlist_neg.append(dw)
    print('-----------------------------------------------')
    # positive dt corresponds to pre before post
    dwlist_pos = []
    for deltat in arange(ddt,t_extent+ddt,ddt):
        reset_settle()
        for i in range(numpairs):
            # pre neuron spike
            make_neuron_spike(0)
            moose.start(deltat)
            # post neuron spike after deltat
            make_neuron_spike(1)
            moose.start(t_between_pairs)
        dw = ( syn.synapse[0].weight - weight ) / weight
        print(('pre before post, dt = %1.3f s, dw/w = %1.3f'%(deltat,dw)))
        dwlist_pos.append(dw)
    print('-----------------------------------------------')
    print(('Each of the above pre-post pairs was repeated',\
            numpairs,'times, with',t_between_pairs,'s between pairs.'))
    print()
    print('Due to event based updates, Ca decays suddenly at events:')
    print('pre-spike, pre-spike + delayD, and post-spike;')
    print('apart from the usual CaPre and CaPost jumps at')
    print('pre-spike + delayD and post-spike respectively.')
    print('Because of the event based update, multiple pre-post pairs are used.')
    print()
    print('If you reduce the t_between_pairs,')
    print(' you\'ll see potentiation for the LTD part without using any triplet rule!')
    print()
    print("If you turn on noise, the weights fluctuate too much,")
    print(" not sure if there's a bug in my noise implementation.")
    print('-----------------------------------------------')

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

    # insert spikes so that Vm reset doesn't look weird
    Vmseries0 = Vms.vec[0].vector
    numsteps = len(Vmseries0)
    for t in spikes.vec[0].vector:
        Vmseries0[int(t/dt)-1] = 30e-3 # V
    Vmseries1 = Vms.vec[1].vector
    for t in spikes.vec[1].vector:
        Vmseries1[int(t/dt)-1] = 30e-3 # V

    timeseries = linspace(0.,1000*numsteps*dt,numsteps)
    # Voltage plots
    figure(facecolor='w')
    plot(timeseries,Vmseries0,color='r') # pre neuron's vm
    plot(timeseries,Vmseries1,color='b') # post neuron's vm
    xlabel('time (ms)')
    ylabel('Vm (V)')
    title("pre (r) and post (b) neurons' Vm")

    # Ca plots for the synapse
    figure(facecolor='w')
    plot(timeseries,CaTable.vector[:len(timeseries)],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 (ms)')
    ylabel('Ca (arb)')
    title("Ca conc in the synapse")

    # Weight plots for the synapse
    figure(facecolor='w')
    plot(timeseries,WtTable.vector[:len(timeseries)],color='r')
    xlabel('time (ms)')
    ylabel('Efficacy')
    title("Efficacy of the synapse")

    # STDP curve
    fig = figure(facecolor='w')
    ax = fig.add_subplot(111)
    ax.plot(arange(-t_extent,0,ddt)*1000,array(dwlist_neg),'.-r')
    ax.plot(arange(ddt,(t_extent+ddt),ddt)*1000,array(dwlist_pos),'.-b')
    xmin,xmax = ax.get_xlim()
    ymin,ymax = ax.get_ylim()
    ax.set_xticks([xmin,0,xmax])
    ax.set_yticks([ymin,0,ymax])
    ax.plot((0,0),(ymin,ymax),linestyle='dashed',color='k')
    ax.plot((xmin,xmax),(0,0),linestyle='dashed',color='k')
    ax.set_xlabel('$t_{post}-t_{pre}$ (ms)')
    ax.set_ylabel('$\Delta w / w$')
    fig.tight_layout()
    #fig.subplots_adjust(hspace=0.3,wspace=0.5) # use after tight_layout()

    show()
コード例 #43
0
ファイル: mload.py プロジェクト: dilawar/moose-gui
def loadFile(filename, target, solver="gsl", merge=True):
    """Try to load a model from specified `filename` under the element
    `target`.

    if `merge` is True, the contents are just loaded at target. If
    false, everything is deleted from the parent of target unless the
    parent is root.

    Returns
    -------
    a dict containing at least these three entries:

    modeltype: type of the loaded model.

    subtype: subtype of the loaded model, None if no specific subtype

    modelroot: root element of the model, None if could not be located - as is the case with Python scripts
    """
    num = 1
    newTarget = target
    while moose.exists(newTarget):
        newTarget = target + "-" + str(num)
        num = num + 1
    target = newTarget
    istext = True
    with open(filename, "rb") as infile:
        istext = mtypes.istextfile(infile)
    if not istext:
        print("Cannot handle any binary formats yet")
        return None
    parent, child = posixpath.split(target)
    p = moose.Neutral(parent)
    if not merge and p.path != "/":
        for ch in p.children:
            moose.delete(ch)
    try:
        modeltype = mtypes.getType(filename)
        subtype = mtypes.getSubtype(filename, modeltype)
    except KeyError:
        raise FileLoadError("Do not know how to handle this filetype: %s" % (filename))
    pwe = moose.getCwe()
    # self.statusBar.showMessage('Loading model, please wait')
    # app = QtGui.qApp
    # app.setOverrideCursor(QtGui.QCursor(Qt.Qt.BusyCursor)) #shows a hourglass - or a busy/working arrow
    if modeltype == "genesis":
        if subtype == "kkit" or subtype == "prototype":
            model, modelpath = loadGenCsp(target, filename, solver)
            if moose.exists(moose.element(modelpath).path):
                moose.Annotator(moose.element(modelpath).path + "/info").modeltype = "kkit"
            else:
                print(" path doesn't exists")
            moose.le(modelpath)
        else:
            print("Only kkit and prototype files can be loaded.")

    elif modeltype == "cspace":
        model, modelpath = loadGenCsp(target, filename)
        if moose.exists(modelpath):
            moose.Annotator((moose.element(modelpath).path + "/info")).modeltype = "cspace"
        addSolver(modelpath, "gsl")

    elif modeltype == "xml":
        if subtype == "neuroml":
            popdict, projdict = neuroml.loadNeuroML_L123(filename)
            # Circus to get the container of populations from loaded neuroml
            for popinfo in list(popdict.values()):
                for cell in list(popinfo[1].values()):
                    solver = moose.HSolve(cell.path + "/hsolve")
                    solver.target = cell.path
                    # model = cell.parent
                    # break
                # break

            # Moving model to a new location under the model name
            # model name is the filename without extension

            model = moose.Neutral("/" + splitext(basename(filename))[0])
            element = moose.Neutral(model.path + "/model")
            if moose.exists("/cells"):
                moose.move("/cells", element.path)
            if moose.exists("/elec"):
                moose.move("/elec", model.path)
            if moose.exists("/library"):
                moose.move("/library", model.path)

            # moose.move("cells/", cell.path)
        elif subtype == "sbml":
            if target != "/":
                if moose.exists(target):
                    moose.delete(target)
            model = mooseReadSBML(filename, target)
            if moose.exists(moose.element(model).path):
                moose.Annotator(moose.element(model).path + "/info").modeltype = "sbml"
            addSolver(target, "gsl")
    else:
        raise FileLoadError("Do not know how to handle this filetype: %s" % (filename))
    moose.setCwe(
        pwe
    )  # The MOOSE loadModel changes the current working element to newly loaded model. We revert that behaviour

    # TODO: check with Aditya how to specify the target for
    # neuroml reader
    # app.restoreOverrideCursor()
    return {"modeltype": modeltype, "subtype": subtype, "model": model}
コード例 #44
0
ファイル: mgblock.py プロジェクト: asiaszmek/moose
def test_mgblock():
    model = moose.Neutral('/model')
    data = moose.Neutral('/data')
    soma = moose.Compartment('/model/soma')
    soma.Em = -60e-3
    soma.Rm = 1e7
    soma.Cm = 1e-9

    ###################################################
    # This is where we create the synapse with MgBlock
    #--------------------------------------------------
    nmda = moose.SynChan('/model/soma/nmda')
    nmda.Gbar = 1e-9
    mgblock = moose.MgBlock('/model/soma/mgblock')
    mgblock.CMg = 2.0
    mgblock.KMg_A = 1/0.33
    mgblock.KMg_B = 1/60.0

    # The synHandler manages the synapses and their learning rules if any.
    synHandler = moose.SimpleSynHandler( '/model/soma/nmda/handler' )
    synHandler.synapse.num = 1
    moose.connect( synHandler, 'activationOut', nmda, 'activation' )



    # MgBlock sits between original channel nmda and the
    # compartment. The origChannel receives the channel message from
    # the nmda SynChan.
    moose.connect(soma, 'VmOut', nmda, 'Vm' )
    moose.connect(nmda, 'channelOut', mgblock, 'origChannel')
    moose.connect(mgblock, 'channel', soma, 'channel')
    # This is for comparing with MgBlock
    nmda_noMg = moose.copy(nmda, soma, 'nmda_noMg')
    moose.connect( nmda_noMg, 'channel', soma, 'channel')
    moose.le( nmda_noMg )

    #########################################
    # The rest is for experiment setup
    spikegen = moose.SpikeGen('/model/spike')
    pulse = moose.PulseGen('/model/input')
    pulse.delay[0] = 10e-3
    pulse.level[0] = 1.0
    pulse.width[0] = 50e-3
    moose.connect(pulse, 'output', spikegen, 'Vm')
    moose.le( synHandler )
    #syn = moose.element(synHandler.path + '/synapse' )
    syn = synHandler.synapse[0]
    syn.delay = simdt * 2
    syn.weight = 10
    moose.connect(spikegen, 'spikeOut', synHandler.synapse[0], 'addSpike')
    moose.le( nmda_noMg )
    noMgSyn = moose.element(nmda_noMg.path + '/handler/synapse' )
    noMgSyn.delay = 0.01
    noMgSyn.weight = 1
    moose.connect(spikegen, 'spikeOut', noMgSyn, 'addSpike')
    moose.showfields( syn )
    moose.showfields( noMgSyn )
    Gnmda = moose.Table('/data/Gnmda')
    moose.connect(Gnmda, 'requestOut', mgblock, 'getGk')
    Gnmda_noMg = moose.Table('/data/Gnmda_noMg')
    moose.connect(Gnmda_noMg, 'requestOut', nmda_noMg, 'getGk')
    Vm = moose.Table('/data/Vm')
    moose.connect(Vm, 'requestOut', soma, 'getVm')
    for i in range( 10 ):
        moose.setClock( i, simdt )
    moose.setClock( Gnmda.tick, plotdt )
    print((spikegen.dt, Gnmda.dt))
    moose.reinit()
    moose.start( simtime )
    t = pylab.linspace(0, simtime*1e3, len(Vm.vector))
    pylab.plot(t, (Vm.vector + 0.06) * 1000, label='Vm (mV)')
    pylab.plot(t, Gnmda.vector * 1e9, label='Gnmda (nS)')
    pylab.plot(t, Gnmda_noMg.vector * 1e9, label='Gnmda no Mg (nS)')
    pylab.legend()
    #data = pylab.vstack((t, Gnmda.vector, Gnmda_noMg.vector)).transpose()
    #pylab.savetxt('mgblock.dat', data)
    pylab.show()
コード例 #45
0
def make_network():
	size = 1024
	timestep = 0.2
	runtime = 100.0
	delayMin = timestep
	delayMax = 4
	weightMax = 0.02
	Vmax = 1.0
	thresh = 0.2
	tau = 1  # Range of tau
	tau0 = 0.5 # minimum tau
	refr = 0.3
	refr0 = 0.2
	connectionProbability = 0.1
	random.seed( 123 )
	nprand.seed( 456 )
	t0 = time.time()

	clock = moose.element( '/clock' )
	network = moose.IntFire( 'network', size, 1 );
	network.vec.bufferTime = [delayMax * 2] * size
	moose.le( '/network' )
	network.vec.numSynapses = [1] * size
	# Interesting. This fails because we haven't yet allocated
	# the synapses. I guess it is fair to avoid instances of objects that
	# don't have allocations.
	#synapse = moose.element( '/network/synapse' )
	sv = moose.vec( '/network/synapse' )
	print('before connect t = ', time.time() - t0)
	mid = moose.connect( network, 'spikeOut', sv, 'addSpike', 'Sparse')
	print('after connect t = ', time.time() - t0)
	#print mid.destFields
	m2 = moose.element( mid )
	m2.setRandomConnectivity( connectionProbability, 5489 )
	print('after setting connectivity, t = ', time.time() - t0)
	network.vec.Vm = [(Vmax*random.random()) for r in range(size)]
	network.vec.thresh = thresh
	network.vec.refractoryPeriod = [( refr0 + refr * random.random()) for r in range( size) ]
	network.vec.tau = [(tau0 + tau*random.random()) for r in range(size)]
	numSynVec = network.vec.numSynapses
	print('Middle of setup, t = ', time.time() - t0)
	numTotSyn = sum( numSynVec )
	for item in network.vec:
		neuron = moose.element( item )
		neuron.synapse.delay = [ (delayMin + random.random() * delayMax) for r in range( len( neuron.synapse ) ) ] 
		neuron.synapse.weight = nprand.rand( len( neuron.synapse ) ) * weightMax
	print('after setup, t = ', time.time() - t0, ", numTotSyn = ", numTotSyn)

	"""

	netvec = network.vec
	for i in range( size ):
		synvec = netvec[i].synapse.vec
		synvec.weight = [ (random.random() * weightMax) for r in range( synvec.len )] 
		synvec.delay = [ (delayMin + random.random() * delayMax) for r in range( synvec.len )] 
	"""

	#moose.useClock( 9, '/postmaster', 'process' )
	moose.useClock( 0, '/network', 'process' )
	moose.setClock( 0, timestep )
	moose.setClock( 9, timestep )
	t1 = time.time()
	moose.reinit()
	print('reinit time t = ', time.time() - t1)
	network.vec.Vm = [(Vmax*random.random()) for r in range(size)]
	print('setting Vm , t = ', time.time() - t1)
	t1 = time.time()
	print('starting')
	moose.start(runtime)
	print('runtime, t = ', time.time() - t1)
	print('Vm100:103', network.vec.Vm[100:103])
	print('Vm900:903', network.vec.Vm[900:903])
	print('weights 100:', network.vec[100].synapse.delay[0:5])
	print('weights 900:', network.vec[900].synapse.delay[0:5])
コード例 #46
0
def main():
    '''
    On the command-line, in moose-examples/snippets directory, run ``python IntegrateFireZoo.py``.  
    The script will ask you which neuron you want to simulate and you can choose and run what you want.  
    Play with the parameters of the IF neurons in the source code.
    '''
    neuronChoices = {'LIF':moose.LIF, 'QIF':moose.QIF, 'ExIF':moose.ExIF, 'AdExIF':moose.AdExIF,
                    'AdThreshIF':moose.AdThreshIF, 'IzhIF':moose.IzhIF}
    #### CHOOSE ONE OF THE NEURON KEYS AS choiceKey FROM BELOW DICTIONARY ####
    #choiceKey = 'LIF'
    #### No need, am inputting it from the user on the terminal
    choiceKeys = list(neuronChoices.keys()) # keys() does not retain the order in dict defn above!
    choiceIndex = eval(input('Choose a number corresponding to your desired neuron: '+ \
                        str([(i,key) for (i,key) in enumerate(choiceKeys)])+' -- '))
    choiceKey = choiceKeys[choiceIndex]
    neuronChoice = neuronChoices[choiceKey]

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

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

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

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

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

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

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

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

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

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

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

    plt.show()
コード例 #47
0
## Leaky integrate and fire neuron
Vrest = -65e-3  # V      # resting potential
Vt_base = -45e-3  # V    # threshold
Vreset = -55e-3  # V     # in current steps, Vreset is same as pedestal
R = 1e8  # Ohm
tau = 10e-3  # s
refrT = 2e-3  # s

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

## two neurons: index 0 will be presynaptic, 1 will be postsynaptic
network = moose.LIF("network", 2)
moose.le("/network")
network.vec.Em = Vrest
network.vec.thresh = Vt_base
network.vec.refractoryPeriod = refrT
network.vec.Rm = R
network.vec.vReset = Vreset
network.vec.Cm = tau / R
network.vec.inject = 0.0
network.vec.initVm = Vrest

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

### Cortical slice values -- Table Suppl 2 in Graupner & Brunel 2012
### Also used in Higgins et al 2014
コード例 #48
0
ファイル: mgblock.py プロジェクト: NeuroArchive/moose
def test_mgblock():
    """
    Demonstrates the use of MgBlock.
    Creates an NMDA channel with MgBlock and another without.
    Connects them up to the compartment on one hand, and to a
    SynHandler on the other, so as to receive synaptic input.
    Delivers two pulses to each receptor, with a small delay in between.

    Plots out the conductance change at each receptor and the reslting
    membrane potential rise at the compartment.

    Note that these NMDA channels do NOT separate out the contributions
    due to calcium and other ions. To do this correctly one should use
    the GHK object.
    """
    model = moose.Neutral('/model')
    data = moose.Neutral('/data')
    soma = moose.Compartment('/model/soma')
    soma.Em = -60e-3
    soma.Rm = 1e7
    soma.Cm = 1e-9

    ###################################################
    # This is where we create the synapse with MgBlock
    #--------------------------------------------------
    nmda = moose.SynChan('/model/soma/nmda')
    nmda.Gbar = 1e-9
    mgblock = moose.MgBlock('/model/soma/mgblock')
    mgblock.CMg = 2.0
    mgblock.KMg_A = 1/0.33
    mgblock.KMg_B = 1/60.0

    # The synHandler manages the synapses and their learning rules if any.
    synHandler = moose.SimpleSynHandler( '/model/soma/nmda/handler' )
    synHandler.synapse.num = 1
    moose.connect( synHandler, 'activationOut', nmda, 'activation' )


    
    # MgBlock sits between original channel nmda and the
    # compartment. The origChannel receives the channel message from
    # the nmda SynChan.
    moose.connect(soma, 'VmOut', nmda, 'Vm' )
    moose.connect(nmda, 'channelOut', mgblock, 'origChannel')
    moose.connect(mgblock, 'channel', soma, 'channel')    
    # This is for comparing with MgBlock
    nmda_noMg = moose.copy(nmda, soma, 'nmda_noMg')
    moose.connect( nmda_noMg, 'channel', soma, 'channel')
    moose.le( nmda_noMg )

    #########################################
    # The rest is for experiment setup
    spikegen = moose.SpikeGen('/model/spike')
    pulse = moose.PulseGen('/model/input')
    pulse.delay[0] = 10e-3
    pulse.level[0] = 1.0
    pulse.width[0] = 50e-3
    moose.connect(pulse, 'output', spikegen, 'Vm')
    moose.le( synHandler )
    #syn = moose.element(synHandler.path + '/synapse' )
    syn = synHandler.synapse[0]
    syn.delay = simdt * 2
    syn.weight = 10
    moose.connect(spikegen, 'spikeOut', synHandler.synapse[0], 'addSpike')
    moose.le( nmda_noMg )
    noMgSyn = moose.element(nmda_noMg.path + '/handler/synapse' )
    noMgSyn.delay = 0.01
    noMgSyn.weight = 1
    moose.connect(spikegen, 'spikeOut', noMgSyn, 'addSpike')
    moose.showfields( syn )
    moose.showfields( noMgSyn )
    Gnmda = moose.Table('/data/Gnmda')
    moose.connect(Gnmda, 'requestOut', mgblock, 'getGk')
    Gnmda_noMg = moose.Table('/data/Gnmda_noMg')
    moose.connect(Gnmda_noMg, 'requestOut', nmda_noMg, 'getGk')
    Vm = moose.Table('/data/Vm')
    moose.connect(Vm, 'requestOut', soma, 'getVm')
    for i in range( 10 ):
        moose.setClock( i, simdt )
    moose.setClock( Gnmda.tick, plotdt )
    print spikegen.dt, Gnmda.dt
    moose.reinit()
    moose.start( simtime )
    t = pylab.linspace(0, simtime*1e3, len(Vm.vector))
    pylab.plot(t, (Vm.vector + 0.06) * 1000, label='Vm (mV)')
    pylab.plot(t, Gnmda.vector * 1e9, label='Gnmda (nS)')
    pylab.plot(t, Gnmda_noMg.vector * 1e9, label='Gnmda no Mg (nS)')
    pylab.legend()
    #data = pylab.vstack((t, Gnmda.vector, Gnmda_noMg.vector)).transpose()
    #pylab.savetxt('mgblock.dat', data)
    pylab.show()
コード例 #49
0
CaRGbar = 0.07
CaLGbar = 0.51
CaNGbar = 1.76
KSKGbar = 4.28006e-02
KBKGbar = 5.08559e-03

ChP = 'Srikanth2015/ChannelProtos_Sri2015_base'
sm_diam = 100e-6
sm_len = 100e-6

Ca_tau = 0.2 / 7  #Not sure about this
Ca_B = np.pi * sm_diam * 1e16 / 2 / F  #Not sure about this

try:
    # [moose.delete(x) for x in ['/model', '/library']]
    for ff in moose.le('library'):
        if ff != '/library[0]/KBK_chan':
            moose.delete(ff)
    [moose.delete(x) for x in ['/model']]
except:
    pass

rdes = rd.rdesigneur(
    # cellProto = [['somaProto', 'soma', 12.76e-6, 0.01e-6]],
    cellProto=[['somaProto', 'soma', sm_diam, sm_len]],
    chanProto=[
        [ChP + '.Na_SChan()', 'Na_Schan'],
        [ChP + '.KDR_SChan()', 'KDR_Schan'],
        [ChP + '.KA_SChan()', 'KA_Schan'],
        [ChP + '.KM_Chan()', 'KM_chan'],
        [ChP + '.h_Chan()', 'h_chan'],
コード例 #50
0
ファイル: buildCA1Pyr.py プロジェクト: BhallaLab/benchmarks
def main():
    cm = ChannelML( {'temperature': 32 })
    cm.readChannelMLFromFile( 'CA1_migliore_reference/hd.xml' )
    cm.readChannelMLFromFile( 'CA1_migliore_reference/kap.xml' )
    cm.readChannelMLFromFile( 'CA1_migliore_reference/kad.xml' )
    cm.readChannelMLFromFile( 'CA1_migliore_reference/kdr.xml' )
    cm.readChannelMLFromFile( 'CA1_migliore_reference/na3.xml' )
    cm.readChannelMLFromFile( 'CA1_migliore_reference/nax.xml' )
    if ( len( sys.argv ) < 2 ):
        print("Usage: ", sys.argv[0], " filename")
        return

    # filename = "./Bhavika_swcplusnmlfiles/preliminarily corrected nmlfiles/ascoli+buzsaki/valid/" + sys.argv[1]
    filename = sys.argv[1]
    moose.Neutral( '/model' )
    # Load in the swc file.
    cell = moose.loadModel( filename, '/model/ca1' )

    for i in moose.wildcardFind( '/library/##' ):
        i.tick = -1

    chanDistrib = [ \
            "EM", "#", "-58e-3", \
            "initVm", "#", "-65e-3", \
            "RM", "#", "2.8", \
            "CM", "#", "0.01", \
            "RA", "#", "1.5", \
            "RA", "#axon#", "0.5", \

            "hd", "#dend#,#apical#", "5e-2*(1+(r*3e4))", \
            "kdr", "#", "100", \
            "na3", "#soma#,#dend#,#apical#", "250", \
            "nax", "#axon#", "1250", \
            "kap", "#axon#,#soma#", "300", \
            "kap", "#dend#,#apical#", "150*(1+sign(100-r*1e6)) * (1+(r*1e4))", \
            "kad", "#dend#,#apical#", "150*(1+sign(r*1e6-100))*(1+r*1e4)", \
            ]
    moose.showfields( cell[0] )
    cell[0].channelDistribution = chanDistrib
    cell[0].parseChanDistrib()
    for i in range( 8 ):
        moose.setClock( i, simdt )
    hsolve = moose.HSolve( '/model/ca1/hsolve' )
    hsolve.dt = simdt
    hsolve.target = '/model/ca1/soma'
    '''
    '''
    moose.reinit()
    makePlot( cell[0] )

    # Now we set up the display
    moose.le( '/model/ca1/soma' )
    soma = moose.element( '/model/ca1/soma' )
    kap = moose.element( '/model/ca1/soma/kap' )

    graphs = moose.Neutral( '/graphs' )
    vtab = moose.Table( '/graphs/vtab' )
    moose.connect( vtab, 'requestOut', soma, 'getVm' )
    kaptab = moose.Table( '/graphs/kaptab' )
    moose.connect( kaptab, 'requestOut', kap, 'getGk' )

    compts = moose.wildcardFind( "/model/ca1/#[ISA=CompartmentBase]" )
    '''
    for i in compts:
        if moose.exists( i.path + '/Na' ):
            print i.path, moose.element( i.path + '/Na' ).Gbar, \
                moose.element( i.path + '/K_DR' ).Gbar, \
                i.Rm, i.Ra, i.Cm
    '''
    '''
    Na = moose.wildcardFind( '/model/ca1/#/Na#' )
    print Na
    Na2 = []
    for i in compts:
        if ( moose.exists( i.path + '/NaF2' ) ):
            Na2.append(  moose.element( i.path + '/NaF2' ) )
        if ( moose.exists( i.path + '/NaPF_SS' ) ):
            Na2.append(  moose.element( i.path + '/NaPF_SS' ) )
    ecomptPath = map( lambda x : x.path, compts )
    print "Na placed in ", len( Na ), len( Na2 ),  " out of ", len( compts ), " compts."
    '''
    compts[0].inject = inject
    ecomptPath = [x.path for x in compts]

    # Graphics stuff here.
    app = QtGui.QApplication(sys.argv)
    morphology = moogli.read_morphology_from_moose(name = "", path = "/model/ca1")
    morphology.create_group( "group_all", ecomptPath, -0.08, 0.02, \
            [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.1] ) 

    viewer = moogli.DynamicMorphologyViewerWidget(morphology)
    def callback( morphology, viewer ):
        moose.start( frameRunTime )
        Vm = [moose.element( x ).Vm for x in compts]
        morphology.set_color( "group_all", Vm )
        currTime = moose.element( '/clock' ).currentTime
        #print currTime, compts[0].Vm
        if ( currTime < runtime ):
            return True
        return False

    viewer.set_callback( callback, idletime = 0 )
    viewer.showMaximized()
    viewer.show()
    app.exec_()
    t = numpy.arange( 0, runtime, vtab.dt )
    fig = plt.figure()
    p1 = fig.add_subplot(311)
    p2 = fig.add_subplot(312)
    p2.plot( t,  vtab.vector, label = 'Vm Soma' )
    p2.legend()
    p3 = fig.add_subplot(313)
    p3.plot( t, kaptab.vector, label = 'kap Soma' )
    p3.legend()
    plt.show()
コード例 #51
0
def makeModel():
    # create container for model
    model = moose.Neutral( 'model' )
    compartment = moose.CubeMesh( '/model/compartment' )
    compartment.volume = 1e-15
    # the mesh is created automatically by the compartment
    moose.le( '/model/compartment' )
    mesh = moose.element( '/model/compartment/mesh' )

    # create molecules and reactions
    a = moose.Pool( '/model/compartment/a' )
    b = moose.Pool( '/model/compartment/b' )
    c = moose.Pool( '/model/compartment/c' )
    enz1 = moose.Enz( '/model/compartment/b/enz1' )
    enz2 = moose.Enz( '/model/compartment/c/enz2' )
    cplx1 = moose.Pool( '/model/compartment/b/enz1/cplx' )
    cplx2 = moose.Pool( '/model/compartment/c/enz2/cplx' )
    reac = moose.Reac( '/model/compartment/reac' )

    # connect them up for reactions
    moose.connect( enz1, 'sub', a, 'reac' )
    moose.connect( enz1, 'prd', b, 'reac' )
    moose.connect( enz1, 'enz', b, 'reac' )
    moose.connect( enz1, 'cplx', cplx1, 'reac' )

    moose.connect( enz2, 'sub', b, 'reac' )
    moose.connect( enz2, 'prd', a, 'reac' )
    moose.connect( enz2, 'enz', c, 'reac' )
    moose.connect( enz2, 'cplx', cplx2, 'reac' )

    moose.connect( reac, 'sub', a, 'reac' )
    moose.connect( reac, 'prd', b, 'reac' )

    # connect them up to the compartment for volumes
    #for x in ( a, b, c, cplx1, cplx2 ):
    #                        moose.connect( x, 'mesh', mesh, 'mesh' )

    # Assign parameters
    a.concInit = 1
    b.concInit = 0
    c.concInit = 0.01
    enz1.kcat = 0.4
    enz1.Km = 4
    enz2.kcat = 0.6
    enz2.Km = 0.01
    reac.Kf = 0.001
    reac.Kb = 0.01

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

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

    # We need a finer timestep than the default 0.1 seconds,
    # in order to get numerical accuracy.
    for i in range (11, 15 ):
        moose.setClock( i, 0.001 ) # for computational objects
コード例 #52
0
def loadFile(filename, target, solver="gsl", merge=True):
    """Try to load a model from specified `filename` under the element
    `target`.

    if `merge` is True, the contents are just loaded at target. If
    false, everything is deleted from the parent of target unless the
    parent is root.

    Returns
    -------
    a dict containing at least these three entries:

    modeltype: type of the loaded model.

    subtype: subtype of the loaded model, None if no specific subtype

    modelroot: root element of the model, None if could not be located - as is the case with Python scripts
    """
    num = 1
    newTarget = target
    while moose.exists(newTarget):
        newTarget = target + "-" + str(num)
        num = num + 1
    target = newTarget
    istext = True
    with open(filename, 'rb') as infile:
        istext = mtypes.istextfile(infile)
    if not istext:
        print 'Cannot handle any binary formats yet'
        return None
    parent, child = posixpath.split(target)
    p = moose.Neutral(parent)
    if not merge and p.path != '/':
        for ch in p.children:
            moose.delete(ch)
    try:
        modeltype = mtypes.getType(filename)
        subtype = mtypes.getSubtype(filename, modeltype)
    except KeyError:
        raise FileLoadError('Do not know how to handle this filetype: %s' %
                            (filename))
    pwe = moose.getCwe()
    #self.statusBar.showMessage('Loading model, please wait')
    # app = QtGui.qApp
    # app.setOverrideCursor(QtGui.QCursor(Qt.Qt.BusyCursor)) #shows a hourglass - or a busy/working arrow
    if modeltype == 'genesis':
        if subtype == 'kkit' or subtype == 'prototype':
            model, modelpath = loadGenCsp(target, filename, solver)
            if moose.exists(moose.element(modelpath).path):
                moose.Annotator(moose.element(modelpath).path +
                                '/info').modeltype = "kkit"
            else:
                print " path doesn't exists"
            moose.le(modelpath)
        else:
            print 'Only kkit and prototype files can be loaded.'

    elif modeltype == 'cspace':
        model, modelpath = loadGenCsp(target, filename)
        if moose.exists(modelpath):
            moose.Annotator(
                (moose.element(modelpath).path + '/info')).modeltype = "cspace"
        addSolver(modelpath, 'gsl')

    elif modeltype == 'xml':
        if subtype == 'neuroml':
            popdict, projdict = neuroml.loadNeuroML_L123(filename)
            # Circus to get the container of populations from loaded neuroml
            for popinfo in popdict.values():
                for cell in popinfo[1].values():
                    solver = moose.HSolve(cell.path + "/hsolve")
                    solver.target = cell.path
                    # model = cell.parent
                    # break
                # break

            # Moving model to a new location under the model name
            # model name is the filename without extension

            model = moose.Neutral("/" + splitext(basename(filename))[0])
            element = moose.Neutral(model.path + "/model")
            if (moose.exists("/cells")): moose.move("/cells", element.path)
            if (moose.exists("/elec")): moose.move("/elec", model.path)
            if (moose.exists("/library")): moose.move("/library", model.path)

            # moose.move("cells/", cell.path)
        elif subtype == 'sbml':
            if target != '/':
                if moose.exists(target):
                    moose.delete(target)
            model = mooseReadSBML(filename, target)
            if moose.exists(moose.element(model).path):
                moose.Annotator(moose.element(model).path +
                                '/info').modeltype = "sbml"
            addSolver(target, 'gsl')
    else:
        raise FileLoadError('Do not know how to handle this filetype: %s' %
                            (filename))
    moose.setCwe(
        pwe
    )  # The MOOSE loadModel changes the current working element to newly loaded model. We revert that behaviour

    # TODO: check with Aditya how to specify the target for
    # neuroml reader
    # app.restoreOverrideCursor()
    return {'modeltype': modeltype, 'subtype': subtype, 'model': model}
コード例 #53
0
ファイル: multi1.py プロジェクト: dilawar/nsdf
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.
コード例 #54
0
ファイル: multi2.py プロジェクト: rgayatri23/moose-examples
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, smdsolve.numPools
    assert (smstoich.numAllPools == 35)
    assert (smdsolve.numPools == 30)
    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/##"
    print 'psd num Pools = ', pmstoich.numAllPools, pmdsolve.numPools
    assert (pmstoich.numAllPools == 55)
    assert (pmdsolve.numPools == 48)
    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 = 5e-3  # 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.
コード例 #55
0
ファイル: Fig6BCDE.py プロジェクト: BhallaLab/moose-examples
    viewer.attach_shapes(list(lifs.shapes.values()))
    # print "Attached Shapes"
    view = moogli.View("view")
    viewer.attach_view(view)
    # print "Attached View"
    return viewer

if __name__=='__main__':
    plt.ion()
    ## ExcInhNetBase has unconnected neurons,
    ## ExcInhNet connects them
    ## Instantiate either ExcInhNetBase or ExcInhNet below
    #net = ExcInhNetBase(N=N)
    net = ExcInhNet(N=N)
    print(net)
    moose.le( '/' )
    moose.le( '/network' )
    rdes = buildRdesigneur()
    rdes.buildModel( '/model' )
    buildNeuronPlots( rdes )
    connectDetailedNeuron()

    app = QtGui.QApplication(sys.argv)
    viewer = create_viewer(rdes)
    viewer.showMaximized()
    viewer.start()
    app.exec_()

    ## Important to distribute the initial Vm-s
    ## else weak coupling gives periodic synchronous firing
    plotif = True
コード例 #56
0
moose.setCwe( '/library' )
proto18.make_Ca()
proto18.make_Ca_conc()
proto18.make_K_AHP()
proto18.make_K_C()
proto18.make_Na()
proto18.make_K_DR()
proto18.make_K_A()
proto18.make_glu()
proto18.make_NMDA()
proto18.make_Ca_NMDA()
proto18.make_NMDA_Ca_conc()
proto18.make_axon()

cellId = moose.loadModel( 'ca1_asym.p', '/cell', "hsolve" )
moose.le( cellId )
moose.le( '/cell/lat_14_1' )
#le( '/cell' )
graphs = moose.Neutral( '/graphs' )
tab = moose.Table( '/graphs/soma' )
catab = moose.Table( '/graphs/ca' )
soma = moose.element( '/cell/soma' )
soma.inject = 2e-10
moose.connect( tab, 'requestOut', soma, 'getVm' )
capool = moose.element( '/cell/soma/Ca_conc' )
moose.connect( catab, 'requestOut', capool, 'getCa' )
print 1
dt = 50e-6
moose.setClock( 0, dt )
moose.setClock( 1, dt )
moose.setClock( 2, dt )
コード例 #57
0
def make_network():
    """
    This snippet sets up a recurrent network of IntFire objects, using
    SimpleSynHandlers to deal with spiking events.
    It isn't very satisfactory as activity runs down after a while.
    It is a good example for using the IntFire, setting up random
    connectivity, and using SynHandlers.
    """
    global all_done_
    done = mp.Value('i', 0)
    q = mp.Queue()
    th = mp.Process(target=streamer_handler, args=(done, q))
    th.start()

    size = 1024
    dt = 0.2
    runsteps = 10
    delayMin = 0
    delayMax = 4
    weightMax = 1
    Vmax = 1.0
    thresh = 0.4
    refractoryPeriod = 0.4
    tau = 0.5
    connectionProbability = 0.01
    random.seed( 123 )
    np.random.seed( 456 )
    t0 = time.time()

    network = moose.IntFire( 'network', size );
    syns = moose.SimpleSynHandler( '/network/syns', size );
    moose.connect( syns, 'activationOut', network, 'activation', 'OneToOne' )
    moose.le( '/network' )
    syns.vec.numSynapses = [1] * size
    sv = moose.vec( '/network/syns/synapse' )
    print('before connect t = %.3f'%(time.time() - t0))
    mid = moose.connect( network, 'spikeOut', sv, 'addSpike', 'Sparse')
    print('after connect t = %.3f'%(time.time() - t0))
    #print mid.destFields
    m2 = moose.element( mid )
    m2.setRandomConnectivity( connectionProbability, 5489 )
    print('after setting connectivity, t=%.3f'%(time.time() - t0))
    #network.vec.Vm = [(Vmax*random.random()) for r in range(size)]
    network.vec.Vm = np.random.rand( size ) * Vmax
    network.vec.thresh = thresh
    network.vec.refractoryPeriod = refractoryPeriod
    network.vec.tau = tau
    numSynVec = syns.vec.numSynapses
    print('Middle of setup, t = %.3f'%(time.time() - t0))
    numTotSyn = sum( numSynVec )
    print((numSynVec.size, ', tot = ', numTotSyn,  ', numSynVec = ', numSynVec))
    for item in syns.vec:
        h = moose.element(item)
        h.synapse.delay = delayMin + (delayMax-delayMin) * np.random.rand(len(h.synapse))
        h.synapse.weight = np.random.rand(len(h.synapse)) * weightMax
    print('After setup, t = %.3f'%(time.time()-t0))

    numStats = 100
    stats = moose.SpikeStats( '/stats', numStats )
    stats.vec.windowLength = 1 # timesteps to put together.
    plots = moose.Table( '/plot', numStats )
    convergence = size // numStats
    for i in range( numStats ):
        for j in range( size//numStats ):
            k = i * convergence + j
            moose.connect( network.vec[k], 'spikeOut', stats.vec[i], 'addSpike' )
    moose.connect( plots, 'requestOut', stats, 'getMean', 'OneToOne' )

    t1 = time.time()
    moose.reinit()
    print('reinit time t = %.3f'%(time.time() - t1))
    network.vec.Vm = np.random.rand( size ) * Vmax
    print('setting Vm , t = %.3f'%(time.time() - t1))
    t1 = time.time()
    moose.start(runsteps * dt, 1)
    time.sleep(0.1)
    done.value = 1
    print('runtime, t = %.3f'%(time.time() - t1))
    print(network.vec.Vm[99:103], network.vec.Vm[900:903])
    res = q.get()

    for tabPath in res:
        aWithTime = res[tabPath]
        a = aWithTime[1::2]
        b = moose.element(tabPath).vector
        print( tabPath, len(a), len(b) )
        if len(a) == len(b):
            assert np.equal(a, b).all()
        else:
            print( "Table did not equal size. The last table is allowed to "
                    " have fewer entries." )


    th.join()
    print( 'All done' )