コード例 #1
0
ファイル: run92_simple.py プロジェクト: Ainurrohmah/Scripts
def main( runTime ):
    try:
        moose.delete('/acc92')
        print("Deleted old model")
    except Exception as  e:
        print("Could not clean. model not loaded yet")

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

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

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

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

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

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

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

    print('[INFO] Saving data to csv files in %s' % dataDir)
    tabPath1 = os.path.join( dataDir, '%s_%s.csv' % (table.name, runTime))
    numpy.savetxt(tabPath1, numpy.matrix([t, table.vector]).T, newline='\n')
    tabPath2 = os.path.join( dataDir, '%s_%s.csv' % (table1.name, runTime) )
    numpy.savetxt(tabPath2, numpy.matrix([t1, table1.vector]).T, newline='\n')
コード例 #2
0
def assign_clocks(model_container_list, simdt, plotdt):
    """
    Assign clocks to elements under the listed paths.

    This should be called only after all model components have been
    created. Anything created after this will not be scheduled.

    """
    global inited
    # `inited` is for avoiding double scheduling of the same object
    if not inited:
        print(('SimDt=%g, PlotDt=%g' % (simdt, plotdt)))
        moose.setClock(0, simdt)
        moose.setClock(1, simdt)
        moose.setClock(2, simdt)
        moose.setClock(3, simdt)
        moose.setClock(4, plotdt)
        for path in model_container_list:
            print(('Scheduling elements under:', path))
            moose.useClock(0, '%s/##[TYPE=Compartment]' % (path), 'init')
            moose.useClock(1, '%s/##[TYPE=Compartment]' % (path), 'process')
            moose.useClock(2, '%s/##[TYPE=SynChan],%s/##[TYPE=HHChannel]' % (path, path), 'process')
            moose.useClock(3, '%s/##[TYPE=SpikeGen],%s/##[TYPE=PulseGen]' % (path, path), 'process')
        moose.useClock(4, '/data/##[TYPE=Table]', 'process')
        inited = True
    moose.reinit()
コード例 #3
0
ファイル: singlemsgcross.py プロジェクト: csiki/MOOSE
def test_crossing_single():
    """This function creates an ematrix of two PulseGen elements and
    another ematrix of two Table elements.

    The two pulsegen elements have same amplitude but opposite phase.

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

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

    """
    size = 2
    pg = moose.PulseGen('pulsegen', size)
    for ix, ii in enumerate(pg.vec):
        pulse = moose.element(ii)
        pulse.delay[0] = 1.0
        pulse.width[0] = 2.0
        pulse.level[0] = (-1)**ix
    tab = moose.Table('table', size)
    moose.connect(tab.vec[0], 'requestOut', pg.vec[1], 'getOutputValue', 'Single')
    moose.connect(tab.vec[1], 'requestOut', pg.vec[0], 'getOutputValue', 'Single')
    print 'Neighbors:'
    for t in tab.vec:
        print t.path
        for n in moose.element(t).neighbors['requestOut']:
            print 'requestOut <-', n.path
    moose.setClock(0, 0.1)
    moose.useClock(0, '/##', 'process')
    moose.start(5)
    for ii in tab.vec:
        t = moose.Table(ii).vector
        print len(t)
        pylab.plot(t)
    pylab.show()
コード例 #4
0
ファイル: twocells.py プロジェクト: asiaszmek/moose
def main():
    """
A demo to create a network of single compartmental neurons connected
via alpha synapses. Here SynChan class is used to setup synaptic
connection between two single-compartmental Hodgkin-Huxley type
neurons.

    """
    simtime = 0.1
    simdt = 0.25e-5
    plotdt = 0.25e-3
    netinfo = create_model()
    expinfo = setup_experiment(netinfo['presynaptic'],
                               netinfo['postsynaptic'],
                               netinfo['synchan'])
    vm_a = expinfo['Vm_pre']
    vm_b = expinfo['Vm_post']
    gksyn_b = expinfo['Gk_syn']
    for ii in range(10):
        moose.setClock(ii, simdt)
    moose.setClock(18, plotdt)
    moose.reinit()
    moose.start(simtime)
    plt.subplot(211)
    plt.plot(vm_a.vector*1e3, color='b', label='presynaptic Vm (mV)')
    plt.plot(vm_b.vector*1e3, color='g', label='postsynaptic Vm (mV)')
    plt.plot(expinfo['stimulus'].vector * 1e9, color='r', label='injected current (nA)')
    plt.legend()
    plt.subplot(212)
    plt.plot(expinfo['Gk_syn'].vector*1e9, color='orange', label='Gk_synapse (nS)')
    plt.legend()
    plt.tight_layout()
    plt.show()
コード例 #5
0
ファイル: issue_93.py プロジェクト: rahulgayatri23/moose-core
def loadAndRun(solver=True):
    simtime = 500e-3
    model = moose.loadModel('../data/h10.CNG.swc', '/cell')
    comp = moose.element('/cell/apical_e_177_0')
    soma = moose.element('/cell/soma')
    for i in range(10):
        moose.setClock(i, dt)
    if solver:
        solver = moose.HSolve('/cell/solver')
        solver.target = soma.path
        solver.dt = dt
    stim = moose.PulseGen('/cell/stim')
    stim.delay[0] = 50e-3
    stim.delay[1] = 1e9
    stim.level[0] = 1e-9
    stim.width[0] = 2e-3    
    moose.connect(stim, 'output', comp, 'injectMsg')
    tab = moose.Table('/cell/Vm')
    moose.connect(tab, 'requestOut', comp, 'getVm')
    tab_soma = moose.Table('/cell/Vm_soma')
    moose.connect(tab_soma, 'requestOut', soma, 'getVm')
    moose.reinit()
    print('[INFO] Running for %s' % simtime)
    moose.start(simtime )
    vec = tab_soma.vector 
    moose.delete( '/cell' )
    return vec
コード例 #6
0
def example():
    """In this example we create a square-pulse generator object and
    record the output using a table.

    The steps are:

    1. Create a PulseGen element `pulse`.

    2. Set `delay[0]=1.0`, `width[0]=0.2`, `level[0]=0.5`, so it
       generates 0.2 s wide square pulses with 0.5 amplitude every 1 s.

    3. Create a Table element `tab`.

    4. Connect the `outputValue` field of `pulse` to `tab`.

    5. We set tick-interval of ticks 0 and 1 to 0.01 and schedule
       `pulse` on tick 0 and `tab` on tick 1.

    5. Run the simulation for 5 s and save data to the ascii file
       `output_tabledemo.csv`.

    """
    pg = moose.PulseGen('pulse')
    pg.delay[0] = 1.0
    pg.width[0] = 0.2
    pg.level[0] = 0.5
    tab = moose.Table('tab')
    moose.connect(tab, 'requestOut', pg, 'getOutputValue')
    moose.setClock(0, 0.01)
    moose.setClock(1, 0.01)
    moose.useClock(0, pg.path, 'process')
    moose.useClock(1, tab.path, 'process')
    moose.reinit()
    moose.start(5.0)
    tab.plainPlot('output_tabledemo.csv')
コード例 #7
0
ファイル: ionchannel.py プロジェクト: asiaszmek/moose
def current_step_test(simtime, simdt, plotdt):
    """
    Create a single compartment and set it up for applying a step
    current injection.

    We use a PulseGen object to generate a 40 ms wide 1 nA current
    pulse that starts 20 ms after start of simulation.

    """
    model = moose.Neutral('/model')
    comp = create_1comp_neuron('/model/neuron')
    stim = moose.PulseGen('/model/stimulus')
    stim.delay[0] = 20e-3
    stim.level[0] = 1e-9
    stim.width[0] = 40e-3
    stim.delay[1] = 1e9
    moose.connect(stim, 'output', comp, 'injectMsg')
    data = moose.Neutral('/data')
    current_tab = moose.Table('/data/current')
    moose.connect(current_tab, 'requestOut', stim, 'getOutputValue')
    vm_tab = moose.Table('/data/Vm')
    moose.connect(vm_tab, 'requestOut', comp, 'getVm')
    for i in range(10):
        moose.setClock(i, simdt)
    moose.setClock(8, plotdt)
    moose.reinit()
    moose.start(simtime)
    ts = np.linspace(0, simtime, len(vm_tab.vector))
    return ts, current_tab.vector, vm_tab.vector,
コード例 #8
0
def main():
    makeModel()
    solver = moose.GslStoich("/model/compartment/solver")
    solver.path = "/model/compartment/##"
    solver.method = "rk5"
    mesh = moose.element("/model/compartment/mesh")
    moose.connect(mesh, "remesh", solver, "remesh")
    moose.setClock(5, 1.0)  # clock for the solver
    moose.useClock(5, "/model/compartment/solver", "process")

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

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

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

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

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

    quit()
コード例 #9
0
    def simulate(self,simtime=simtime,dt=dt,plotif=False,**kwargs):
        
        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime/dt)
        self.trange = np.arange(0,self.simtime+dt,dt)   
        
        self._init_network(**kwargs)
        if plotif:
            self._init_plots()
        
        # moose simulation
        # moose auto-schedules
        #moose.useClock( 0, '/network/syns', 'process' )
        #moose.useClock( 1, '/network', 'process' )
        #moose.useClock( 2, '/plotSpikes', 'process' )
        #moose.useClock( 3, '/plotVms', 'process' )
        #moose.useClock( 3, '/plotWeights', 'process' )
        for i in range(10):
            moose.setClock( i, dt )

        t1 = time.time()
        print('reinit MOOSE')
        moose.reinit()
        print(('reinit time t = ', time.time() - t1))
        t1 = time.time()
        print('starting')
        moose.start(self.simtime)
        print(('runtime, t = ', time.time() - t1))

        if plotif:
            self._plot()
