def loadGran98NeuroML_L123(filename, nogui=False):
    neuromlR = NeuroML()
    populationDict, projectionDict = neuromlR.readNeuroMLFromFile(filename)
    soma_path = populationDict["Gran"][1][0].path + "/Soma_0"
    somaVm = setupTable("somaVm", moose.Compartment(soma_path), "Vm")
    somaCa = setupTable("somaCa", moose.CaConc(soma_path + "/Gran_CaPool_98"), "Ca")
    somaIKCa = setupTable("somaIKCa", moose.HHChannel(soma_path + "/Gran_KCa_98"), "Gk")

    soma = moose.Compartment(soma_path)
    print ("Reinit MOOSE ... ")
    resetSim(["/elec", "/cells"], simdt, plotdt, simmethod="ee")  # from moose.utils
    print ("Running ... ")
    moose.start(runtime)
    print ("Finished simulation of %s seconds" % runtime)

    if not nogui:
        from pylab import *

        tvec = arange(0.0, runtime, plotdt)
        plot(tvec, somaVm.vector[1:])
        title("Soma Vm")
        xlabel("time (s)")
        ylabel("Voltage (V)")
        figure()
        plot(tvec, somaCa.vector[1:])
        title("Soma Ca")
        xlabel("time (s)")
        ylabel("Ca conc (mol/m^3)")
        figure()
        plot(tvec, somaIKCa.vector[1:])
        title("KCa current (A)")
        xlabel("time (s)")
        ylabel("")
        print "Showing plots ..."
        show()
Example #2
0
def testModel( useSolver ):
	elecDt = 20e-6
	chemDt = 1e-4
	plotDt = 2e-4
	plotName = 'gn.plot'
	if ( useSolver ):
		elecDt = 50e-6
		chemDt = 2e-3
		plotName = 'mcs.plot'

	makeModel()
	moose.setClock( 0, elecDt )
	moose.setClock( 1, elecDt )
	moose.setClock( 2, elecDt )
	moose.setClock( 5, chemDt )
	moose.setClock( 6, chemDt )
	moose.setClock( 7, plotDt )
	moose.setClock( 8, plotDt )
	moose.useClock( 0, '/model/##[ISA=Compartment]', 'init' )
	moose.useClock( 1, '/model/##[ISA=Compartment],/model/##[ISA=SpikeGen]', 'process' )
	moose.useClock( 2, '/model/##[ISA=SynBase],/model/##[ISA=ChanBase],/model/##[ISA=CaConc]','process')
	moose.useClock( 8, '/graphs/#', 'process' )

	moose.reinit()
	moose.start( 0.1 )
	dumpPlots( plotName )
    def simulate( self, simTime, simDt = 1e-3, plotDt = None ):
        '''Simulate the cable '''

        if plotDt is None:
            plotDt = simDt / 2
        self.simDt = simDt
        self.plotDt = plotDt
        self.setupDUT( )
 
        # Setup clocks 
        utils.dump("STEP", "Setting up the clocks ... ")
        moose.setClock( 0, self.simDt )
        moose.setClock( 1, self.simDt )
        moose.setClock( 2, self.simDt )

        ## Use clocksc
        moose.useClock( 0, '/cable/##'.format(self.cablePath), 'process' )
        moose.useClock( 1, '/cable/##'.format(self.cablePath), 'init' )
        moose.useClock( 2, '{}/##'.format(self.tablePath), 'process' )

        utils.dump("STEP"
                , [ "Simulating cable for {} sec".format(simTime)
                    , " simDt: %s, plotDt: %s" % ( self.simDt, self.plotDt )
                    ]
                )
        self.setupHSolve( )
        moose.reinit( )
        utils.verify( )
        moose.start( simTime )
Example #4
0
def testNeuroMeshMultiscale():
        useHsolve = 1
        runtime = 0.5
        if useHsolve:
	    elecDt = 50e-6
        else:
	    elecDt = 10e-6
	chemDt = 0.005
	ePlotDt = 0.5e-3
	cPlotDt = 0.005
	plotName = 'nm.plot'

	makeNeuroMeshModel()
	print "after model is completely done"
	for i in moose.wildcardFind( '/model/chem/#/#/#/transloc#' ):
		print i[0].name, i[0].Kf, i[0].Kb, i[0].kf, i[0].kb

	makeChemPlots()
	makeElecPlots()
	makeCaPlots()
	moose.setClock( 0, elecDt )
	moose.setClock( 1, elecDt )
	moose.setClock( 2, elecDt )
	moose.setClock( 4, chemDt )
	moose.setClock( 5, chemDt )
	moose.setClock( 6, chemDt )
	moose.setClock( 7, cPlotDt )
	moose.setClock( 8, ePlotDt )
        if useHsolve:
	    hsolve = moose.HSolve( '/model/elec/hsolve' )
	    moose.useClock( 1, '/model/elec/hsolve', 'process' )
	    hsolve.dt = elecDt
	    hsolve.target = '/model/elec/compt'
	    moose.reinit()
        else:
	    moose.useClock( 0, '/model/elec/##[ISA=Compartment]', 'init' )
	    moose.useClock( 1, '/model/elec/##[ISA=Compartment]', 'process' )
	    moose.useClock( 2, '/model/elec/##[ISA=ChanBase],/model/##[ISA=SynBase],/model/##[ISA=CaConc]','process')

	moose.useClock( 1, '/model/elec/##[ISA=SpikeGen]', 'process' )
	moose.useClock( 2, '/model/##[ISA=SynBase],/model/##[ISA=CaConc]','process')
	#moose.useClock( 5, '/model/chem/##[ISA=PoolBase],/model/##[ISA=ReacBase],/model/##[ISA=EnzBase]', 'process' )
	#moose.useClock( 4, '/model/chem/##[ISA=Adaptor]', 'process' )
	moose.useClock( 4, '/model/chem/#/dsolve', 'process' )
	moose.useClock( 4, '/model/chem/#/ksolve', 'init' )
	moose.useClock( 5, '/model/chem/#/ksolve', 'process' )
	moose.useClock( 6, '/model/chem/spine/adaptCa', 'process' )
	moose.useClock( 6, '/model/chem/dend/DEND/adaptCa', 'process' )
	moose.useClock( 7, '/graphs/chem/#', 'process' )
	moose.useClock( 8, '/graphs/elec/#,/graphs/ca/#', 'process' )
        moose.element( '/model/elec/soma' ).inject = 2e-10
        moose.element( '/model/chem/psd/Ca' ).concInit = 0.001
        moose.element( '/model/chem/spine/Ca' ).concInit = 0.002
        moose.element( '/model/chem/dend/DEND/Ca' ).concInit = 0.003
	moose.reinit()

	moose.start( runtime )
#        moose.element( '/model/elec/soma' ).inject = 0
#	moose.start( 0.25 )
        makeGraphics( cPlotDt, ePlotDt )
Example #5
0
def run(nogui):
    
    reader = NML2Reader(verbose=True)

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

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

        for i in range(len(t)):
            vfile.write('%s\t%s\n'%(t[i],vm.vector[i]))
        vfile.close()
        plt.subplot(211)
        plt.plot(t, vm.vector * 1e3, label='Vm (mV)')
        plt.legend()
        plt.title('Vm')
        plt.subplot(212)
        plt.title('Input')
        plt.plot(t, inj.vector * 1e9, label='injected (nA)')
        #plt.plot(t, gK.vector * 1e6, label='K')
        #plt.plot(t, gNa.vector * 1e6, label='Na')
        plt.legend()
        plt.figure()
        test_channel_gates()
        plt.show()
        plt.close()
Example #6
0
def example():
    """
    The RandSpike class generates spike events from a Poisson process
    and sends out a trigger via its `spikeOut` message. It is very
    common to approximate the spiking in many neurons as a Poisson
    process, i.e., the probability of `k` spikes in any interval `t`
    is given by the Poisson distribution:

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

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

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

    In this model the synaptic conductance is set so high that each
    incoming spike evokes an action potential.
    """
    ectopic = moose.RandSpike('ectopic_input')
    ectopic.rate = 10.0
    cellmodel = create_cell()
    moose.connect(ectopic, 'spikeOut', 
                  cellmodel['synhandler'].synapse[0], 'addSpike')
    tab_vm = moose.Table('/Vm')
    moose.connect(tab_vm, 'requestOut', cellmodel['neuron'], 'getVm')
    moose.reinit()
    moose.start(SIMTIME)
    return tab_vm
 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.
Example #8
0
def main( runTime ):
    try:
        moose.delete('/acc92')
        print("Deleted old model")
    except Exception as  e:
        print("Could not clean. model not loaded yet")

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

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

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

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

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

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

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

    print('[INFO] Saving data to csv files in %s' % dataDir)
    tabPath1 = os.path.join( dataDir, '%s_%s.csv' % (table.name, runTime))
    numpy.savetxt(tabPath1, numpy.matrix([t, table.vector]).T, newline='\n')
    tabPath2 = os.path.join( dataDir, '%s_%s.csv' % (table1.name, runTime) )
    numpy.savetxt(tabPath2, numpy.matrix([t1, table1.vector]).T, newline='\n')