コード例 #10
0
 def setupSolver(self, path = '/hsolve'):
     """Setting up HSolver """
     hsolve = moose.HSolve( path )
     hsolve.dt = self.simDt
     moose.setClock(1, self.simDt)
     moose.useClock(1, hsolve.path, 'process')
     hsolve.target = self.cablePath
コード例 #11
0
ファイル: Fig4B.py プロジェクト: dilawar/moose-examples
def main():
    numpy.random.seed( 1234 )
    rdes = buildRdesigneur()
    rdes.buildModel( '/model' )
    assert( moose.exists( '/model' ) )
    moose.element( '/model/elec/hsolve' ).tick = -1
    for i in range( 10, 18 ):
        moose.setClock( i, dt )
    moose.setClock( 18, plotdt )
    moose.reinit()

    if do3D:
        app = QtGui.QApplication(sys.argv)
        compts = moose.wildcardFind( "/model/elec/#[ISA=CompartmentBase]" )
        print(("LEN = ", len( compts )))
        for i in compts:
            n = i.name[:4]
            if ( n == 'head' or n == 'shaf' ):
                i.diameter *= 1.0
                i.Vm = 0.02
            else:
                i.diameter *= 4.0
                i.Vm = -0.05
        vm_viewer = createVmViewer(rdes)
        vm_viewer.showMaximized()
        vm_viewer.start()
        app.exec_()
コード例 #12
0
    def simulate(self, simtime=simtime, dt=dt, plotif=False, **kwargs):

        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime / dt)
        self.trange = np.arange(0, self.simtime + dt, dt)

        self._init_network(**kwargs)
        if plotif:
            self._init_plots()

        # moose simulation
        moose.useClock(0, "/network/syns", "process")
        moose.useClock(1, "/network", "process")
        moose.useClock(2, "/plotSpikes", "process")
        moose.useClock(3, "/plotVms", "process")
        moose.useClock(3, "/plotWeights", "process")
        moose.setClock(0, dt)
        moose.setClock(1, dt)
        moose.setClock(2, dt)
        moose.setClock(3, dt)
        moose.setClock(9, dt)
        t1 = time.time()
        print "reinit MOOSE"
        moose.reinit()
        print "reinit time t = ", time.time() - t1
        t1 = time.time()
        print "starting"
        moose.start(self.simtime)
        print "runtime, t = ", time.time() - t1

        if plotif:
            self._plot()
コード例 #13
0
    def simulate(self,simtime=simtime,dt=dt,plotif=False,**kwargs):
        
        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime/dt)
        self.trange = np.arange(0,self.simtime+dt,dt)   
        
        self._init_network(**kwargs)
        if plotif:
            self._init_plots()
        
        # moose simulation
        moose.useClock( 0, '/network/syns', 'process' )
        moose.useClock( 1, '/network', 'process' )
        moose.useClock( 2, '/plotSpikes', 'process' )
        moose.useClock( 3, '/plotVms', 'process' )
        moose.useClock( 3, '/plotWeights', 'process' )
        moose.setClock( 0, dt )
        moose.setClock( 1, dt )
        moose.setClock( 2, dt )
        moose.setClock( 3, dt )
        moose.setClock( 9, dt )
        t1 = time.time()
        print 'reinit MOOSE -- takes a while ~20s.'
        moose.reinit()
        print 'reinit time t = ', time.time() - t1
        t1 = time.time()
        print 'starting'
        moose.start(self.simtime)
        print 'runtime, t = ', time.time() - t1

        if plotif:
            self._plot()
コード例 #14
0
def main():
    """
    This example illustrates how to define a kinetic model embedded in
    a NeuroMesh, and undergoing cross-compartment reactions. It is 
    completely self-contained and does not use any external model definition
    files.  Normally one uses standard model formats like
    SBML or kkit to concisely define kinetic and neuronal models.
    This example creates a simple reaction::
        a <==> b <==> c 
    in which 
    **a, b**, and **c** are in the dendrite, spine head, and PSD 
    respectively.
    The model is set up to run using the Ksolve for integration. Although
    a diffusion solver is set up, the diff consts here are set to zero.
    The display has two parts: 
    Above is a line plot of concentration against compartment#. 
    Below is a time-series plot that appears after # the simulation has 
    ended. The plot is for the last (rightmost) compartment.
    Concs of **a**, **b**, **c** are plotted for both graphs.
    """
    simdt = 0.01
    plotdt = 0.01

    makeModel()

    # Schedule the whole lot
    for i in range( 10, 19):
        moose.setClock( i, simdt ) # for the compute objects
    moose.reinit()
    display()
    quit()
コード例 #15
0
ファイル: run_hhcell.py プロジェクト: hrani/moose-core
def run(nogui):
    
    reader = NML2Reader(verbose=True)

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

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

        for i in range(len(t)):
            vfile.write('%s\t%s\n'%(t[i],vm.vector[i]))
        vfile.close()
        plt.subplot(211)
        plt.plot(t, vm.vector * 1e3, label='Vm (mV)')
        plt.legend()
        plt.title('Vm')
        plt.subplot(212)
        plt.title('Input')
        plt.plot(t, inj.vector * 1e9, label='injected (nA)')
        #plt.plot(t, gK.vector * 1e6, label='K')
        #plt.plot(t, gNa.vector * 1e6, label='Na')
        plt.legend()
        plt.figure()
        test_channel_gates()
        plt.show()
        plt.close()
コード例 #16
0
ファイル: compartment_net.py プロジェクト: asiaszmek/moose
def main():
    """
    This example illustrates how to create a network of single compartmental neurons
    connected via alpha synapses. It also shows the use of SynChan class to create a
    network of single-compartment neurons connected by synapse.
    """
    simtime = 0.1
    simdt = 0.25e-5
    plotdt = 0.25e-3
    netinfo = create_network(size=2)
    vm_a = netinfo['Vm_A']
    vm_b = netinfo['Vm_B']
    gksyn_b = netinfo['Gsyn_B']
    for ii in range(10):
        moose.setClock(ii, simdt)
    moose.setClock(18, plotdt)
    moose.reinit()
    moose.start(simtime)
    plt.subplot(221)
    for oid in vm_a.vec:
        print((oid, oid.vector.shape))
        plt.plot(oid.vector, label=oid.path)
    plt.legend()
    plt.subplot(223)
    for oid in vm_b.vec:
        plt.plot(oid.vector, label=oid.path)
    plt.legend()
    plt.subplot(224)
    for oid in gksyn_b.vec:
        plt.plot(oid.vector, label=oid.path)
    plt.legend()
    plt.show()
コード例 #17
0
ファイル: interpol.py プロジェクト: dilawar/moose-examples
def main():
    """
    Example of Interpol object.
    """
    simtime = 1.0
    simdt = 0.001
    model = moose.Neutral('/model')
    data = moose.Neutral('/data')
    interpol = moose.Interpol('/model/sin')
    vec = np.sin(np.linspace(-3.14, 3.14, 100))
    interpol.vector = vec
    interpol.xmax = 3.14
    interpol.xmin = -3.14
    recorded = moose.Table('/data/output')
    moose.connect(recorded, 'requestOut', interpol, 'getY')

    stimtab = moose.StimulusTable('/model/x')
    stimtab.stepSize = 0.0
    # stimtab.startTime = 0.0
    # stimtab.stopTime = simtime
    stimtab.vector = np.linspace(-4, 4, 1000)
    print((stimtab.vector))
    print((interpol.vector))
    moose.connect(stimtab, 'output', interpol, 'input')


    moose.setClock(0, simdt)
    moose.useClock(0, '/data/##,/model/##', 'process')
    moose.reinit()
    moose.start(simtime)
    plt.plot(np.linspace(0, simtime, len(recorded.vector)), recorded.vector, 'b-+', label='interpolated')
    plt.plot(np.linspace(0, simtime, len(vec)), vec, 'r-+', label='original')
    plt.show()
コード例 #18
0
def main():
    makeModel()
    gsolve = moose.Gsolve("/model/compartment/gsolve")
    stoich = moose.Stoich("/model/compartment/stoich")
    stoich.compartment = moose.element("/model/compartment")
    stoich.ksolve = gsolve
    stoich.path = "/model/compartment/##"
    # solver.method = "rk5"
    # mesh = moose.element( "/model/compartment/mesh" )
    # moose.connect( mesh, "remesh", solver, "remesh" )
    moose.setClock(5, 1.0)  # clock for the solver
    moose.useClock(5, "/model/compartment/gsolve", "process")

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

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

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

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

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

    quit()