Example #9
0
def run_LIF():
	## reset and run the simulation
	print("Reinit MOOSE.")
	## from moose_utils.py sets clocks and resets
	resetSim(['/cells[0]'], SIMDT, PLOTDT, simmethod='ee')
	print("Running now...")
	moose.start(RUNTIME)
    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()
Example #11
0
def singleCompt( name, params ):
    mod = moose.copy( '/library/' + name + '/' + name, '/model' )
    A = moose.element( mod.path + '/A' )
    Z = moose.element( mod.path + '/Z' )
    Z.nInit = 1
    Ca = moose.element( mod.path + '/Ca' )
    CaStim = moose.element( Ca.path + '/CaStim' )
    runtime = params['preStimTime'] + params['stimWidth'] + params['postStimTime'] 
    steptime = 100

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

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

    moose.reinit()
    moose.start( runtime )
    t = np.arange( 0, runtime + 1e-9, tab.dt )
    return name, t, tab.vector
Example #12
0
def loadGran98NeuroML_L123(filename):
    neuromlR = NeuroML()
    populationDict, projectionDict = \
        neuromlR.readNeuroMLFromFile(filename)
    soma_path = populationDict['Gran'][1][0].path+'/Soma_0'
    somaVm = setupTable('somaVm',moose.Compartment(soma_path),'Vm')
    somaCa = setupTable('somaCa',moose.CaConc(soma_path+'/Gran_CaPool_98'),'Ca')
    somaIKCa = setupTable('somaIKCa',moose.HHChannel(soma_path+'/Gran_KCa_98'),'Gk')
    ## Am not able to plot KDr gating variable X when running under hsolve
    #KDrX = setupTable('ChanX',moose.HHChannel(soma_path+'/Gran_KDr_98'),'X')

    print "Reinit MOOSE ... "
    resetSim(['/elec',cells_path], simdt, plotdt, simmethod='hsolve')

    print "Running ... "
    moose.start(runtime)
    tvec = arange(0.0,runtime*2.0,plotdt)
    tvec = tvec[ : somaVm.vector.size ]
    plot(tvec,somaVm.vector)
    title('Soma Vm')
    xlabel('time (s)')
    ylabel('Voltage (V)')
    figure()
    plot(tvec,somaCa.vector)
    title('Soma Ca')
    xlabel('time (s)')
    ylabel('Ca conc (mol/m^3)')
    figure()
    plot(tvec,somaIKCa.vector)
    title('soma KCa current')
    xlabel('time (s)')
    ylabel('KCa current (A)')
    print "Showing plots ..."
    show()
Example #13
0
def run_sim_parallel(passive=True, solver='hsolve'):
    data_info_list = []
    model_info_list = []
    for jj, ti in enumerate(intervals):
        for ii, st in enumerate(stim_order):
            experiment_name = 'expt_%d_%d' % (jj, ii)
            dinfo, minfo = setup_experiment(experiment_name, st, tonset, ti, passive=passive, solver=solver)
            data_info_list.append(dinfo)
            model_info_list.append(minfo)
    mutils.setDefaultDt(elecdt=simdt)
    mutils.assignDefaultTicks()
    moose.reinit()
    moose.start(tstop)
    print('$$$$$$$$$$$', moose.element('/clock'    ).currentTime)
    axes_vm = fig.add_subplot(111)
    # axes_vm_out = fig.add_subplot(121)
    # axes_vm_in = fig.add_subplot(122, sharex=axes_vm_out, sharey=axes_vm_out)
    ################
    # axes_vm = fig.add_subplot(311)
    # axes_nmda = fig.add_subplot(312)
    # axes_ampa = fig.add_subplot(313)
    for jj, ti in enumerate(intervals):
        for ii, st in enumerate(stim_order):
            dinfo = data_info_list[jj * len(stim_order) + ii]
            print('Interval=', ti, 'Stim order=', st)
            print('dinfo:', dinfo)
            print(dinfo['soma_vm'])
            print(dinfo['soma_vm'].vector)
            v = dinfo['soma_vm'].vector
            t = np.linspace(0, tstop, len(v))
            print('num points=', len(t), 't0=', t[0], 't_last=', t[-1], 'v0=', v[0], 'v_last=', v[-1])