コード例 #19
0
ファイル: nsdf.py プロジェクト: NeuroArchive/moose
def setup_model():
    """Setup a dummy model with a pulsegen and a spikegen detecting the
    leading edges of the pulses. We record the pulse output as Uniform
    data and leading edge time as Event data."""
    simtime = 100.0
    dt = 1e-3
    model = moose.Neutral('/model')
    pulse = moose.PulseGen('/model/pulse')
    pulse.level[0] = 1.0
    pulse.delay[0] = 10
    pulse.width[0] = 20
    t_lead = moose.SpikeGen('/model/t_lead')
    t_lead.threshold = 0.5
    moose.connect(pulse, 'output', t_lead,'Vm');
    nsdf = moose.NSDFWriter('/model/writer')
    nsdf.filename = 'nsdf_demo.h5'
    nsdf.mode = 2 #overwrite existing file
    nsdf.flushLimit = 100
    moose.connect(nsdf, 'requestOut', pulse, 'getOutputValue')
    print 'event input', nsdf.eventInput, nsdf.eventInput.num
    print nsdf

    nsdf.eventInput.num = 1
    ei = nsdf.eventInput[0]
    print ei.path
    moose.connect(t_lead, 'spikeOut', nsdf.eventInput[0], 'input')
    tab = moose.Table('spiketab')
    tab.threshold = t_lead.threshold
    clock = moose.element('/clock')
    for ii in range(32):
        moose.setClock(ii, dt)
    moose.connect(pulse, 'output', tab, 'spike')
    print datetime.now().isoformat()
    moose.reinit()
    moose.start(simtime)
    print datetime.now().isoformat()
    np.savetxt('nsdf.txt', tab.vector)
    ###################################
    # Set the environment attributes
    ###################################
    nsdf.stringAttr['title'] = 'NSDF writing demo for moose'
    nsdf.stringAttr['description'] = '''An example of writing data to NSDF file from MOOSE simulation. In
this simulation we generate square pules from a PulseGen object and
use a SpikeGen to detect the threshold crossing events of rising
edges. We store the pulsegen output as Uniform data and the threshold
crossing times as Event data. '''    
    nsdf.stringAttr['creator'] = getpass.getuser()
    nsdf.stringVecAttr['software'] = ['python2.7', 'moose3' ]
    nsdf.stringVecAttr['method'] = ['']
    nsdf.stringAttr['rights'] = ''
    nsdf.stringAttr['license'] = 'CC-BY-NC'
    # Specify units. MOOSE is unit agnostic, so we explicitly set the
    # unit attibutes on individual datasets
    nsdf.stringAttr['/data/uniform/PulseGen/outputValue/tunit'] = 's'
    nsdf.stringAttr['/data/uniform/PulseGen/outputValue/unit'] = 'A'
    eventDataPath = '/data/event/SpikeGen/spikeOut/{}_{}_{}/unit'.format(t_lead.vec.value,
                                                                         t_lead.getDataIndex(), 
                                                                         t_lead.getFieldIndex())
    nsdf.stringAttr[eventDataPath] = 's'
コード例 #20
0
ファイル: run_cell.py プロジェクト: pgleeson/moose-core
def run(nogui):
    
    reader = NML2Reader(verbose=True)

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

        plt.subplot(211)
        plt.plot(t, vm.vector * 1e3, label='Vm (mV)')
        plt.legend()
        plt.title('Vm')
        plt.subplot(212)
        plt.title('Input')
        plt.plot(t, inj.vector * 1e9, label='injected (nA)')
        #plt.plot(t, gK.vector * 1e6, label='K')
        #plt.plot(t, gNa.vector * 1e6, label='Na')
        plt.legend()
        plt.show()
        plt.close()
コード例 #21
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
コード例 #22
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
コード例 #23
0
def create_func(funcname, expr):
    f = moose.Function(funcname)
    f.expr = expr
    t = moose.Table(funcname + 'tab')
    t.connect('requestOut', f, 'getValue')
    moose.setClock(f.tick, 0.1)
    moose.setClock(t.tick, 0.1)
    return f, t
コード例 #24
0
def timetable_demo():
    tt_array, sp_array = timetable_nparray()
    tt_file, sp_file = timetable_file()
    # Create a synchan inside a compartment to demonstrate how to use
    # TimeTable to send artificial spike events to a synapse.
    comp = moose.Compartment('/model/comp')
    comp.Em = -60e-3
    comp.Rm = 1e9
    comp.Cm = 1e-12
    synchan = moose.SynChan('/model/comp/synchan')
    synchan.Gbar = 1e-6
    synchan.Ek = 0.0
    moose.connect(synchan, 'channel', comp, 'channel')
    synh = moose.SimpleSynHandler('/model/comp/synchan/synh')
    moose.connect(synh, 'activationOut', synchan, 'activation')
    synh.synapse.num = 1
    moose.connect(tt_file, 'eventOut', moose.element(synh.path + '/synapse'),
                  'addSpike')
    # Data recording: record the `state` of the time table filled
    # using array.
    data = moose.Neutral('/data')
    tab_array = moose.Table('/data/tab_array')
    moose.connect(tab_array, 'requestOut', tt_array, 'getState')
    # Record the synaptic conductance for the other time table, which
    # is filled from a text file and sends spike events to a synchan.
    tab_file = moose.Table('/data/tab_file')
    moose.connect(tab_file, 'requestOut', synchan, 'getGk')

    # Scheduling
    moose.setClock(0, simdt)
    moose.setClock(1, simdt)
    moose.useClock(1, '/model/##[ISA=Compartment]', 'init')
    moose.useClock(1, '/model/##,/data/##', 'process')
    moose.reinit()
    moose.start(simtime)

    # Plotting
    pylab.subplot(2, 1, 1)
    pylab.plot(sp_array,
               np.ones(len(sp_array)),
               'rx',
               label='spike times from numpy array')
    pylab.plot(np.linspace(0, simtime, len(tab_array.vector)),
               tab_array.vector,
               'b-',
               label='TimeTable state')
    pylab.legend()
    pylab.subplot(2, 1, 2)
    pylab.plot(sp_file,
               np.ones(len(sp_file)),
               'rx',
               label='spike times from file')
    pylab.plot(np.linspace(0, simtime, len(tab_file.vector)),
               tab_file.vector * 1e6,
               'b-',
               label='Syn Gk (uS)')
    pylab.legend()
    pylab.show()
コード例 #25
0
def main(model_name, comp_passive, channel_settings, ca_params):
    # Simulation information.
    simtime = 1
    simdt = 0.25e-5
    plotdt = 0.25e-3

    diameter = 20e-6
    length = 20e-6

    # Model creation
    soma, moose_paths = simple_model(model_name, comp_passive,
                                     channel_settings, ca_params, length,
                                     diameter)

    # Output table
    tabs = creat_moose_tables()

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

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

    from collections import namedtuple
    cond = namedtuple('cond', 'k Ltype Ntype cl')
    # Final execution test
    test_conductances = [
        cond(k=0.3775621, Ltype=0.18, Ntype=0.4, cl=40),
    ]

    for K, V1, V2, cc in test_conductances:
        moose.element(
            '/soma/K'
        ).Gbar = K  #* compute_comp_area(length, diameter)[0] * 1E4
        moose.element(
            '/soma/Ca_V1'
        ).Gbar = V1  #* compute_comp_area(length, diameter)[0] * 1E4
        moose.element(
            '/soma/Ca_V2'
        ).Gbar = V2  #* compute_comp_area(length, diameter)[0] * 1E4
        moose.element(
            '/soma/ca_cc'
        ).Gbar = cc  #* compute_comp_area(length, diameter)[0] * 1E4
        moose.reinit()
        moose.start(simtime)
        #plot_internal_currents(*tabs['internal_currents'])
        plot_vm_table(
            simtime,
            tabs['vm'][0],
            title=
            'Conductances: ca_V1(L): {0}, Ca_V2 (N) :{1}, ca_cc :{2} K : {3}'.
            format(V1, V2, cc, K),
            xlab="Time in Seconds",
            ylab="Volage (V)")
        plt.show()
コード例 #26
0
ファイル: test_function.py プロジェクト: dilawar/moose
def test_var_order():
    """The y values are one step behind the x values because of
    scheduling sequences"""
    nsteps = 5
    simtime = nsteps
    dt = 1.0
    # fn0 = moose.Function('/fn0')
    fn1 = moose.Function('/fn1')
    fn1.x.num = 2
    fn1.expr = 'y1+y0+x1+x0'
    fn1.mode = 1
    inputs = np.arange(0, nsteps + 1, 1.0)
    x0 = moose.StimulusTable('/x0')
    x0.vector = inputs
    x0.startTime = 0.0
    x0.stopTime = simtime
    x0.stepPosition = 0.0
    print('x0', x0.vector)
    inputs /= 10
    x1 = moose.StimulusTable('/x1')
    x1.vector = inputs
    x1.startTime = 0.0
    x1.stopTime = simtime
    x1.stepPosition = 0.0
    print('x1', x1.vector)
    inputs /= 10
    y0 = moose.StimulusTable('/y0')
    y0.vector = inputs
    y0.startTime = 0.0
    y0.stopTime = simtime
    y0.stepPosition = 0.0
    print('y0', y0.vector)
    inputs /= 10
    y1 = moose.StimulusTable('/y1')
    y1.vector = inputs
    print('y1', y1.vector)
    y1.startTime = 0.0
    y1.startTime = 0.0
    y1.stopTime = simtime
    y1.stepPosition = 0.0
    #  print( fn1, type(fn1) )
    #  print( moose.showmsg(fn1.x) )
    moose.connect(x0, 'output', fn1.x[0], 'input')
    moose.connect(x1, 'output', fn1.x[1], 'input')
    moose.connect(fn1, 'requestOut', y0, 'getOutputValue')
    moose.connect(fn1, 'requestOut', y1, 'getOutputValue')
    z1 = moose.Table('/z1')
    moose.connect(z1, 'requestOut', fn1, 'getValue')
    for ii in range(32):
        moose.setClock(ii, dt)
    moose.reinit()
    moose.start(simtime)
    expected = [0, 1.1, 2.211, 3.322, 4.433, 5.544]
    print('sum: ', x0.vector + x1.vector + y0.vector + y1.vector)
    print('got', z1.vector)
    assert np.allclose(z1.vector,
                       expected), "Excepted %s, got %s" % (expected, z1.vector)
    print('Passed order vars')
コード例 #27
0
def sim_run():
    simtime = 1000E-3
    simdt = 0.5E-3
    inj_duration = 50E-3
    inj_amplitude = 0.1E-12

    # Create cell
    chicken_cell = create_swc_comp()
    cortical_cell = create_p_comp()
    chicken_cell_soma = moose.element('/chkE19[0]/soma')
    cortical_cell_soma = moose.element('/corcell[0]/soma')

    #Create injection source
    chicken_inject = create_pulse_generator(chicken_cell_soma, inj_duration,
                                            inj_amplitude)
    cortical_inject = create_pulse_generator(cortical_cell_soma, inj_duration,
                                             inj_amplitude)

    # Create output tables
    chicken_soma_table = create_output_table(table_element='/output',
                                             table_name='chksoma')
    chicken_dend_table = create_output_table(table_element='/output',
                                             table_name='chkdend')
    cortical_soma_table = create_output_table(table_element='/output',
                                              table_name='corsoma')
    cortical_dend_table = create_output_table(table_element='/output',
                                              table_name='cordend')

    # Connect output tables to target compartments.
    moose.connect(chicken_soma_table, 'requestOut', chicken_cell_soma, 'getVm')
    moose.connect(cortical_soma_table, 'requestOut', cortical_cell_soma,
                  'getVm')
    moose.connect(chicken_dend_table, 'requestOut',
                  moose.element('/chkE19[0]/dend_36_0'), 'getVm')
    moose.connect(cortical_dend_table, 'requestOut',
                  moose.element('/corcell[0]/apical3'), 'getVm')

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

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

    plot_chk = plot_vm_table(simtime,
                             chicken_soma_table,
                             chicken_dend_table,
                             title="Chicken Cell")
    plot_chk.legend(['soma', 'dend'])
    plot_cor = plot_vm_table(simtime,
                             cortical_soma_table,
                             cortical_dend_table,
                             title="cortical Cell")
    plot_cor.legend(['soma', 'dend'])
    plt.grid(True)
    plt.show()
コード例 #28
0
ファイル: run_cell.py プロジェクト: pgleeson/moose-core
def run(nogui):

    reader = NML2Reader(verbose=True)

    filename = 'test_files/passiveCell.nml'
    print('Loading: %s' % filename)
    reader.read(filename)

    msoma = reader.getComp(reader.doc.networks[0].populations[0].id, 0, 0)
    print(msoma)

    data = moose.Neutral('/data')

    pg = reader.getInput('pulseGen1')

    inj = moose.Table('%s/pulse' % (data.path))
    moose.connect(inj, 'requestOut', pg, 'getOutputValue')

    vm = moose.Table('%s/Vm' % (data.path))
    moose.connect(vm, 'requestOut', msoma, 'getVm')

    simdt = 1e-6
    plotdt = 1e-4
    simtime = 150e-3

    if (1):
        #moose.showmsg( '/clock' )
        for i in range(8):
            moose.setClock(i, simdt)
        moose.setClock(8, plotdt)
        moose.reinit()
    else:
        utils.resetSim([model.path, data.path], simdt, plotdt, simmethod='ee')
        moose.showmsg('/clock')

    moose.start(simtime)

    print("Finished simulation!")

    t = np.linspace(0, simtime, len(vm.vector))

    if not nogui:
        import matplotlib.pyplot as plt

        plt.subplot(211)
        plt.plot(t, vm.vector * 1e3, label='Vm (mV)')
        plt.legend()
        plt.title('Vm')
        plt.subplot(212)
        plt.title('Input')
        plt.plot(t, inj.vector * 1e9, label='injected (nA)')
        #plt.plot(t, gK.vector * 1e6, label='K')
        #plt.plot(t, gNa.vector * 1e6, label='Na')
        plt.legend()
        plt.show()
        plt.close()
コード例 #29
0
def ts(chem, ht, ampl, plotPos, title=''):
    tsettle = 500  # This turns out to be needed for both models.
    tpre = 10
    tstim = 1
    tpost = 50
    modelId = moose.loadModel(chem, 'model', 'gsl')[0]
    Ca = moose.element('/model/kinetics/Ca')
    output = moose.element('/model/kinetics/synAMPAR')
    iplot = moose.element('/model/graphs/conc1/Ca.Co')
    oplot = moose.element('/model/graphs/conc2/synAMPAR.Co')
    moose.setClock(iplot.tick, plotDt)
    for i in range(10, 20):
        moose.setClock(i, plotDt)

    Ca.concInit = 0.08e-3
    moose.reinit()
    moose.start(tsettle)
    moose.start(tpre)
    Ca.concInit = ampl
    moose.start(tstim)
    Ca.concInit = 0.08e-3
    moose.start(tpost)
    ivec = iplot.vector
    ovec = oplot.vector
    ivec = ivec[int(tsettle / plotDt):]
    ovec = ovec[int(tsettle / plotDt):]
    x = np.array(range(len(ivec))) * plotDt
    ax = plotBoilerplate(char[plotPos],
                         plotPos,
                         title,
                         xlabel="Time (s)",
                         ylabel="[synAMPAR] ($\mu$M)")
    #ax.plot( x , 1000 * ivec, label = "input" )
    ax.plot(x, 1000 * ovec, label="output")
    moose.delete('/model')

    jsonDict = hillTau.loadHillTau(ht)
    hillTau.scaleDict(jsonDict, hillTau.getQuantityScale(jsonDict))
    model = hillTau.parseModel(jsonDict)
    model.dt = plotDt
    inputMolIndex = model.molInfo.get("Ca").index
    outputMolIndex = model.molInfo.get("synAMPAR").index

    model.advance(tpre + tsettle)
    model.conc[inputMolIndex] = ampl
    model.advance(tstim)
    model.conc[inputMolIndex] = 0.08e-3
    model.advance(tpost)
    plotvec = np.transpose(np.array(model.plotvec))
    x = np.array(range(plotvec.shape[1] - int(tsettle / plotDt))) * plotDt
    reacn = "this is ht"
    #ax = plotBoilerplate( "B", plotPos+1, reacn, xlabel = "Time (s)" )
    #ax.plot( x , 1000 * plotvec[inputMolIndex], label = "input" )
    ax.plot(x,
            1000 * plotvec[outputMolIndex][int(tsettle / plotDt):],
            label="output")
コード例 #30
0
ファイル: test_Xreacs6.py プロジェクト: dilawar/moose
def test_xreac6():
    for i in range( 10, 18):
        moose.setClock( i, 0.01 )
    runtime = 100
    makeModel()
    moose.reinit()
    moose.start( runtime )
    assert( almostEq( moose.element( 'model/compartment/s' ).conc,
        moose.element( '/model/endo/s' ).conc ) )
    moose.delete( '/model' )
コード例 #31
0
def runMOOSE():
    for i in range(10):
        moose.setClock(i, dt_)
    hsolve = moose.HSolve('/hsolve')
    hsolve.dt = dt_
    hsolve.target = '/model/##'
    moose.reinit()
    moose.start(0.1)
    records = {}
    mu.saveRecords(records_, outfile="moose_results.csv")
コード例 #32
0
ファイル: propagationBis.py プロジェクト: csiki/MOOSE
def makeModel():
		# create container for model
		r0 = 1e-6	# m
		r1 = 0.5e-6	# m. Note taper.
		num = 200
		diffLength = 1e-6 # m
		comptLength = num * diffLength	# m
		diffConst = 20e-12 # m^2/sec
		concA = 1 # millimolar
		dt4 = 0.02  # for the diffusion
		dt5 = 0.2   # for the reaction
                mfile = '../../Genesis_files/M1719.g'

		model = moose.Neutral( 'model' )
		compartment = moose.CylMesh( '/model/kinetics' )

		# load in model
                modelId = moose.loadModel( mfile, '/model', 'ee' )
		a = moose.element( '/model/kinetics/a' )
		b = moose.element( '/model/kinetics/b' )
		c = moose.element( '/model/kinetics/c' )

                ac = a.concInit
                bc = b.concInit
                cc = c.concInit

		compartment.r0 = r0
		compartment.r1 = r1
		compartment.x0 = 0
		compartment.x1 = comptLength
		compartment.diffLength = diffLength
		assert( compartment.numDiffCompts == num )

		# Assign parameters
                for x in moose.wildcardFind( '/model/kinetics/##[ISA=PoolBase]' ):
                    #print 'pools: ', x, x.name
                    x.diffConst = diffConst

		# Make solvers
		ksolve = moose.Ksolve( '/model/kinetics/ksolve' )
		dsolve = moose.Dsolve( '/model/dsolve' )
                # Set up clocks. The dsolver to know before assigning stoich
		moose.setClock( 4, dt4 )
		moose.setClock( 5, dt5 )
		moose.useClock( 4, '/model/dsolve', 'process' )
                # Ksolve must be scheduled after dsolve.
		moose.useClock( 5, '/model/kinetics/ksolve', 'process' )

		stoich = moose.Stoich( '/model/kinetics/stoich' )
		stoich.compartment = compartment
		stoich.ksolve = ksolve
		stoich.dsolve = dsolve
		stoich.path = "/model/kinetics/##"
                print 'dsolve.numPools, num = ', dsolve.numPools, num
                b.vec[num-1].concInit *= 1.01 # Break symmetry.