Example #14
0
def main():
        """
        This example illustrates loading, and running a kinetic model 
        for a bistable positive feedback system, defined in kkit format. 
        This is based on Bhalla, Ram and Iyengar, Science 2002.

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

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

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

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

	# Display all plots.
        img = mpimg.imread( 'mapkFB.png' )
        fig = plt.figure( figsize=(12, 10 ) )
        png = fig.add_subplot( 211 )
        imgplot = plt.imshow( img )
        ax = fig.add_subplot( 212 )
	x = moose.wildcardFind( '/model/#graphs/conc#/#' )
        t = numpy.arange( 0, x[0].vector.size, 1 ) * x[0].dt
        ax.plot( t, x[0].vector, 'b-', label=x[0].name )
        ax.plot( t, x[1].vector, 'c-', label=x[1].name )
        ax.plot( t, x[2].vector, 'r-', label=x[2].name )
        ax.plot( t, x[3].vector, 'm-', label=x[3].name )
        plt.ylabel( 'Conc (mM)' )
        plt.xlabel( 'Time (seconds)' )
        pylab.legend()
        pylab.show()
def main():
    """ This example illustrates loading, running of an SBML model defined in XML format.\n
	The model 00001-sbml-l3v1.xml is taken from l3v1 SBML testcase.\n
	Plots are setup.\n
	Model is run for 20sec.\n
	As a general rule we created model under '/path/model' and plots under '/path/graphs'.\n
    """

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

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

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

        
    # Reset and Run
    moose.reinit()
    moose.start(runtime)
def main():
    """
    This is a toy model of synaptic bidirectional plasticity. The model has 
    a small a bistable chemical switch, and a small set of reactions that
    decode calcium input. One can turn the switch on with short high 
    calcium pulses (over 2 uM for about 10 sec). One can turn it back off
    again using a long, lower calcium pulse (0.2 uM, 2000 sec).
    """
    method = 'old_gssa'  # This is the Gillespie Stoichastic Systems Algorithm
    if ( len( sys.argv ) >= 2 ):
        method = sys.argv[1]
    if ( method == "gsl" ):
        method = "old_gsl"
    if ( method == "gssa" ):
        method = "old_gssa"
    # Load in the model and set up to use the specified method
    modelId = moose.loadModel( './stargazin_synapse.g', 'model', method )
    moose.start( 1000.0 ) # Run the model for 1000 seconds.
    Ca = moose.element( '/model/kinetics/BULK/Ca' )

    applyInputPulseTrain(Ca, 'concInit'
            , [ (1000.0, 1.0e-3)
                , (10.0, 0.08e-3)
                , (50.0, 1.0e-3)
                , (10.0, 0.08e-3)
                , (1000.0, 0.2e-3)
                , (2000.0, 0.08e-3) 
                ]
            )
    moose.start(2000.0)
    displayPlots()
    quit()
Example #17
0
def loadAndRun(solver=True):
    simtime = 500e-3
    model = moose.loadModel('../data/h10.CNG.swc', '/cell')
    comp = moose.element('/cell/apical_e_177_0')
    soma = moose.element('/cell/soma')
    for i in range(10):
        moose.setClock(i, dt)
    if solver:
        solver = moose.HSolve('/cell/solver')
        solver.target = soma.path
        solver.dt = dt
    stim = moose.PulseGen('/cell/stim')
    stim.delay[0] = 50e-3
    stim.delay[1] = 1e9
    stim.level[0] = 1e-9
    stim.width[0] = 2e-3    
    moose.connect(stim, 'output', comp, 'injectMsg')
    tab = moose.Table('/cell/Vm')
    moose.connect(tab, 'requestOut', comp, 'getVm')
    tab_soma = moose.Table('/cell/Vm_soma')
    moose.connect(tab_soma, 'requestOut', soma, 'getVm')
    moose.reinit()
    print('[INFO] Running for %s' % simtime)
    moose.start(simtime )
    vec = tab_soma.vector 
    moose.delete( '/cell' )
    return vec
def runSTGNeuroML_L123(filename):
    neuromlR = NeuroML()
    populationDict, projectionDict = \
        neuromlR.readNeuroMLFromFile(filename)
    soma1_path = populationDict['AB_PD'][1][0].path+'/Soma_0'
    soma1Vm = setupTable('somaVm',moose.Compartment(soma1_path),'Vm')
    soma2_path = populationDict['LP'][1][0].path+'/Soma_0'
    soma2Vm = setupTable('somaVm',moose.Compartment(soma2_path),'Vm')
    soma3_path = populationDict['PY'][1][0].path+'/Soma_0'
    soma3Vm = setupTable('somaVm',moose.Compartment(soma3_path),'Vm')
    #somaCa = setupTable('somaCa',moose.CaConc(soma_path+'/CaPool_STG'),'Ca')
    #somaIKCa = setupTable('somaIKCa',moose.HHChannel(soma_path+'/KCa_STG'),'Ik')
    #somaCaE = setupTable('somaCaE',moose.HHChannel(soma_path+'/CaT_STG/nernst'),'E')
    ## Am not able to plot KDr gating variable X when running under hsolve
    #KDrX = setupTable('ChanX',moose.HHChannel(soma_path+'/Gran_KDr_98'),'X')

    print "Reinit MOOSE ... "
    resetSim(['/elec',cells_path], simdt, plotdt, simmethod='hsolve')

    print "Running ... "
    moose.start(runtime)
    tvec = arange(0.0,runtime+2*plotdt,plotdt)
    tvec = tvec[ : soma1Vm.vec.size ]
    plot(tvec,soma1Vm.vec,label='AB_PD',color='g',linestyle='dashed')
    plot(tvec,soma2Vm.vec,label='LP',color='r',linestyle='solid')
    plot(tvec,soma3Vm.vec,label='PY',color='b',linestyle='dashed')
    legend()
    title('Soma Vm')
    xlabel('time (s)')
    ylabel('Voltage (V)')
    print "Showing plots ..."
    show()
Example #19
0
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' )
def test():
    global finish_all_
    os.environ['MOOSE_STREAMER_ADDRESS'] = 'http://127.0.0.1:%d'%port_
    done = mp.Value('d', 0)
    q = mp.Queue()
    client = mp.Process(target=socket_client, args=(q, done))
    client.start()

    time.sleep(0.1)

    print( '[INFO] Socket client is running now' )
    ts = models.simple_model_a()
    moose.reinit()
    time.sleep(0.1)
    # If TCP socket is created, some delay is often neccessary before start. Don't
    # know why. probably some latency in a fresh TCP socket. A TCP guru can
    # tell.
    moose.start(50)
    print( 'MOOSE is done' )

    time.sleep(0.5)
    done.value = 1
    res = q.get()
    client.join()

    if not res:
        raise RuntimeWarning('Nothing was streamed')
    for k in res:
        a = res[k][1::2]
        b = moose.element(k).vector
        print(k, len(a), len(b))
        assert( (a==b).all())
    print( 'Test 1 passed' )
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()
def run_single_channel(channelname, Gbar, simtime, simdt=testutils.SIMDT, plotdt=testutils.PLOTDT):
    testId = uuid.uuid4().int
    container = moose.Neutral('test%d' % (testId))
    model_container = moose.Neutral('%s/model' % (container.path))
    data_container = moose.Neutral('%s/data' % (container.path))
    params = testutils.setup_single_compartment(
        model_container, data_container,
        channelbase.prototypes[channelname],
        Gbar)
    vm_data = params['Vm']
    gk_data = params['Gk']
    ik_data = params['Ik']
    testutils.setup_clocks(simdt, plotdt)
    testutils.assign_clocks(model_container, data_container)
    moose.reinit()
    print 'Starting simulation', testId, 'for', simtime, 's'
    moose.start(simtime)
    print 'Finished simulation'
    vm_file = 'data/%s_Vm.dat' % (channelname)
    gk_file = 'data/%s_Gk.dat' % (channelname)
    ik_file = 'data/%s_Ik.dat' % (channelname)
    tseries = np.array(range(len(vm_data.vec))) * simdt
    print 'Vm:', len(vm_data.vec), 'Gk', len(gk_data.vec), 'Ik', len(ik_data.vec)
    data = np.c_[tseries, vm_data.vec]
    np.savetxt(vm_file, data)
    print 'Saved Vm in', vm_file
    print len(gk_data.vec), len(vm_data.vec)
    data = np.c_[tseries, gk_data.vec]
    np.savetxt(gk_file, data)
    print 'Saved Gk in', gk_file
    data = np.c_[tseries, ik_data.vec]
    np.savetxt(ik_file, data)
    print 'Saved Gk in', ik_file
    return params
Example #23
0
 def resetAndStartSimulation(self):
     """TODO this should provide a clean scheduling through all kinds
     of simulation or default scheduling should be implemented in MOOSE
     itself. We need to define a policy for handling scheduling. It can
     be pushed to the plugin-developers who should have knowledge of
     the scheduling criteria for their domain."""
     settings = config.MooseSetting()
     try:
         simdt_kinetics = float(settings[config.KEY_KINETICS_SIMDT])
     except ValueError:
         simdt_kinetics = 0.1
     try:
         simdt_electrical = float(settings[config.KEY_ELECTRICAL_SIMDT])
     except ValueError:
         simdt_electrical = 0.25e-4
     try:
         plotdt_kinetics = float(settings[config.KEY_KINETICS_PLOTDT])
     except ValueError:
         plotdt_kinetics = 0.1
     try:
         plotdt_electrical = float(settings[config.KEY_ELECTRICAL_PLOTDT])
     except ValueError:
         plotdt_electrical = 0.25e-3
     try:
         simtime = float(settings[config.KEY_SIMTIME])
     except ValueError:
         simtime = 1.0
     moose.reinit()
     view = self.plugin.getRunView()
     moose.start(simtime)
     if view.getCentralWidget().plotAll:
         view.getCentralWidget().plotAllData()
     self.setCurrentView('run')        
Example #24
0
def main():
    """
    A toy compartmental neuronal + chemical model that causes bad things
    to happen to the hsolver, as of 28 May 2013. Hopefully this will
    become irrelevant soon.
    """
    fineDt = 1e-5
    coarseDt = 5e-5
    make_spiny_compt()
    make_plots()
    for i in range( 8 ):
        moose.setClock( i, fineDt )
    moose.setClock( 8, coarseDt )
    moose.reinit()
    moose.start( 0.1 )
    display_plots( 'instab.plot' )
    # make Hsolver and rerun
    hsolve = moose.HSolve( '/n/hsolve' )
    for i in range( 8 ):
        moose.setClock( i, coarseDt )
    hsolve.dt = coarseDt
    hsolve.target = '/n/compt'
    moose.reinit()
    moose.start( 0.1 )
    display_plots( 'h_instab.plot' )
    pylab.show()
Example #25
0
def test_crossing_single():
    """This function creates an ematrix of two PulseGen elements and
    another ematrix of two Table elements.

    The two pulsegen elements have same amplitude but opposite phase.

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

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

    """
    size = 2
    pg = moose.PulseGen('pulsegen', size)
    for ix, ii in enumerate(pg.vec):
        pulse = moose.element(ii)
        pulse.delay[0] = 1.0
        pulse.width[0] = 2.0
        pulse.level[0] = (-1)**ix
    tab = moose.Table('table', size)
    moose.connect(tab.vec[0], 'requestOut', pg.vec[1], 'getOutputValue', 'Single')
    moose.connect(tab.vec[1], 'requestOut', pg.vec[0], 'getOutputValue', 'Single')
    print 'Neighbors:'
    for t in tab.vec:
        print t.path
        for n in moose.element(t).neighbors['requestOut']:
            print 'requestOut <-', n.path
    moose.setClock(0, 0.1)
    moose.useClock(0, '/##', 'process')
    moose.start(5)
    for ii in tab.vec:
        t = moose.Table(ii).vector
        print len(t)
        pylab.plot(t)
    pylab.show()
Example #26
0
def main():
	"""
	This snippet shows the use of several objects.
	This snippet sets up a StimulusTable to control a RandSpike which
	sends its outputs to two places: to a SimpleSynHandler on an IntFire,
	which is used to monitor spike arrival, and to various Stats objects.
    Each of these are recorded and plotted.
	The StimulusTable has a sine-wave waveform.
	"""
        make_model()

        moose.reinit()
        moose.start( runtime )
        plots = moose.element( '/plots' )
        plot1 = moose.element( '/plot1' )
        plot2 = moose.element( '/plot2' )
        plotf = moose.element( '/plotf' )
        t = [i * dt for i in range( plot1.vector.size )]
        pylab.plot( t, plots.vector, label='stimulus' )
        pylab.plot( t, plot1.vector, label='spike rate mean' )
        pylab.plot( t, plot2.vector, label='Vm mean' )
        pylab.plot( t, plotf.vector, label='Vm' )
        pylab.legend()
        pylab.show()

	'''
def main():
		makeModel()
                '''
                '''
		ksolve = moose.Ksolve( '/model/compartment/ksolve' )
		stoich = moose.Stoich( '/model/compartment/stoich' )
		stoich.compartment = moose.element( '/model/compartment' )
		stoich.ksolve = ksolve
		stoich.path = "/model/compartment/##"
		#solver.method = "rk5"
		#mesh = moose.element( "/model/compartment/mesh" )
		#moose.connect( mesh, "remesh", solver, "remesh" )
                '''
		moose.setClock( 5, 1.0 ) # clock for the solver
		moose.useClock( 5, '/model/compartment/ksolve', 'process' )
                '''

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

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

		quit()
Example #28
0
 def continueSimulation(self):
     """TODO implement this somewhere else"""
     try:
         simtime = float(config.MooseSetting()[config.KEY_SIMTIME])
     except ValueError:
         simtime = 1.0
     moose.start(simtime)      
def testCubeMultiscale( useSolver ):
    elecDt = 10e-6
    chemDt = 1e-4
    plotDt = 5e-4
    plotName = 'mc.plot'
    if ( useSolver ):
        elecDt = 50e-6
        chemDt = 2e-3
        plotName = 'mcs.plot'
    makeCubeMultiscale()

    makeChemPlots()
    makeElecPlots()
    moose.setClock( 0, elecDt )
    moose.setClock( 1, elecDt )
    moose.setClock( 2, elecDt )
    moose.setClock( 5, chemDt )
    moose.setClock( 6, chemDt )
    moose.setClock( 7, plotDt )
    moose.setClock( 8, plotDt )
    moose.useClock( 0, '/model/elec/##[ISA=Compartment]', 'init' )
    moose.useClock( 1, '/model/elec/##[ISA=Compartment],/model/elec/##[ISA=SpikeGen]', 'process' )
    moose.useClock( 2, '/model/elec/##[ISA=SynBase],/model/elec/##[ISA=ChanBase],/model/elec/##[ISA=CaConc]','process')
    moose.useClock( 5, '/model/##[ISA=ReacBase],/model/##[ISA=EnzBase]', 'process' )
    moose.useClock( 6, '/model/##[ISA=PoolBase],/model/chem/##[ISA=Adaptor]', 'process' )
    moose.useClock( 7, '/graphs/#', 'process' )
    moose.useClock( 8, '/graphs/elec/#', 'process' )
    if ( useSolver ):
        makeSolvers( elecDt )
    moose.reinit()
    moose.start( 1.0 )
    dumpPlots( plotName )
Example #30
0
def run_model_fig7(chans_1, chans_2, chans_3):
    to_run = simtime
    delta_t = 0.25 * tau
    for ii in range(0, len(chans_1), 2):
        print(ii)
        print('-----------------')
        chans_1[ii].Gk = 1 / Rm
        chans_1[ii+1].Gk = 1 / Rm
        chans_2[-ii-1].Gk = 1 / Rm
        chans_2[-ii-2].Gk = 1 / Rm
        for chan in chans_3:
            chan.Gk = 0.25 / Rm
        
        for chan in chans_1:
            print(chan.Gk, end=' ')
        print()
        for chan in chans_2:
            print(chan.Gk, end=' ')
        print()
        moose.start(delta_t)
        for chan in chans_1:
            chan.Gk = 0.0
        for chan in chans_2:
            chan.Gk = 0.0
        to_run = to_run - delta_t
    for chan in chans_3:
        chan.Gk = 0.0
    moose.start(to_run)
Example #31
0
def main():
    '''
    On the command-line, in moose-examples/snippets directory, run ``python STDP.py``
    '''
    setupModel()
    dwlist_neg = []
    ddt = 2e-3  # s
    t_extent = 20e-3  # s
    # dt = tpost - tpre
    # negative dt corresponds to post before pre
    print '-----------------------------------------------'
    for deltat in arange(t_extent, 0.0, -ddt):
        reset_settle()
        # post neuron spike
        make_neuron_spike(1)
        moose.start(deltat)
        # pre neuron spike after deltat
        make_neuron_spike(0)
        moose.start(1e-3)
        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()
        # pre neuron spike
        make_neuron_spike(0)
        moose.start(deltat)
        # post neuron spike after deltat
        make_neuron_spike(1)
        moose.start(1e-3)
        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 '-----------------------------------------------'

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

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

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

    # STDP curve
    fig = plt.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) # has to be after tight_layout()

    plt.show()
Example #32
0
def run_sim():
    moose.reinit()
    moose.start(900e-3)
moose.useClock(1, '/model/#[TYPE=Compartment]', 'process')
moose.useClock(2, axon_Vm.path, 'process')
moose.useClock(2, axon_Vm2.path, 'process')
# Now initialize everything and get set
moose.reinit()

# Here we take a simple approach to try current injection experiemnt:
# Run the simulation for some time. Then set the `inject` field of the
# soma to a positive value and run for some more time. This will
# emulate a current injection for that duration. Finally, remove the
# current injection by setting the `inject` field back to 0 and run
# for some more time to get the discharging curve.

# Normally you should use a PulseGen object for this instead of
# stopping the simulation midway to set the inject field..
moose.start(50e-3)
# Now apply 1 pA current injection to soma
soma.inject = 1e-12
# Run for 100 ms
moose.start(100e-3)
# Stop the current injection
soma.inject = 0.0
# Run for 500 ms
moose.start(500e-3)
clock = moose.Clock('/clock')  # Get a handle to the global clock
time = np.linspace(0, clock.currentTime, len(axon_Vm.vector))
data = np.vstack((time, axon_Vm.vector, axon_Vm2.vector))

np.savetxt('compartmental_neuron.csv',
           data.T,
           delimiter=',',
Example #34
0
              'injectMsg')
tab_v_soma = moose.Table('/data/soma_v')
moose.connect(tab_v_soma, 'requestOut', moose.element('/model/h10/soma'),
              'getVm')
tab_v_apical = moose.Table('/data/apical_v')
moose.connect(tab_v_apical, 'requestOut',
              moose.element('/model/h10/apical_e_177_0'), 'getVm')

import sys

if __name__ == '__main__':
    if len(sys.argv) > 1:
        solver = moose.HSolve('/model/h10/solver')
        solver.target = '/model/h10/soma'
        solver.dt = dt
        outfile = 'h10.CNG.moose.hsolve.txt'
    else:
        outfile = 'h10.CNG.moose.ee.txt'
        for ii in range(20):
            moose.setClock(ii, dt)

    simtime = 100e-3
    moose.reinit()
    moose.start(simtime)
    t = np.arange(len(tab_v_soma.vector)) * simtime / len(tab_v_soma.vector)
    np.savetxt(outfile,
               np.vstack([t, tab_v_soma.vector, tab_v_apical.vector]).T)

#
# h10.CNG.moose.py ends here
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

    inj_delay = 20E-3
    inj_amp = 2E-3 # Pleace chirp amplitudes 2.5E-3 and 15E-3
    inj_width = 1

    # Model creation
    soma, moose_paths = simple_model(model_name, comp_passive, channel_settings, ca_params, length, diameter)
    chirp_test = chirp(gen_name="chirp",amp=inj_amp, f0=0.1, f1=40, T=1, start=inj_delay, end=inj_width+inj_delay, simdt=simdt,amp_offset=0)
    moose.connect(chirp_test, 'valueOut', soma, 'injectMsg')
    # Output table
    tabs = creat_moose_tables()
    soma_c_table = create_output_table(table_element='/output', table_name='somchirpIm')
    moose.connect(soma_c_table, 'requestOut', chirp_test, 'getValue')

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

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

    # set conductance for a list to Ca_v1, Ca_V2 and CC
    from collections import namedtuple
    cond = namedtuple('cond', 'k Ltype Ntype cl')
    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): {1}, Ca_V2 (N) :{0}, ca_cc :{2} K : {3}'.format(V1, V2, cc, K), xlab="Time in Seconds", ylab="Volage (V)")
        plt.show()

    # plot chirp signal
    t = np.arange(0, simtime, 1/len(soma_c_table.vector))
    plt.plot(t, soma_c_table.vector)
    plt.xlabel("time in seconds", fontsize = 15)
    plt.ylabel("voltage (V)", fontsize = 15)
    plt.show()

    current_time_domain = soma_c_table.vector
    voltage_time_domain = tabs['vm'][0].vector
    import scipy.fftpack as fftpack
    current_fft = fftpack.fft(current_time_domain)
    voltage_fft = fftpack.fft(voltage_time_domain)
    current_magnitude = np.abs(current_fft)
    voltage_magnitude = np.abs(voltage_fft)
    current_phase = np.angle(current_fft)
    voltage_phase = np.angle(voltage_fft)
    freq_current = np.fft.fftfreq(len(current_fft), 1/len(soma_c_table.vector))
    freq_voltage = np.fft.fftfreq(len(voltage_fft), 1/len(soma_c_table.vector))
    N = len(current_fft)
    plt.figure("soma_current")
    plt.plot(freq_current, current_magnitude)
    plt.xlabel('Frequecy (Hz)', fontsize = 15)
    plt.ylabel('Magnitude (mA)', fontsize = 15)
    plt.show()

    plt.figure("membrane voltage")
    plt.plot(freq_voltage, voltage_magnitude)
    plt.xlabel('Frequecy (Hz)', fontsize = 15)
    plt.ylabel('Volts (V)', fontsize = 15)
    plt.show()

    plt.figure("membrane voltage")
    plt.plot(freq_voltage, voltage_magnitude/current_magnitude)
    plt.xlabel('Frequecy (Hz)', fontsize = 15)
    plt.ylabel('ohms ($\Omega$)', fontsize = 15)
    plt.show()

    plt.title('membrance impedance')
    plt.plot(freq_voltage, voltage_phase - current_phase)
    plt.xlabel('Frequecy (Hz)', fontsize = 15)
    plt.ylabel('phase ($\Theta$)', fontsize = 15)
    plt.show()
def main():
    """
    This example illustrates how to set up a diffusion/transport model with
    a simple reaction-diffusion system in a tapering cylinder:

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

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

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

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

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

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

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

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

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

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

    msg = 'Ratio of initial to final total numbers of '
    got = np.array((atot2 / atot, btot2 / btot, ctot2 / ctot, dtot2 / dtot))
    msg += 'a=%f b=%f, c=%f, d=%f' % (tuple(got))
    print(msg)
    print('Initial to final (b+c)=%f' % (float(btot2 + ctot2) / (btot + ctot)))
    expected = np.array((1.00003087, 1.39036644, 0.92191184, 1.11427514))
    error = got - expected
    rerror = np.abs(error) / expected
    assert np.allclose(got, expected,
                       atol=1e-3), "Got %s, expected %s" % (got, expected)