コード例 #33
0
ファイル: test_Xenz1.py プロジェクト: hrani/moose-core
def main( standalone = False ):
    for i in range( 10, 18 ):
        moose.setClock( i, 0.001 )
    runtime = 100
    displayInterval = 2
    makeModel()
    moose.reinit()
    moose.start( runtime )
    assert( almostEq( moose.element( 'model/compartment/prd' ).n,
        moose.element( '/model/endo/sub' ).n ) )
    moose.delete( '/model' )
コード例 #34
0
ファイル: test_Xenz1.py プロジェクト: hrani/moose-core1
def main( standalone = False ):
    for i in range( 10, 18 ):
        moose.setClock( i, 0.001 )
    runtime = 100
    displayInterval = 2
    makeModel()
    moose.reinit()
    moose.start( runtime )
    assert( almostEq( moose.element( 'model/compartment/prd' ).n,
        moose.element( '/model/endo/sub' ).n ) )
    moose.delete( '/model' )
コード例 #35
0
    def simulate(self, simtime=simtime, dt=dt, plotif=False, **kwargs):

        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime / dt)
        self.trange = np.arange(0, self.simtime, dt)

        print("Noise injections being set ...")
        for i in range(self.N):
            if noiseInj:
                ## Gaussian white noise SD added every dt interval should be
                ## divided by sqrt(dt), as the later numerical integration
                ## will multiply it by dt.
                ## See the Euler-Maruyama method, numerical integration in
                ## http://www.scholarpedia.org/article/Stochastic_dynamical_systems
                self.noiseTables.vec[i].vector = self.Iinject + \
                    np.random.normal( \
                        scale=self.noiseInjSD*np.sqrt(self.Rm*self.Cm/self.dt), \
                        size=self.T ) # scale = SD
                self.noiseTables.vec[i].stepSize = 0  # use current time
                # as x value for interpolation
                self.noiseTables.vec[i].stopTime = self.simtime

        print("init membrane potentials being set ... ")
        self._init_network(**kwargs)
        print("initializing plots ... ")
        if plotif:
            self._init_plots()

        ## MOOSE simulation

        ## MOOSE assigns clocks by default, no need to set manually
        #print "setting clocks ... "
        #moose.useClock( 1, '/network', 'process' )
        #moose.useClock( 2, '/plotSpikes', 'process' )
        #moose.useClock( 3, '/plotVms', 'process' )
        #if CaPlasticity:
        #    moose.useClock( 3, '/plotWeights', 'process' )
        #    moose.useClock( 3, '/plotCa', 'process' )
        ## Do need to set the dt for MOOSE clocks
        for i in range(10):
            moose.setClock(i, dt)

        t1 = time.time()
        print('reinit MOOSE -- takes a while ~20s.')
        moose.reinit()
        print('reinit time t = ', time.time() - t1)
        t1 = time.time()
        print('starting run ...')
        moose.start(self.simtime)
        print('runtime, t = ', time.time() - t1)

        if plotif:
            self._plot()
コード例 #36
0
def test_hsolve_calcium():
    for tick in range(0, 7):
        moose.setClock(tick, 10e-6)
    moose.setClock(8, 0.005)

    lib = moose.Neutral('/library')
    model = moose.loadModel(p_file, 'neuron')
    assert model, model
    pulse = moose.PulseGen('/neuron/pulse')
    inject = 100e-10
    chan_proto.chan_proto('/library/SK', param_chan.SK)
    chan_proto.chan_proto('/library/CaL12', param_chan.Cal)
    pulse.delay[0] = 8.
    pulse.width[0] = 500e-12
    pulse.level[0] = inject
    pulse.delay[1] = 1e9

    for comp in moose.wildcardFind('/neuron/#[TYPE=Compartment]'):
        new_comp = moose.element(comp)
        new_comp.initVm = -.08
        difs, difb = td.add_difshells_and_buffers(new_comp, difshell_no,
                                                  difbuf_no)
        for name in cond:
            chan = td.addOneChan(name, cond[name], new_comp)
            if 'Ca' in name:
                moose.connect(chan, "IkOut", difs[0], "influx")

            if 'SK' in name:
                moose.connect(difs[0], 'concentrationOut', chan, 'concen')

    data = moose.Neutral('/data')
    vmtab = moose.Table('/data/Vm')
    shelltab = moose.Table('/data/Ca')
    caltab = moose.Table('/data/CaL_Gk')
    sktab = moose.Table('/data/SK_Gk')
    moose.connect(vmtab, 'requestOut', moose.element('/neuron/soma'), 'getVm')
    moose.connect(shelltab, 'requestOut', difs[0], 'getC')
    moose.connect(caltab, 'requestOut', moose.element('/neuron/soma/CaL12'),
                  'getGk')
    moose.connect(sktab, 'requestOut', moose.element('/neuron/soma/SK'),
                  'getGk')

    hsolve = moose.HSolve('/neuron/hsolve')
    hsolve.dt = 10e-6
    hsolve.target = ('/neuron/soma')
    t_stop = 10.
    moose.reinit()
    moose.start(t_stop)
    vec1 = sktab.vector
    vec2 = shelltab.vector
    assert_stat(vec1, [0.0, 5.102834e-22, 4.79066e-22, 2.08408e-23])
    assert_stat(vec2, [5.0e-5, 5.075007e-5, 5.036985e-5, 2.1950117e-7])
    assert len(np.where(sktab.vector < 1e-19)[0]) == 2001
    assert len(np.where(shelltab.vector > 50e-6)[0]) == 2000
コード例 #37
0
    def simulate(self,simtime=simtime,dt=dt,plotif=False,**kwargs):
        
        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime/dt)
        self.trange = np.arange(0,self.simtime,dt)   

        print "Noise injections being set ..."
        for i in range(self.N):
            if noiseInj:
                ## Gaussian white noise SD added every dt interval should be
                ## divided by sqrt(dt), as the later numerical integration
                ## will multiply it by dt.
                ## See the Euler-Maruyama method, numerical integration in 
                ## http://www.scholarpedia.org/article/Stochastic_dynamical_systems
                self.noiseTables.vec[i].vector = self.Iinject + \
                    np.random.normal( \
                        scale=self.noiseInjSD*np.sqrt(self.Rm*self.Cm/self.dt), \
                        size=self.T ) # scale = SD
                self.noiseTables.vec[i].stepSize = 0    # use current time 
                                                        # as x value for interpolation
                self.noiseTables.vec[i].stopTime = self.simtime
        
        print "init membrane potentials being set ... "
        self._init_network(**kwargs)
        print "initializing plots ... "
        if plotif:
            self._init_plots()
        
        ## MOOSE simulation
        
        ## MOOSE assigns clocks by default, no need to set manually
        #print "setting clocks ... "
        #moose.useClock( 1, '/network', 'process' )
        #moose.useClock( 2, '/plotSpikes', 'process' )
        #moose.useClock( 3, '/plotVms', 'process' )
        #if CaPlasticity:
        #    moose.useClock( 3, '/plotWeights', 'process' )
        #    moose.useClock( 3, '/plotCa', 'process' )
        ## Do need to set the dt for MOOSE clocks
        for i in range(10):
            moose.setClock( i, dt )

        t1 = time.time()
        print 'reinit MOOSE -- takes a while ~20s.'
        moose.reinit()
        print 'reinit time t = ', time.time() - t1
        t1 = time.time()
        print 'starting run ...'
        moose.start(self.simtime)
        print 'runtime, t = ', time.time() - t1

        if plotif:
            self._plot()
コード例 #38
0
ファイル: Fig2A.py プロジェクト: BhallaLab/moose-examples
    def simulate(self,simtime=simtime,dt=dt,plotif=False,**kwargs):
        
        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime/dt)
        self.trange = np.arange(0,self.simtime,dt)   

        for i in range(self.N):
            if noiseInj:
                ## Gaussian white noise SD added every dt interval should be
                ## divided by sqrt(dt), as the later numerical integration
                ## will multiply it by dt.
                ## See the Euler-Maruyama method, numerical integration in 
                ## http://www.scholarpedia.org/article/Stochastic_dynamical_systems
                self.noiseTables.vec[i].vector = self.Iinject + \
                    np.random.normal( \
                        scale=self.noiseInjSD*np.sqrt(self.Rm*self.Cm/self.dt), \
                        size=int(self.T)
                        ) # scale = SD
                self.noiseTables.vec[i].stepSize = 0    # use current time 
                                                        # as x value for interpolation
                self.noiseTables.vec[i].stopTime = self.simtime
        
        self._init_network(**kwargs)
        if plotif:
            self._init_plots()
        
        # moose simulation
        #moose.useClock( 1, '/network', 'process' )
        #moose.setClock( 0, dt )
        #moose.setClock( 1, dt )
        #moose.setClock( 2, dt )
        #moose.setClock( 3, dt )
        #moose.setClock( 9, dt )
        ## Do need to set the dt for MOOSE clocks
        for i in range(10):
            moose.setClock( i, dt )
        moose.setClock( 18, plotDt )
        t1 = time.time()
        print('reinit MOOSE -- takes a while ~20s.')
        moose.reinit()
        print(('reinit time t = ', time.time() - t1))
        t1 = time.time()
        print('starting')
        simadvance = self.simtime / 50.0
        for i in range( 50 ):
            moose.start( simadvance )
            print(('at t = ', i * simadvance, 'realtime = ', time.time() - t1))
        #moose.start(self.simtime)
        print(('runtime for ', self.simtime, 'sec, is t = ', time.time() - t1))

        if plotif:
            self._plot()