Example #37
0
def main(experiment_title):
    # Simulation information.
    simtime = 0.1
    simdt = 0.25e-6
    plotdt = 0.25E-3

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

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

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

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

    moose_paths = [soma.path]
    for channel_name, channel_obj in channels_set.items():
        copy_connect_channel_moose_paths(channel_obj, channel_name,
                                         moose_paths)

    # Create calcium pools in library.
    ca_pool = create_ca_conc_pool(ca_params)

    # copy calcium pools to all compartments.
    copy_ca_pools_moose_paths(ca_pool, 'CaPool', moose_paths)

    # Connect calciums pools to channels in compartments.
    connect_ca_pool_to_chan(chan_name='SKca',
                            chan_type='ca_dependent',
                            calname='CaPool',
                            moose_paths=moose_paths)
    connect_ca_pool_to_chan(chan_name='CaL',
                            chan_type='ca_permeable',
                            calname='CaPool',
                            moose_paths=moose_paths)

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

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

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

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

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

    # Plot output tables.
    v_plot = plot_vm_table(simtime,
                           soma_v_table,
                           soma_i_table,
                           title=experiment_title)
    plt.grid(True)
    plt.legend(['v', 'i'])
    plt.show()
Example #38
0
                res_buf = moose.Table('/data/' + difshell_name + str(i) + '_' +
                                      difbuff_name + str(j))
                buftab[i].append(res_buf)
                moose.connect(buftab[i][j], 'requestOut', buf, 'getBBound')

    moose.reinit()
    if not gbar:
        for i, dif in enumerate(difs):
            if i == 0:
                dif.C = Ca_initial
            else:
                dif.C = 0
            for j, dbuf in enumerate(difb[i]):
                dbuf.bFree = dbuf.bTot

    moose.start(t_stop)

    t = np.linspace(0, t_stop, len(vmtab.vector))
    fname = 'moose_results_difshell_no_' + str(
        difshell_no) + '_difbuffer_no_' + str(difbuff_no) + '_pump_' + str(
            pumps) + '_gbar_' + str(gbar) + '.txt'
    print(fname)
    header = 'time Vm Ik Gk'
    number = 4 + difshell_no * (difbuff_no + 1)
    res = np.zeros((len(t), number))
    res[:, 0] = t
    res[:, 1] = vmtab.vector
    res[:, 2] = iktab.vector
    res[:, 3] = gktab.vector

    for i in range(difshell_no):
Example #39
0
import moose
import rdesigneur as rd
rdes = rd.rdesigneur(
    stimList=[['soma', '1', '.', 'vclamp',
               '-0.065 + (t>0.1 && t<0.2) * 0.02']],
    plotList=[
        ['soma', '1', '.', 'Vm', 'Soma membrane potential'],
        ['soma', '1', 'vclamp', 'current', 'Soma holding current'],
    ])
rdes.buildModel()
moose.reinit()
moose.start(0.3)
rdes.display()
def main():
    """
    This example sets up the kinetic solver and steady-state finder, on
    a bistable model of a chemical system. The model is set up within the
    script.
    The algorithm calls the steady-state finder 50 times with different 
    (randomized) initial conditions, as follows:

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

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

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

    * the first attractor (stable point) and the saddle point (unstable 
      fixed point) are both found quite often. But the second
      attractor is found just once. 
      It has a very small basin of attraction.
    * The values found for each of the fixed points match well with the
      values found by running the system to steady-state at the end.
    * There are a large number of failures to find a fixed point. These are
      found and reported in the diagnostics. They show up on the plot
      as cases where the 10-second runs are not flat.
 
    If you wanted to find fixed points in a production model, you would
    not need to do the 10-second runs, and you would need to eliminate the
    cases where the state-finder failed. Then you could identify the good
    points and keep track of how many of each were found.

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

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

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

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

    # Now display the states of the system at more length to compare.
    moose.start( 100.0 ) # Run the model for 100 seconds.

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

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

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

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

    quit()
Example #41
0
def runPanelCDEF(name, dist, seqDt, numSpine, seq, stimAmpl):
    numCompts = 10
    comptLength = 4
    startPos = numCompts * comptLength
    preStim = 10.0
    blanks = 20
    print moose.le('/library')
    rdes = rd.rdesigneur(
        useGssa=False,
        turnOffElec=True,
        chemPlotDt=0.1,
        #diffusionLength = params['diffusionLength'],
        diffusionLength=1e-6,
        #cellProto = [['cell', 'soma']],
        cellProto=[['./taper.p', 'elec']],
        chemProto=[['dend', name]],
        #chemDistrib = [['dend', 'soma', 'install', '1' ]],
        chemDistrib=[['dend', '#', 'install', '1']],
        #plotList = [['soma', '1', 'dend' + '/A', 'n', '# of A']],
        plotList=[['#', '1', 'dend' + '/A', 'n', '# of A']],
    )
    rdes.buildModel()
    #for i in range( 20 ):
    #moose.setClock( i, 0.02 )
    A = moose.vec('/model/chem/dend/A')
    print "\n\t $$$>:", moose.element('/model/chem')
    Z = moose.vec('/model/chem/dend/Z')
    print moose.element('/model/chem/dend/A/Adot').expr
    print moose.element('/model/chem/dend/B/Bdot').expr
    print moose.element('/model/chem/dend/Ca/CaStim').expr
    phase = moose.vec('/model/chem/dend/phase')
    ampl = moose.vec('/model/chem/dend/ampl')
    #vel = moose.vec( '/model/chem/dend/vel' )
    #vel.nInit = 1e-6 * seqDt
    ampl.nInit = stimAmpl
    stride = int(dist) / numSpine
    phase.nInit = 10000
    Z.nInit = 0
    headV = A[0].volume
    print 'headV is', headV
    pos = range(startPos + 1, len(A), 2)
    print pos
    #pos = (21,23,25,27,29)
    for j in range(numSpine):
        #k = blanks + j * stride
        k = pos[j]
        print 'Volume of A is ', A[k].volume, A[k - 1].volume, A[
            k -
            2].volume, A[k -
                         3].volume, A[k -
                                      13].volume, A[k -
                                                    15].volume, A[k -
                                                                  24].volume
        print 'k is', k, 'Length of Z is', len(Z.n)
        Z[k].nInit = 1
        phase[k].nInit = preStim + seq[j] * seqDt
        print 'k is', k, 'phase is', phase[k].n
    moose.reinit()
    runtime = 50
    snapshot = preStim + seqDt * (numSpine - 0.8)
    print preStim, seqDt, numSpine, (numSpine -
                                     0.8), "and the Snapshot>:", snapshot
    #snapshot = 26
    moose.start(snapshot)
    avec = moose.vec('/model/chem/dend/A').n
    avec_0 = moose.vec('/model/chem/dend/A')
    moose.start(runtime - snapshot)
    print avec_0, len(avec), runtime, (runtime - snapshot)
    tvec = []
    for i in range(5):
        #tab = moose.element( '/model/graphs/plot0[' + str( blanks + i * stride ) + ']' )
        tab = moose.element('/model/graphs/plot0[' + str(pos[i]) + ']')
        dt = tab.dt
        tvec.append(tab.vector)
    moose.delete('/model')
    return dt, tvec, avec
Example #42
0
def main():
    global num
    num = 100
    runtime = 11
    makeModel()
    dsolve = moose.element('/model/dsolve')
    moose.reinit()
    #moose.start( runtime ) # Run the model for 10 seconds.

    a = moose.element('/model/compartment/a')
    b = moose.element('/model/compartment/b')
    c = moose.element('/model/compartment/c')
    d = moose.element('/model/compartment/d')
    s = moose.element('/model/compartment/s')
    halfWidth = []
    timeArr = []
    maxFWHH = []
    r2 = moose.element('/model/compartment/r2')
    trialNum = str(c.diffConst) + str(r2.Kf) + str(r2.Kb)
    plt.ion()

    #fig = plt.figure( figsize=(12,10) )
    #png = fig.add_subplot(211)
    #  imgplot = plt.imshow( img )
    #ax = fig.add_subplot(212)
    #ax.set_ylim( 0, 2 )
    #plt.ylabel( 'Conc (mM)' )
    #plt.xlabel( 'Position along cylinder (microns)' )
    #pos = numpy.arange( 0, a.vec.conc.size, 1 )
    #timeLabel = plt.text(60, 0.4, 'time = 0')
    #line1, = ax.plot( pos, a.vec.conc, label='a' )
    #line2, = ax.plot( pos, b.vec.conc, label='c' )
    #line3, = ax.plot( pos, b.vec.conc, label='d' )
    #plt.legend()
    #fig.canvas.draw()
    w = len(a.vec.conc)
    h = w
    v2d = [[0 for x in range(w)] for y in range(h)]
    anC = []
    mm = moose.vec('/model/compartment/mesh')
    diffL = moose.element('/model/compartment').diffLength
    print a.vec[0].nInit, 'diff length', diffL
    list = [[0, 4]]
    for j in list:
        anC = []
        anC2 = []
        for i in range(len(a.vec.conc)):
            anC.append(2.0 * diffL *
                       (4.0 / (math.sqrt(4 * math.pi * a.diffConst * 4))) *
                       math.exp(-(mm[i].Coordinates[0]**2) /
                                (4 * a.diffConst * 4)))
            for k in range(len(a.vec.conc)):
                #anC.append((10/numpy.sqrt(4*numpy.pi*a.diffConst*1))*numpy.exp(-(i**2)/4*a.diffConst*1))
                #print mm[i].Coordinates[0]
                anC2.append(4.0 * diffL**2 *
                            (4.0 / (4 * numpy.pi * j[1] *
                                    numpy.sqrt(a.diffConst * a.diffConst))) *
                            numpy.exp(-(mm[i].Coordinates[0]**2) /
                                      (4 * a.diffConst * j[1]) -
                                      (mm[k].Coordinates[0]**2) /
                                      (4 * a.diffConst * j[1])))
                v2d[i][k] = 4.0 * diffL**2 * (4.0 / (
                    4 * numpy.pi * j[1] * numpy.sqrt(a.diffConst * a.diffConst)
                )) * numpy.exp(-(mm[i].Coordinates[0]**2) /
                               (4 * a.diffConst * j[1]) -
                               (mm[k].Coordinates[0]**2) /
                               (4 * a.diffConst * j[1]))
                #anC3.append(4*diffL**2*(3/(4*numpy.pi*4*numpy.sqrt(4*numpy.pi*4*a.diffConst*a.diffConst*a.diffConst)))*numpy.exp(-(mm[i].Coordinates[0]**2)/(4*a.diffConst*4)-(mm[i].Coordinates[0]**2)/(4*a.diffConst*4)-j/(4*a.diffConst*4)))
                #print (3/(numpy.sqrt(4*numpy.pi*a.diffConst*1)))*numpy.exp(-(mm[i].Coordinates[0]**2)/(4*a.diffConst*1))
                firstCell = diffL * (4.0 /
                                     (math.sqrt(4 * math.pi * a.diffConst * 4))
                                     ) * math.exp(-(mm[0].Coordinates[0]**2) /
                                                  (4 * a.diffConst * 4))
                firstCell2 = 2 * diffL**2 * (4.0 / (
                    4 * numpy.pi * j[1] * numpy.sqrt(a.diffConst * a.diffConst)
                )) * numpy.exp(-(mm[0].Coordinates[0]**2) /
                               (4 * a.diffConst * j[1]) -
                               (mm[0].Coordinates[0]**2) /
                               (4 * a.diffConst * j[1]))
        print 'analaytical sum 1D is', sum(
            anC) - firstCell, 'max of anC is', max(anC)
        print 'analaytical sum 2D is', sum(
            anC2) - 2 * firstCell - firstCell2 / 2, 'max of anC2 is', max(
                anC2), firstCell, firstCell2
        plt.plot(anC)
        plt.plot(anC2)
    raw_input()
    plt.figure(2)
    alongX = []
    for i in range(len(a.vec.conc)):
        alongX.append(v2d[i][2])
    plt.plot(alongX)
    time = 0
    for t in range(0, runtime):
        moose.start(0.5)
        time = time + 0.5
        if int(time == 4):
            print 'numerical sum is', sum(a.vec.conc), max(a.vec.conc)
            temp = a.vec.conc
            plt.figure(3)
            plt.plot(temp)
            raw_input()
        aList = a.vec.conc
        maxa = max(aList)
        #indMax = numpy.where(aList==maxa)
        #indMax = num/2
        indMax = 0
        halfMax = maxa / 2
        indHalfMax = (numpy.abs(aList[0:num] - halfMax)).argmin()
        #print 'maximum value is', maxa, 'postion is', numpy.where(aList==maxa)
        print 'maximum value is', maxa
        print 'half height is at', indHalfMax
        print 'half maximum is', aList[indHalfMax]
        #halfWidth.append(int(indMax[0])-indHalfMax)
        #halfWidth.append(indMax-indHalfMax)
        halfWidth.append(indHalfMax - indMax)
        timeArr.append(t)
        #line1.set_ydata( a.vec.conc )
        #line2.set_ydata( b.vec.conc )
        #line2.set_ydata( c.vec.conc )
        #line3.set_ydata( d.vec.conc )
        #timeLabel.set_text( "time = %d" % t )
        #fig.canvas.draw()
        print 'minimum and maximum of a', min(a.vec.conc), max(a.vec.conc)

    maxFWHH.append(max(halfWidth))
    print 'max FWHH is', max(halfWidth)
    fileName = 'data.xml'
    writeXML(timeArr, halfWidth, maxFWHH, trialNum, fileName)
Example #43
0
def probeStimulus(time):
    for t in numpy.arange(0, time, probeInterval):
        moose.start(probeInterval)
        for i in synSpineList:
            i.activation(probeAmplitude)
Example #44
0
def testNeuroMeshMultiscale():
    elecDt = 50e-6
    chemDt = 0.01
    ePlotDt = 0.5e-3
    cPlotDt = 0.01
    plotName = 'nm.plot'

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

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

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

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

    elec = fig.add_subplot(212)
    plt.ylabel('Vm (V)')
    plt.xlabel('time (seconds)')
    for x in moose.wildcardFind('/graphs/elec/#[ISA=Table]'):
        pos = numpy.arange(0, x.vector.size, 1) * ePlotDt
        line1, = elec.plot(pos, x.vector, label=x.name)
    plt.legend()

    fig.canvas.draw()
    raw_input()
    '''
        for x in moose.wildcardFind( '/graphs/##[ISA=Table]' ):
            t = numpy.arange( 0, x.vector.size, 1 )
            pylab.plot( t, x.vector, label=x.name )
        pylab.legend()
        pylab.show()
        '''

    pylab.show()
    print 'All done'
Example #45
0
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(0, 10):
        moose.setClock(i, 100)
    for i in range(10, 18):
        moose.setClock(i, dt)
    moose.setClock(18, plotdt)
    moose.reinit()
    buildPlots()
    # Run for baseline, tetanus, and post-tetanic settling time
    print 'starting...'
    t1 = time.time()
    moose.start(baselineTime)
    caPsd = moose.vec('/model/chem/psd/Ca_input')
    caDend = moose.vec('/model/chem/dend/DEND/Ca_input')
    castim = (numpy.random.rand(len(caPsd.concInit)) * 0.8 + 0.2) * psdTetCa
    caPsd.concInit = castim
    caDend.concInit = numpy.random.rand(len(caDend.concInit)) * dendTetCa
    moose.start(tetTime)
    caPsd.concInit = basalCa
    caDend.concInit = basalCa
    moose.start(interTetTime)
    caPsd.concInit = castim
    caDend.concInit = numpy.random.rand(len(caDend.concInit)) * dendTetCa
    moose.start(tetTime)
    caPsd.concInit = basalCa
    caDend.concInit = basalCa
    moose.start(postTetTime)
    caPsd.concInit = ltdCa
    caDend.concInit = ltdCa
    moose.start(ltdTime)
    caPsd.concInit = basalCa
    caDend.concInit = basalCa
    moose.start(postLtdTime)
    print 'real time = ', time.time() - t1

    if do3D:
        app = QtGui.QApplication(sys.argv)
        compts = moose.wildcardFind("/model/elec/#[ISA=compartmentBase]")
        ecomptPath = map(lambda x: x.path, compts)
        morphology = moogli.read_morphology_from_moose(name="",
                                                       path="/model/elec")
        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(0.1)
            return True

        viewer.set_callback(callback, idletime=0)
        viewer.showMaximized()
        viewer.show()
        app.exec_()

    displayPlots()
Example #46
0
def main( nT ):
    """
    This example implements a reaction-diffusion like system which is
    bistable and propagates losslessly. It is based on the NEURON example 
    rxdrun.py, but incorporates more compartments and runs for a longer time.
    The system is implemented in a function rather than as a proper system
    of chemical reactions. Please see rxdReacDiffusion.py for a variant that 
    uses a reaction plus a function object to control its rates.
    """
    print( 'Using %d threads' % nT )

    dt = 0.1

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

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


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

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

    #Set up solvers
    ksolve = moose.Gsolve( '/cylinder/Gsolve' )
    try:
        ksolve.numThreads = nT
    except Exception as e:
        print( 'OLD MOOSE. Does not support multithreading' )
    dsolve = moose.Dsolve( '/cylinder/dsolve' )
    stoich = moose.Stoich( '/cylinder/stoich' )
    stoich.compartment = compt
    stoich.ksolve = ksolve
    stoich.dsolve = dsolve
    stoich.path = '/cylinder/##'

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

    # Run and plot it.
    moose.reinit()
    updateDt = 50
    runtime = updateDt * 10
    t1 = time.time()
    res = []
    for t in range( 0, runtime-1, updateDt ):
        moose.start( updateDt )
        y = c.vec.n
        res.append( (np.mean(y), np.std(y)) )

    expected = [(9.0, 0.0), (6.0, 0.0), (5.0, 0.0), (3.0, 0.0), (2.0, 0.0),
        (2.0, 0.0), (2.0, 0.0), (1.0, 0.0), (1.0, 0.0), (1.0, 0.0)]
    print(("Time = ", time.time() - t1))
    print( res )
    assert res == expected
Example #47
0
def main():
    """
        This example illustrates loading, and running a kinetic model 
        for a bistable system, defined in kkit format. 
        Defaults to the deterministic gsl method, you can pick the 
        stochastic one by 

            ``python filename gssa``

        The model starts out equally poised between sides **b** and **c**. 
        Then there is a small molecular 'tap' to push it over to **b**.
        Then we apply a moderate push to show that it is now very stably in
        this state. it takes a strong push to take it over to **c**.
        Then it takes a strong push to take it back to **b**.
        This is a good model to use as the basis for running stochastically
        and examining how state stability is affected by changing volume.
        """

    solver = "gsl"  # Pick any of gsl, gssa, ee..
    #solver = "gssa"  # Pick any of gsl, gssa, ee..
    #moose.seed( 1234 ) # Needed if stochastic.
    mfile = './M1719.g'
    runtime = 300.0
    if (len(sys.argv) >= 2):
        solver = sys.argv[1]
    modelId = moose.loadModel(mfile, 'model', solver)
    # Increase volume so that the stochastic solver gssa
    # gives an interesting output
    compt = moose.element('/model/kinetics')
    compt.volume = 0.2e-19
    r = moose.element('/model/kinetics/equil')

    moose.reinit()
    moose.start(runtime)
    r.Kf *= 1.1  # small tap to break symmetry
    moose.start(runtime / 10)
    r.Kf = r.Kb
    moose.start(runtime)

    r.Kb *= 2.0  # Moderate push does not tip it back.
    moose.start(runtime / 10)
    r.Kb = r.Kf
    moose.start(runtime)

    r.Kb *= 5.0  # Strong push does tip it over
    moose.start(runtime / 10)
    r.Kb = r.Kf
    moose.start(runtime)
    r.Kf *= 5.0  # Strong push tips it back.
    moose.start(runtime / 10)
    r.Kf = r.Kb
    moose.start(runtime)

    # Display all plots.
    df = pd.DataFrame()
    img = mpimg.imread('strongBis.png')
    fig = plt.figure(figsize=(12, 10))
    png = fig.add_subplot(211)
    imgplot = plt.imshow(img)
    ax = fig.add_subplot(212)
    x = moose.wildcardFind('/model/#graphs/conc#/#')
    dt = moose.element('/clock').tickDt[18]
    t = numpy.arange(0, x[0].vector.size, 1) * dt
    df['time'] = t
    for i in range(3):
        df[x[i].name] = x[i].vector
    ax.plot(t, x[0].vector, 'r-', label=x[0].name)
    ax.plot(t, x[1].vector, 'g-', label=x[1].name)
    ax.plot(t, x[2].vector, 'b-', label=x[2].name)
    plt.ylabel('Conc (mM)')
    plt.xlabel('Time (seconds)')
    pylab.legend()
    pylab.savefig('res.png')
    df.to_csv('%s.csv' % solver, index=False)
Example #48
0
 def callback(morphology, viewer):
     moose.start(0.1)
     return True
Example #49
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)
    # chirp_test = chirp(gen_name="chirp",amp=1E-9, f0=0.1, f1=500, T=0.8, start=inj_delay, end=inj_width+inj_delay, simdt=simdt,amp_offset=5E-9)

    # moose.connect(chirp_test, 'valueOut', soma, 'injectMsg')
    # Output table
    tabs = creat_moose_tables()
    # moose.connect(soma_i_table, 'requestOut', chirp_test, 'getValue')

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

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

    # Plot output tables.
    #v_plot = plot_vm_table(simtime,soma_v_table, soma_i_table, title="soma vs i")
    #plt.grid(True)
    #plt.legend(['v', 'i'])
    #plt.show()
    # set conductance for a list to Ca_v1, Ca_V2 and CC
    from collections import namedtuple
    cond = namedtuple('cond', 'k Ltype Ntype cl')
    test_conductances = [
        cond(k=0.5E-3, Ltype=0.18E-3, Ntype=0.4E-3, cl=40E-3),  # control test
        cond(k=0.5E-3, Ltype=0.18E-3, Ntype=0,
             cl=40E-3),  # L-type frequecy reduce test
        cond(k=0.5E-3, Ltype=0, Ntype=0.4E-3,
             cl=40E-3),  # N-type amplitude reduce test
        cond(k=0.5E-3, Ltype=0.18E-3, Ntype=0.4E-3,
             cl=0),  # cl-type Current abolish test
        cond(k=0.5E-3 * 0.2, Ltype=0.18E-3, Ntype=0.4E-3,
             cl=40E-3)  # K AHP reduce test
    ]

    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): {1}, Ca_V2 (N) :{0}, ca_cc :{2} K : {3}'.
            format(V1, V2, cc, K),
            xlab="Time in Seconds",
            ylab="Volage (V)")
        plt.show()
        ['./chans/nax.xml'],
        ['./chans/CaConc.xml'],
        ['./chans/Ca.xml']
    ],
    cellProto = [['./cells/simple.swc', 'elec']],
    chanDistrib = [ \
        ["hd", "#dend#,#apical#", "Gbar", "50e-2*(1+(p*3e4))" ],
        ["kdr", "#", "Gbar", "p < 50e-6 ? 500 : 100" ],
        ["na3", "#soma#,#dend#,#apical#", "Gbar", "850" ],
        ["nax", "#soma#,#axon#", "Gbar", "1250" ],
        ["kap", "#axon#,#soma#", "Gbar", "300" ],
        ["kap", "#dend#,#apical#", "Gbar", "300*(H(100-p*1e6)) * (1+(p*1e4))" ],
        ["Ca_conc", "#", "tau", "0.0133" ],
        ["kad", "#soma#,#dend#,#apical#", "Gbar", "50" ],
        ["Ca", "#", "Gbar", "50" ]
    ],
    stimList = [['soma', '1', '.', 'inject', '(t>0.02) * 1e-9' ]],
    plotList = [['#', '1', '.', 'Vm', 'Membrane potential'],
            ['#', '1', 'Ca_conc', 'Ca', 'Ca conc (uM)']
            ],
    #moogList = [['#', '1', 'Ca_conc', 'Ca', 'Calcium conc (uM)', 0, 120],
    #    ['#', '1', '.', 'Vm', 'Soma potential']]
)

rdes.buildModel()
moose.reinit()
for a in moose.wildcardFind('/model/##'):
    print(a)
#  rdes.displayMoogli( 0.0002, 0.052 )
moose.start(10)
Example #51
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/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')
    ksolve0.method = "lsoda"
    ksolve1.method = "lsoda"
    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.numVarPools == 5)
    assert (stoich0.numBufPools == 1)
    assert (stoich0.numProxyPools == 1)
    assert (stoich0.numAllPools == 7)
    print(len(stoich0.proxyPools[stoich1]), end=' ')
    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 == 6)
    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()
Example #52
0
def run_sequence():
    """In this example we demonstrate the use of PyRun objects to execute
    Python statements from MOOSE. Here is a couple of fun things to
    indicate the power of MOOSE-Python integration.

    First we create a PyRun object called `Hello`. In its `initString`
    we put in Python statements that prints the element's string
    representation using pymoose-API. When ``moose.reinit()`` is
    called, this causes MOOSE to execute these Python statements which
    include Python calling a MOOSE function
    (Python->MOOSE->Python->MOOSE) - isn't that cool!

    We also initialize a counter called `hello_count` to 0.

    The statements in initString gets executed once, when we call
    ``moose.reinit()``.

    In the `runString` we put a couple of print statements to indicate
    the name fof the object which is running and the current
    count. Then we increase the count directly.

    When we call ``moose.start()``, the `runString` gets executed at
    each time step.

    The other PyRun object we create, is `/World`. In its `initString`
    apart from ordinary print statements and initialization, we define
    a Python function called ``incr_count``. This silly little
    function just increments the global `world_count` by 1.

    The `runString` for `World` simply calls this function to
    increment the count and print it.

    We may notice that we assign tick 0 to `Hello` and tick 1 to
    `World`. Looking at the output, you will realize that the
    sequences of the ticks strictly maintain the sequence of
    execution.

    """
    model = moose.Neutral('/model')
    hello_runner = moose.PyRun('/model/Hello')
    hello_runner.initString = """