コード例 #39
0
def make_model():
    sinePeriod = 50
    maxFiringRate = 10
    refractT = 0.05

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

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

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

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

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

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

    ############### Connect up circuit ###############
    moose.connect(stim, 'output', spike, 'setRate')
    moose.connect(spike, 'spikeOut', syn.synapse[0], 'addSpike')
    moose.connect(spike, 'spikeOut', stats1, 'addSpike')
    moose.connect(syn, 'activationOut', fire, 'activation')
    moose.connect(stats2, 'requestOut', fire, 'getVm')
    moose.connect(plots, 'requestOut', stim, 'getOutputValue')
    moose.connect(plot1, 'requestOut', stats1, 'getWmean')
    moose.connect(plot2, 'requestOut', stats2, 'getWmean')
    moose.connect(plotf, 'requestOut', fire, 'getVm')
コード例 #40
0
def testModel(useSolver):
    plotDt = 2e-4
    if (useSolver):
        elecDt = 50e-6
        chemDt = 2e-3

    makeModel()
    moose.setClock(18, plotDt)

    moose.reinit()
    moose.start(0.1)
    dumpPlots()
コード例 #41
0
ファイル: propagationBis.py プロジェクト: tdeuling/moose
def makeModel():
                # create container for model
                r0 = 1e-6        # m
                r1 = 0.5e-6        # m. Note taper.
                num = 200
                diffLength = 1e-6 # m
                comptLength = num * diffLength        # m
                diffConst = 20e-12 # m^2/sec
                concA = 1 # millimolar
                diffDt = 0.02  # for the diffusion
                chemDt = 0.2   # for the reaction
                mfile = '../../genesis/M1719.g'

                model = moose.Neutral( 'model' )
                compartment = moose.CylMesh( '/model/kinetics' )

                # load in model
                modelId = moose.loadModel( mfile, '/model', 'ee' )
                a = moose.element( '/model/kinetics/a' )
                b = moose.element( '/model/kinetics/b' )
                c = moose.element( '/model/kinetics/c' )

                ac = a.concInit
                bc = b.concInit
                cc = c.concInit

                compartment.r0 = r0
                compartment.r1 = r1
                compartment.x0 = 0
                compartment.x1 = comptLength
                compartment.diffLength = diffLength
                assert( compartment.numDiffCompts == num )

                # Assign parameters
                for x in moose.wildcardFind( '/model/kinetics/##[ISA=PoolBase]' ):
                    #print 'pools: ', x, x.name
                    x.diffConst = diffConst

                # Make solvers
                ksolve = moose.Ksolve( '/model/kinetics/ksolve' )
                dsolve = moose.Dsolve( '/model/dsolve' )
                # Set up clocks.
                moose.setClock( 10, diffDt )
                for i in range( 11, 17 ):
                    moose.setClock( i, chemDt )

                stoich = moose.Stoich( '/model/kinetics/stoich' )
                stoich.compartment = compartment
                stoich.ksolve = ksolve
                stoich.dsolve = dsolve
                stoich.path = "/model/kinetics/##"
                print(('dsolve.numPools, num = ', dsolve.numPools, num))
                b.vec[num-1].concInit *= 1.01 # Break symmetry.
コード例 #42
0
def main(standalone=False):
    for i in range(10, 18):
        moose.setClock(i, 0.001)
    runtime = 100
    makeModel()
    moose.reinit()
    moose.start(runtime)

    assert (almostEq(2.0 * moose.element('model/compartment/s').conc,
                     moose.element('/model/endo/s').conc))

    moose.delete('/model')
コード例 #43
0
def testModel( useSolver ):
	plotDt = 2e-4
	if ( useSolver ):
		elecDt = 50e-6
		chemDt = 2e-3

	makeModel()
	moose.setClock( 18, plotDt )

	moose.reinit()
	moose.start( 0.1 )
	dumpPlots()
コード例 #44
0
ファイル: test_mumbl.py プロジェクト: csiki/MOOSE
def main():
    utils.parser
    nml.loadNeuroML_L123('./two_cells_nml_1.8/two_cells.nml')
    #mumbl.loadMumbl("./two_cells_nml_1.8/mumbl.xml")
    table1 = utils.recordTarget('/tableA', '/cells/purkinjeGroup_0/Dend_37_41', 'vm')
    table2 = utils.recordTarget('/tableB', '/cells/granuleGroup_0/Soma_0', 'vm')
    moose.setClock(0, 5e-6)
    moose.useClock(0, '/##', 'process')
    moose.useClock(0, '/##', 'init')
    moose.reinit()
    utils.run(0.1)
    graphviz.writeGraphviz(__file__+".dot", ignore='/library')
コード例 #45
0
def makeSolvers():
    stoich = moose.Stoich('/model/compartment/stoich')
    stoich.compartment = moose.element('/model/compartment')
    if (solver == 'gssa'):
        gsolve = moose.Gsolve('/model/compartment/ksolve')
        stoich.ksolve = gsolve
    else:
        ksolve = moose.Ksolve('/model/compartment/ksolve')
        stoich.ksolve = ksolve
    stoich.path = "/model/compartment/##"
    moose.setClock(5, 1.0)  # clock for the solver
    moose.useClock(5, '/model/compartment/ksolve', 'process')
コード例 #46
0
    def simulate(self,simtime=simtime,dt=dt,plotif=False,**kwargs):
        
        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime/dt)
        self.trange = np.arange(0,self.simtime,dt)   

        for i in range(self.N):
            if noiseInj:
                ## Gaussian white noise SD added every dt interval should be
                ## divided by sqrt(dt), as the later numerical integration
                ## will multiply it by dt.
                ## See the Euler-Maruyama method, numerical integration in 
                ## http://www.scholarpedia.org/article/Stochastic_dynamical_systems
                self.noiseTables.vec[i].vector = self.Iinject + \
                    np.random.normal( \
                        scale=self.noiseInjSD*np.sqrt(self.Rm*self.Cm/self.dt), \
                        size=int(self.T)
                        ) # scale = SD
                self.noiseTables.vec[i].stepSize = 0    # use current time 
                                                        # as x value for interpolation
                self.noiseTables.vec[i].stopTime = self.simtime
        
        self._init_network(**kwargs)
        if plotif:
            self._init_plots()
        
        # moose simulation
        #moose.useClock( 1, '/network', 'process' )
        #moose.setClock( 0, dt )
        #moose.setClock( 1, dt )
        #moose.setClock( 2, dt )
        #moose.setClock( 3, dt )
        #moose.setClock( 9, dt )
        ## Do need to set the dt for MOOSE clocks
        for i in range(10):
            moose.setClock( i, dt )
        moose.setClock( 18, plotDt )
        t1 = time.time()
        print('reinit MOOSE -- takes a while ~20s.')
        moose.reinit()
        print(('reinit time t = ', time.time() - t1))
        t1 = time.time()
        print('starting')
        simadvance = self.simtime / 50.0
        for i in range( 50 ):
            moose.start( simadvance )
            print(('at t = ', i * simadvance, 'realtime = ', time.time() - t1))
        #moose.start(self.simtime)
        print(('runtime for ', self.simtime, 'sec, is t = ', time.time() - t1))

        if plotif:
            self._plot()
コード例 #47
0
ファイル: RandSpikeStats.py プロジェクト: asiaszmek/moose
def make_model():
    sinePeriod = 50
    maxFiringRate = 10
    refractT = 0.05

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

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

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

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

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

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

    ############### Connect up circuit ###############
    moose.connect( stim, 'output', spike, 'setRate' )
    moose.connect( spike, 'spikeOut', syn.synapse[0], 'addSpike' )
    moose.connect( spike, 'spikeOut', stats1, 'addSpike' )
    moose.connect( syn, 'activationOut', fire, 'activation' )
    moose.connect( stats2, 'requestOut', fire, 'getVm' )
    moose.connect( plots, 'requestOut', stim, 'getOutputValue' )
    moose.connect( plot1, 'requestOut', stats1, 'getWmean' )
    moose.connect( plot2, 'requestOut', stats2, 'getWmean' )
    moose.connect( plotf, 'requestOut', fire, 'getVm' )