print 'Init', moose.element('/model/Hello')
hello_count = 0
"""
    hello_runner.runString = """
print 'Running Hello'
print 'Hello count =', hello_count
hello_count += 1
"""
    hello_runner.run('from datetime import datetime')
    hello_runner.run(
        'print("Hello: current time:", datetime.now().isoformat())')
    moose.useClock(0, hello_runner.path, 'process')
    world_runner = moose.PyRun('World')
    world_runner.initString = """
print 'Init World'
world_count = 0
def incr_count():
    global world_count
    world_count += 1
"""
    world_runner.runString = """
print 'Running World'
print 'World count =', world_count
incr_count()
"""
    world_runner.run('from datetime import datetime')
    world_runner.run(
        'print("World: current time:", datetime.now().isoformat())')

    moose.useClock(0, world_runner.path, 'process')
    moose.reinit()
    moose.start(0.001)
Example #53
0
def main():
    library = moose.Neutral('/library')
    #makePassiveSoma( 'cell', params['dendL'], params['dendDia'] )
    makeDendProto()
    makeChemProto()
    rdes = rd.rdesigneur(
        turnOffElec=True,
        chemPlotDt=0.1,
        diffusionLength=params['diffusionL'],
        #cellProto=[['cell','soma']],
        cellProto=[['elec', 'dend']],
        chemProto=[['hydra', 'hydra']],
        chemDistrib=[['hydra', '#soma#,#dend#', 'install', '1']],
        stimList=[['soma', '1', '.', 'inject', '(t>0.01&&t<0.2)*1e-10']],
        plotList=[['soma', '1', 'dend/A', 'n', '# of A'],
                  ['soma', '1', 'dend/B', 'n', '# of B']],
        moogList=[['#', '1', '.', 'Vm', 'Vm']]
        #    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
    randper = np.random.uniform(1, 2, savec)
    #print randper, randper.size

    for i in range(0, savec - 1, 1):
        moose.element('/model/chem/dend/A').vec[i].nInit = randper[i]
        #print moose.element('/model/chem/dend/A').vec[i].nInit

    print moose.element('/model/chem/dend/A').vec.nInit.size
    print 'simulation start'
    moose.reinit()
    #moose.start(2)
    for t in range(0, 2000, 250):
        print 'in loop', t
        moose.start(250)
        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
    #rdes.displayMoogli(0.00005, 0.05, 0.0)
    #plt.plot(bvec)

    return bvec, avec, cvec
Example #54
0
        # ['soma', '1', 'CaL_Schan', 'Ik', 'Soma CaL_S current'],
    ],
)

rdes.buildModel()
# moose.element( '/model/elec/soma/vclamp' ).gain *= 0.001
moose.element('/model/elec/soma/Ca_conc').B = 28789637.7
moose.reinit()

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

moose.start( 6 )

# plt.figure(100)
# plt.plot(np.linspace(0,6,60000), somaNa_SXgate.vector**3, label='X gate')
# plt.plot(np.linspace(0,6,60000), somaNa_SYgate.vector, label='Y gate')
# plt.plot(np.linspace(0,6,60000), somaNa_SZgate.vector, label='Z gate')
# plt.xlabel('Time (s)')
# plt.ylabel('Gating probabilities')
# plt.title('Na_S gates ModelDB')
# plt.legend()

rdes.display()
Example #55
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])
Example #56
0
def main():
    """