コード例 #48
0
def makeModel():
                # create container for model
                r0 = 1e-6        # m
                r1 = 0.5e-6        # m. Note taper.
                num = 200
                diffLength = 1e-6 # m
                comptLength = num * diffLength        # m
                diffConst = 20e-12 # m^2/sec
                concA = 1 # millimolar
                diffDt = 0.02  # for the diffusion
                chemDt = 0.2   # for the reaction
                mfile = '../../genesis/M1719.g'

                model = moose.Neutral( 'model' )
                compartment = moose.CylMesh( '/model/kinetics' )

                # load in model
                modelId = moose.loadModel( mfile, '/model', 'ee' )
                a = moose.element( '/model/kinetics/a' )
                b = moose.element( '/model/kinetics/b' )
                c = moose.element( '/model/kinetics/c' )

                ac = a.concInit
                bc = b.concInit
                cc = c.concInit

                compartment.r0 = r0
                compartment.r1 = r1
                compartment.x0 = 0
                compartment.x1 = comptLength
                compartment.diffLength = diffLength
                assert( compartment.numDiffCompts == num )

                # Assign parameters
                for x in moose.wildcardFind( '/model/kinetics/##[ISA=PoolBase]' ):
                    #print 'pools: ', x, x.name
                    x.diffConst = diffConst

                # Make solvers
                ksolve = moose.Ksolve( '/model/kinetics/ksolve' )
                dsolve = moose.Dsolve( '/model/dsolve' )
                # Set up clocks.
                moose.setClock( 10, diffDt )
                for i in range( 11, 17 ):
                    moose.setClock( i, chemDt )

                stoich = moose.Stoich( '/model/kinetics/stoich' )
                stoich.compartment = compartment
                stoich.ksolve = ksolve
                stoich.dsolve = dsolve
                stoich.path = "/model/kinetics/##"
                b.vec[num-1].concInit *= 1.01 # Break symmetry.
コード例 #49
0
ファイル: stimtable.py プロジェクト: upibhalla/moose-examples
def stimulus_table_demo():
    """
    Example of StimulusTable using Poisson random numbers.
    Creates a StimulusTable and assigns it signal representing events in a
    Poisson process. The output of the StimTable is sent to a DiffAmp
    object for buffering and then recorded in a regular table.
    """

    model = moose.Neutral('/model')
    data = moose.Neutral('/data')
    # This is the stimulus generator
    stimtable = moose.StimulusTable('/model/stim')
    recorded = moose.Table('/data/stim')
    moose.connect(recorded, 'requestOut', stimtable, 'getOutputValue')
    simtime = 100
    simdt = 1e-3
    # Inter-stimulus-intervals with rate=20/s
    rate = 20
    np.random.seed(1)  # ensure repeatability
    isi = np.random.exponential(rate, int(simtime / rate))
    # The stimulus times are the cumulative sum of the inter-stimulus intervals.
    stimtimes = np.cumsum(isi)
    # Select only stimulus times that are within simulation time -
    # this may leave out some possible stimuli at the end, but the
    # exoected number of Poisson events within simtime is
    # simtime/rate.
    stimtimes = stimtimes[stimtimes < simtime]
    ts = np.arange(0, simtime, simdt)
    # Find the indices of table entries corresponding to time of stimulus
    stimidx = np.searchsorted(ts, stimtimes)
    stim = np.zeros(len(ts))
    # Since linear interpolation is forced, we need at least three
    # consecutive entries to have same value to get correct
    # magnitude. And still we shall be off by at least one time step.
    indices = np.concatenate((stimidx - 1, stimidx, stimidx + 1))
    stim[indices] = 1.0
    stimtable.vector = stim
    stimtable.stepSize = 0  # This forces use of current time as x value for interpolation
    stimtable.stopTime = simtime
    moose.setClock(0, simdt)
    moose.useClock(0, '/model/##,/data/##', 'process')
    moose.reinit()
    moose.start(simtime)
    plt.plot(np.linspace(0, simtime, len(recorded.vector)),
             recorded.vector,
             'r-+',
             label='generated stimulus')
    plt.plot(ts, stim, 'b-x', label='originally assigned values')
    plt.ylim((-1, 2))
    plt.legend()
    plt.title('Exmaple of StimulusTable')
    plt.show()
コード例 #50
0
def main():
                """
This example illustrates how to set up a transport model with
four non-reacting molecules in a cylinder.
Molecule a and b have a positive motorConst so they are
are transported from soma (voxel 0) to the end of the cylinder.
Molecules c and d have a negative motorConst so they are transported
from the end of the cylinder to the soma.
Rate of all motors is 1e-6 microns/sec.
Pools a and c start out with all molecules at the soma, b and d
start with all molecules at the end of the cylinder.
Net effect is that only molecules a and d actually move. B and c
stay put as their motors are pushing further toward their respective
ends, and I assume all cells have sealed ends.
                """
                dt4 = 0.01
                dt5 = 0.01
                runtime = 10.0 # seconds
                # Set up clocks. The dsolver to know before assigning stoich
                moose.setClock( 4, dt4 )
                moose.setClock( 5, dt5 )

                makeModel()
                moose.useClock( 4, '/model/compartment/dsolve', 'process' )
                # Ksolve must be scheduled after dsolve.
                moose.useClock( 5, '/model/compartment/ksolve', 'process' )

                moose.reinit()
                moose.start( runtime ) # Run the model

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

                atot = sum( a.vec.conc )
                btot = sum( b.vec.conc )
                ctot = sum( c.vec.conc )
                dtot = sum( d.vec.conc )

                print(('tot = ', atot, btot, ctot, dtot, ' (b+c)=', btot+ctot))
                displayPlots()
                moose.start( runtime ) # Run the model
                atot = sum( a.vec.conc )
                btot = sum( b.vec.conc )
                ctot = sum( c.vec.conc )
                dtot = sum( d.vec.conc )

                print(('tot = ', atot, btot, ctot, dtot, ' (b+c)=', btot+ctot))

                quit()
コード例 #51
0
ファイル: test_function.py プロジェクト: physicalist/moose
def test_var_order():
    """The y values are one step behind the x values because of
    scheduling sequences"""
    nsteps = 5
    simtime = nsteps
    dt = 1.0
    # fn0 = moose.Function('/fn0')
    # fn0.x.num = 2
    # fn0.expr = 'x0 + x1'
    # fn0.mode = 1
    fn1 = moose.Function('/fn1')
    fn1.x.num = 2
    fn1.expr = 'y1 + y0 + x1 + x0'
    fn1.mode = 1
    inputs = np.arange(0, nsteps+1, 1.0)
    x0 = moose.StimulusTable('/x0')
    x0.vector = inputs
    x0.startTime = 0.0
    x0.stopTime = simtime
    x0.stepPosition = 0.0
    inputs /= 10
    x1 = moose.StimulusTable('/x1')
    x1.vector = inputs
    x1.startTime = 0.0
    x1.stopTime = simtime
    x1.stepPosition = 0.0
    inputs /= 10
    y0 = moose.StimulusTable('/y0')
    y0.vector = inputs
    y0.startTime = 0.0
    y0.stopTime = simtime
    y0.stepPosition = 0.0
    inputs /= 10
    y1 = moose.StimulusTable('/y1')
    y1.vector = inputs
    y1.startTime = 0.0
    y1.startTime = 0.0
    y1.stopTime = simtime
    y1.stepPosition = 0.0
    moose.connect(x0, 'output', fn1.x[0], 'input')
    moose.connect(x1, 'output', fn1.x[1], 'input')
    moose.connect(fn1, 'requestOut', y0, 'getOutputValue')
    moose.connect(fn1, 'requestOut', y1, 'getOutputValue')
    z1 = moose.Table('/z1')
    moose.connect(z1, 'requestOut', fn1, 'getValue')
    for ii in range(32):
        moose.setClock(ii, dt)
    moose.reinit()
    moose.start(simtime)
    for ii in range(len(z1.vector)):
        print ii, z1.vector[ii]
コード例 #52
0
def test_hhcomp():
    """Create and simulate a single spherical compartment with
    Hodgkin-Huxley Na and K channel.

    Plots Vm, injected current, channel conductances.

    """
    model = moose.Neutral('/model')
    data = moose.Neutral('/data')    
    comp, na, k = create_hhcomp(parent=model.path)
    print comp.Rm, comp.Cm, na.Ek, na.Gbar, k.Ek, k.Gbar
    pg = moose.PulseGen('%s/pg' % (model.path))
    pg.firstDelay = 20e-3
    pg.firstWidth = 40e-3
    pg.firstLevel = 1e-9
    pg.secondDelay = 1e9
    moose.connect(pg, 'output', comp, 'injectMsg')
    inj = moose.Table('%s/pulse' % (data.path))
    moose.connect(inj, 'requestOut', pg, 'getOutputValue')
    vm = moose.Table('%s/Vm' % (data.path))
    moose.connect(vm, 'requestOut', comp, 'getVm')
    gK = moose.Table('%s/gK' % (data.path))
    moose.connect(gK, 'requestOut', k, 'getGk')
    gNa = moose.Table('%s/gNa' % (data.path))
    moose.connect(gNa, 'requestOut', na, 'getGk')
    simdt = 1e-6
    plotdt = 1e-4
    simtime = 100e-3
    if (1):
        moose.showmsg( '/clock' )
        for i in range(8):
            moose.setClock( i, simdt )
        moose.setClock( 8, plotdt )
        moose.reinit()
    else:
        utils.resetSim([model.path, data.path], simdt, plotdt, simmethod='ee')
        moose.showmsg( '/clock' )
    moose.start(simtime)
    t = np.linspace(0, simtime, len(vm.vector))
    plt.subplot(211)
    plt.plot(t, vm.vector * 1e3, label='Vm (mV)')
    plt.plot(t, inj.vector * 1e9, label='injected (nA)')
    plt.legend()
    plt.title('Vm')
    plt.subplot(212)
    plt.title('Conductance (uS)')
    plt.plot(t, gK.vector * 1e6, label='K')
    plt.plot(t, gNa.vector * 1e6, label='Na')
    plt.legend()
    plt.show()
    plt.close()
コード例 #53
0
ファイル: fig6.py プロジェクト: BhallaLab/HillTau
def runSim(chem, ht, cps, runtime):
    print("-------------------------------------> RUNNING: ", chem)
    modelId = moose.loadModel("KKIT_MODELS/" + chem, 'model', 'gsl')
    for i in range(0, 20):
        moose.setClock(i, plotDt)

    moose.reinit()
    mooseTime = time.time()
    moose.start(runtime)
    mooseTime = time.time() - mooseTime
    moose.delete('/model')

    jsonDict = hillTau.loadHillTau("HT_MODELS/" + ht)
    hillTau.scaleDict(jsonDict, hillTau.getQuantityScale(jsonDict))
    model = hillTau.parseModel(jsonDict)
    model.dt = plotDt
    htTime = 0.0
    for i in range(htReps):
        model.reinit()
        t0 = time.time()
        model.advance(runtime)
        htTime += time.time() - t0

    # Now run it again, but in steady-state mode for HillTau
    htTime2 = 0.0
    for i in range(htReps):
        model.reinit()
        t0 = time.time()
        model.advance(runtime, settle=True)
        htTime2 += time.time() - t0

    # Now do the COPASI thing.
    shutil.copy("SBML_MODELS/" + cps, "temp.sbml")

    # It croaks if you just give the file name. Have to use ./temp.sbml
    smodel = pycotools3.model.ImportSBML("./temp.sbml")
    m = smodel.load_model()
    #TC = pycotools3.tasks.TimeCourse( m, end = runtime, step_size = plotDt, run = True, save = False )
    TC = pycotools3.tasks.TimeCourse(m,
                                     end=runtime,
                                     step_size=plotDt,
                                     run=False,
                                     save=False)
    TC.run = True
    TC.set_timecourse()
    TC.set_report()
    t0 = time.time()
    TC.simulate()
    ctime = time.time() - t0

    return [chem, mooseTime, htTime, htTime2, ctime, runtime]
コード例 #54
0
def test_var_order():
    nsteps = 5
    simtime = nsteps
    dt = 1.0
    fn1 = moose.Function('/fn1')
    fn1.expr = 'B+A+y0+y1'
    inputs = np.arange(0, nsteps + 1, 1.0)
    x0 = moose.StimulusTable('/x0')
    x0.vector = inputs
    x0.startTime = 0.0
    x0.stopTime = simtime
    x0.stepPosition = 0.0
    print('x0', x0.vector)
    inputs /= 10
    x1 = moose.StimulusTable('/x1')
    x1.vector = inputs
    x1.startTime = 0.0
    x1.stopTime = simtime
    x1.stepPosition = 0.0
    print('x1', x1.vector)
    inputs /= 10
    y0 = moose.StimulusTable('/y0')
    y0.vector = inputs
    y0.startTime = 0.0
    y0.stopTime = simtime
    y0.stepPosition = 0.0
    print('y0', y0.vector)
    inputs /= 10
    y1 = moose.StimulusTable('/y1')
    y1.vector = inputs
    print('y1', y1.vector)
    y1.startTime = 0.0
    y1.startTime = 0.0
    y1.stopTime = simtime
    y1.stepPosition = 0.0
    moose.connect(x0, 'output', fn1['A'], 'input')
    moose.connect(x1, 'output', fn1['B'], 'input')
    moose.connect(fn1, 'requestOut', y0, 'getOutputValue')
    moose.connect(fn1, 'requestOut', y1, 'getOutputValue')

    z1 = moose.Table('/z1')
    moose.connect(z1, 'requestOut', fn1, 'getValue')
    for ii in range(32):
        moose.setClock(ii, dt)
    moose.reinit()
    moose.start(simtime)
    expected = [0, 1.1, 2.211, 3.322, 4.433, 5.544]
    assert np.allclose(z1.vector,
                       expected), "Excepted %s, got %s" % (expected, z1.vector)
    print('Passed order vars')
コード例 #55
0
def example():
    pg = moose.PulseGen('pulse')
    pg.delay[0] = 1.0
    pg.width[0] = 0.2
    pg.level[0] = 0.5
    tab = moose.Table('tab')
    moose.connect(tab, 'requestOut', pg, 'getOutputValue')
    moose.setClock(0, 0.01)
    moose.setClock(1, 0.01)
    moose.useClock(0, pg.path, 'process')
    moose.useClock(1, tab.path, 'process')
    moose.reinit()
    moose.start(5.0)
    tab.plainPlot('output_tabledemo.csv')
コード例 #56
0
 def schedule(self, simdt, plotdt, clampmode):
     self.simdt = simdt
     self.plotdt = plotdt
     if clampmode == 'vclamp':
         self.clamp_ckt.do_voltage_clamp()
     else:
         self.clamp_ckt.do_current_clamp()
     moose.setClock(0, simdt)
     moose.setClock(1, simdt)
     moose.setClock(2, simdt)
     moose.setClock(3, plotdt)
     # Ensure we do not create multiple scheduling
     if not self.scheduled:
         moose.useClock(
             0, '%s/#[TYPE=Compartment]' % (self.model_container.path),
             'init')
         moose.useClock(0, '%s/##' % (self.clamp_ckt.path), 'process')
         moose.useClock(
             1, '%s/#[TYPE=Compartment]' % (self.model_container.path),
             'process')
         moose.useClock(2, '%s/#[TYPE=HHChannel]' % (self.squid_axon.path),
                        'process')
         moose.useClock(3, '%s/#[TYPE=Table]' % (self.data_container.path),
                        'process')
         self.scheduled = True
     moose.reinit()
コード例 #57
0
def test_xreac5():
    for i in range(10, 18):
        moose.setClock(i, 0.001)
    runtime = 100
    makeModel()
    moose.reinit()
    moose.start(runtime)

    e1 = moose.element('model/compartment/s')
    e2 = moose.element('model/endo/s')
    assert almostEq(2.0 * e1.conc, e2.conc), \
            "Expected %g, Got %g" % (e1.conc, e2.conc )

    moose.delete('/model')
コード例 #58
0
    def simulate(self, simtime=simtime, dt=dt, plotif=False, **kwargs):

        self.dt = dt
        self.simtime = simtime
        self.T = np.ceil(simtime / dt)
        self.trange = np.arange(0, self.simtime, dt)

        for i in range(self.N):
            if noiseInj:
                ## Gaussian white noise SD added every dt interval should be
                ## divided by sqrt(dt), as the later numerical integration
                ## will multiply it by dt.
                ## See the Euler-Maruyama method, numerical integration in
                ## http://www.scholarpedia.org/article/Stochastic_dynamical_systems
                self.noiseTables.vec[i].vector = self.Iinject + \
                    np.random.normal( \
                        scale=self.noiseInjSD*np.sqrt(self.Rm*self.Cm/self.dt), \
                        size=self.T ) # scale = SD
                self.noiseTables.vec[i].stepSize = 0  # use current time
                # as x value for interpolation
                self.noiseTables.vec[i].stopTime = self.simtime

        self._init_network(**kwargs)
        if plotif:
            self._init_plots()

        # moose simulation
        moose.useClock(1, '/network', 'process')
        moose.useClock(2, '/plotSpikes', 'process')
        moose.useClock(3, '/plotVms', 'process')
        if CaPlasticity:
            moose.useClock(3, '/plotWeights', 'process')
            moose.useClock(3, '/plotCa', 'process')
        moose.setClock(0, dt)
        moose.setClock(1, dt)
        moose.setClock(2, dt)
        moose.setClock(3, dt)
        moose.setClock(9, dt)
        t1 = time.time()
        print 'reinit MOOSE -- takes a while ~20s.'
        moose.reinit()
        print 'reinit time t = ', time.time() - t1
        t1 = time.time()
        print 'starting'
        moose.start(self.simtime)
        print 'runtime, t = ', time.time() - t1

        if plotif:
            self._plot()
コード例 #59
0
def updateTicks(tickDtMap):
    """Try to assign dt values to ticks.

    Parameters
    ----------
    tickDtMap: dict
    map from tick-no. to dt value. if it is empty, then default dt
    values are assigned to the ticks.

    """
    for tickNo, dt in list(tickDtMap.items()):
        if tickNo >= 0 and dt > 0.0:
            moose.setClock(tickNo, dt)
    if all([(v == 0) for v in list(tickDtMap.values())]):
        setDefaultDt()
コード例 #60
0
def multilevel_pulsegen():
    pg = moose.PulseGen('pulsegen')
    pg.count = 5
    for ii in range(pg.count):
        pg.level[ii] = ii + 1
        pg.width[ii] = 0.1
        pg.delay[ii] = 0.5 * (ii + 1)
    tab = moose.Table('tab')
    moose.connect(tab, 'requestOut', pg, 'getOutputValue')
    moose.setClock(0, 0.01)
    moose.useClock(0, '%s,%s' % (pg.path, tab.path), 'process')
    moose.reinit()
    moose.start(20.0)
    plt.plot(tab.vector)
    plt.show()