This example implements a reaction-diffusion like system which is
bistable and propagates losslessly. It is based on the NEURON example
rxdrun.py, but incorporates more compartments and runs for a longer time.
The system is implemented in a function rather than as a proper system
of chemical reactions. Please see rxdReacDiffusion.py for a variant that
uses a reaction plus a function object to control its rates.
    """

    dt = 0.1

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

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

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

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

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

    #for i in range( 10, 18 ):
    #    moose.setClock( i, dt )

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

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

    pylab.ylim(0, 105)
    pylab.legend()
    pylab.show()
Example #57
0
def setup_model():
    """Setup a dummy model with a PulseGen and a SpikeGen. The SpikeGen
    detects the leading edges of the pulses created by the PulseGen
    and sends out the event times. We record the PulseGen outputValue
    as Uniform data and leading edge time as Event data in the NSDF
    file.

    """
    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(('Starting simulation at:', datetime.now().isoformat()))
    moose.reinit()
    moose.start(simtime)
    print(('Finished simulation at:', 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.fieldIndex)
    nsdf.stringAttr[eventDataPath] = 's'
Example #58
0
    synWeights = np.zeros((len(memory), len(memory)))
    synWeights = updateWeights(synWeights, memory)

    memoryFile2 = "memory2.csv"
    memory2 = np.loadtxt(memoryFile2)
    synWeights = updateWeights(synWeights, memory2)

    inputFile = "input.csv"
    inputData = np.loadtxt(inputFile)
    #cells,Vms,pgTable,inTables =
    cell, vmtable, pgTable, spikegen, intable = createNetwork(
        synWeights, inputData)
    moose.setClock(0, 1e-4)
    moose.useClock(0, '/hopfield/##,/data/##', 'process')
    moose.reinit()
    moose.start(0.2)
    ii = 0
    for vm in vmtable:
        plot(np.linspace(0, 0.2, len(vm.vector)),
             vm.vector + ii * 1.5e-7,
             label=vm.name)
        ii += 1
    show()
# #plot(pgTable.vector[1:])
# #for yset,inTable in enumerate(inTables):
# #    plot(float(yset)+inTable.vector[1:])
# for ySet,Vm in enumerate(Vms):
#     plot(float(2*ySet)/(1e+7)+Vm.vector[1:])
# #plot(Vms[0].vector[1:])
# show()
Example #59
0
def main():
    """
    This example illustrates the classic **Repressilator** model, based on
    Elowitz and Liebler, Nature 2000. The model has the basic architecture::
    
            A ---| B---| C
            T            |
            |            |
            |____________|
    
    where **A**, **B**, and **C** are genes whose products repress
    eachother. The plunger symbol indicates inhibition. The model 
    uses the Gillespie (stochastic) method by default but you can run it
    using a deterministic method by saying ``python repressillator.py gsl``
    
    Good things to do with this model include:

        * Ask what it would take to change period of repressillator:
            
            * Change inhibitor rates::

                inhib = moose.element( '/model/kinetics/TetR_gene/inhib_reac' )
                moose.showfields( inhib )
                inhib.Kf *= 0.1
    
            * Change degradation rates::

                degrade = moose.element( '/model/kinetics/TetR_gene/TetR_degradation' )
                degrade.Kf *= 10.0
        * Run in stochastic mode:
                
            * Change volumes, figure out how many molecules are present::

                lac = moose.element( '/model/kinetics/lac_gene/lac' )
                print lac.n``

            * Find when it becomes hopelessly unreliable with small volumes.
    """
    #solver = "gsl"  # Pick any of gsl, gssa, ee..
    solver = "gssa"  # Pick any of gsl, gssa, ee..
    mfile = '../../genesis/Repressillator.g'
    runtime = 6000.0
    if (len(sys.argv) >= 2):
        solver = sys.argv[1]
    modelId = moose.loadModel(mfile, 'model', solver)
    # Increase volume so that the stochastic solver gssa
    # gives an interesting output
    compt = moose.element('/model/kinetics')
    compt.volume = 1e-19
    dt = moose.element('/clock').tickDt[18]

    moose.reinit()
    moose.start(runtime)

    # Display all plots.
    img = mpimg.imread('repressillatorOsc.png')
    fig = plt.figure(figsize=(12, 10))
    png = fig.add_subplot(211)
    imgplot = plt.imshow(img)
    ax = fig.add_subplot(212)
    x = moose.wildcardFind('/model/#graphs/conc#/#')
    plt.ylabel('Conc (mM)')
    plt.xlabel('Time (seconds)')
    for x in moose.wildcardFind('/model/#graphs/conc#/#'):
        t = numpy.arange(0, x.vector.size, 1) * dt
        pylab.plot(t, x.vector, label=x.name)
    pylab.legend()
    pylab.show()
Example #60
0
moose.Neutral('/library')
moose.Neutral('/library/diffn')
moose.CubeMesh('/library/diffn/dend')
A = moose.Pool('/library/diffn/dend/A')
A.diffConst = 1e-10

rdes = rd.rdesigneur(
    turnOffElec=True,
    diffusionLength=1e-6,
    chemProto=[['diffn', 'diffn']],
    chemDistrib=[['diffn', 'soma', 'install', '1']],
    moogList=[['soma', '1', 'dend/A', 'conc', 'A Conc', 0, 360]])
rdes.buildModel()
rdes.displayMoogli(1, 2, rotation=0, azim=-np.pi / 2, elev=0.0, block=False)
moose.start(2)
av = moose.vec('/model/chem/dend/A')
for i in range(10):
    av[i].concInit = 1
moose.reinit()
plist = []
t0 = time.time()
for i in range(20):
    plist.append(av.conc[:200])
    moose.start(2)
print("[INFO ] Time taken %f" % (time.time() - t0))
quit()

fig = plt.figure(figsize=(10, 12))
plist = np.array(plist).T
plt.plot(range(0, 200), plist)