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 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 )
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 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 )
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()
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 main(): global synSpineList global synDendList numpy.random.seed( 1234 ) rdes = buildRdesigneur( ) for i in elecFileNames: print(i) rdes.cellProtoList = [ ['./cells/' + i, 'elec'] ] rdes.buildModel( ) assert( moose.exists( '/model' ) ) synSpineList = moose.wildcardFind( "/model/elec/#head#/glu,/model/elec/#head#/NMDA" ) temp = set( moose.wildcardFind( "/model/elec/#/glu,/model/elec/#/NMDA" ) ) synDendList = list( temp - set( synSpineList ) ) moose.reinit() buildPlots( rdes ) # Run for baseline, tetanus, and post-tetanic settling time t1 = time.time() probeStimulus( baselineTime ) tetanicStimulus( tetTime ) probeStimulus( postTetTime ) print(('real time = ', time.time() - t1)) printPsd( i + ".fig5" ) saveAndClearPlots( i + ".fig5" ) moose.delete( '/model' ) rdes.elecid = moose.element( '/' )
def runsim(self, simtime, stepsize=0.1, pulsearray=None): """Run the simulation for `simtime`. Save the data at the end.""" mutils.resetSim([self.model_container.path, self.data_container.path], self.simdt, self.plotdt, simmethod=self.solver) if pulsearray is not None: self.tweak_stimulus(pulsearray) moose.reinit() start = datetime.now() step_run(simtime, stepsize) end = datetime.now() # The sleep is required to get all threads to end while moose.isRunning(): time.sleep(0.1) delta = end - start config.logger.info('Simulation time with solver %s: %g s' % \ (self.solver, delta.seconds + delta.microseconds * 1e-6)) self.tseries = np.arange(0, simtime+self.plotdt, self.plotdt) # Now save the data for table_id in self.data_container.children: try: data = np.vstack((self.tseries, table_id[0].vec)) except ValueError as e: self.tseries = np.linspace(0, simtime, len(table_id[0].vec)) data = np.vstack((self.tseries, table_id[0].vec)) fname = 'data/%s_%s_%s.dat' % (self.celltype, table_id[0].name, self.solver) np.savetxt(fname, np.transpose(data)) print 'Saved', table_id[0].name, 'in', fname
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
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])
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()
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()
def main(): makeModel() gsolve = moose.Gsolve("/model/compartment/gsolve") stoich = moose.Stoich("/model/compartment/stoich") stoich.compartment = moose.element("/model/compartment") stoich.ksolve = gsolve stoich.path = "/model/compartment/##" # solver.method = "rk5" # mesh = moose.element( "/model/compartment/mesh" ) # moose.connect( mesh, "remesh", solver, "remesh" ) moose.setClock(5, 1.0) # clock for the solver moose.useClock(5, "/model/compartment/gsolve", "process") moose.reinit() moose.start(100.0) # Run the model for 100 seconds. a = moose.element("/model/compartment/a") b = moose.element("/model/compartment/b") # move most molecules over to bgsolve b.conc = b.conc + a.conc * 0.9 a.conc = a.conc * 0.1 moose.start(100.0) # Run the model for 100 seconds. # move most molecules back to a a.conc = a.conc + b.conc * 0.99 b.conc = b.conc * 0.01 moose.start(100.0) # Run the model for 100 seconds. # Iterate through all plots, dump their contents to data.plot. displayPlots() quit()
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()
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 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')
def deliverStim(currTime): global injectionCurrent global spineVm global somaVm if numpy.fabs( currTime - baselineTime ) < frameRunTime/2.0 : #start eList = moose.wildcardFind( '/model/elec/#soma#' ) assert( len(eList) > 0 ) eList[0].inject = injectionCurrent #print "1. injected current = ", injectionCurrent injectionCurrent += deltaCurrent #print "del stim first ", moose.element('/clock').currentTime if numpy.fabs( currTime - baselineTime - currPulseTime) < frameRunTime/2.0 : #end eList = moose.wildcardFind( '/model/elec/#soma#' ) assert( len(eList) > 0 ) eList[0].inject = 0.0 #print "2. injected current = ", injectionCurrent #print "del stim second ", moose.element('/clock').currentTime if runtime - currTime < frameRunTime * 2.0 : #print "3. reinit-ing" somaVm.append( moose.element( '/graphs/VmTab' ).vector ) spineVm.append( moose.element( '/graphs/eSpineVmTab' ).vector ) iList.append(injectionCurrent) if injectionCurrent < maxCurrent : moose.reinit()
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 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
def main(): ######## Put your favourite cell model here ###### ##This one is from PMID 22730554: Suo et al J. Mol Cell Biol 2012 filename = 'cells/ko20x-07.CNG.swc' moose.Neutral( '/library' ) rdes = rd.rdesigneur( \ cellProto = [[ filename, 'elec' ] ],\ passiveDistrib = passiveDistrib_, chanProto = chanProto_, chanDistrib = chanDistrib_ ) rdes.buildModel( '/model' ) moose.reinit() ################## Now we store plots ######################## somaVm = moose.Table( '/somaVm' ) moose.connect( somaVm, 'requestOut', rdes.soma, 'getVm' ) ################## Now we set up the display ######################## compts = moose.wildcardFind( "/model/elec/#[ISA=CompartmentBase]" ) compts[0].inject = inject print("Setting Up 3D Display") app = QtGui.QApplication(sys.argv) vm_viewer = create_vm_viewer(rdes, somaVm) vm_viewer.show() vm_viewer.start() return app.exec_()
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 showVisualization(): makeModel() elec = moose.element( '/model/elec' ) elec.setSpineAndPsdMesh( moose.element('/model/chem/spine'), moose.element('/model/chem/psd') ) eHead = moose.wildcardFind( '/model/elec/#head#' ) oldDia = [ i.diameter for i in eHead ] graphs = moose.Neutral( '/graphs' ) #makePlot( 'psd_x', moose.vec( '/model/chem/psd/x' ), 'getN' ) #makePlot( 'head_x', moose.vec( '/model/chem/spine/x' ), 'getN' ) makePlot( 'dend_x', moose.vec( '/model/chem/dend/x' ), 'getN' ) dendZ = makePlot( 'dend_z', moose.vec( '/model/chem/dend/z' ), 'getN' ) makePlot( 'head_z', moose.vec( '/model/chem/spine/z' ), 'getN' ) psdZ = makePlot( 'psd_z', moose.vec( '/model/chem/psd/z' ), 'getN' ) diaTab = makePlot( 'headDia', eHead, 'getDiameter' ) # print diaTab[0].vector[-1] # return dendrite = moose.element("/model/elec/dend") dendrites = [dendrite.path + "/" + str(i) for i in range(len(dendZ))] # print dendrites moose.reinit() spineHeads = moose.wildcardFind( '/model/elec/#head#') # print moose.wildcardFind( '/model/elec/##') # print "dendZ", readValues(dendZ) # print dendrite app = QtGui.QApplication(sys.argv) viewer = create_viewer("/model/elec", dendrite, dendZ, diaTab, psdZ) viewer.showMaximized() viewer.start() return app.exec_()
def assign_clocks(model_container_list, simdt, plotdt): """ Assign clocks to elements under the listed paths. This should be called only after all model components have been created. Anything created after this will not be scheduled. """ global inited # `inited` is for avoiding double scheduling of the same object if not inited: print(('SimDt=%g, PlotDt=%g' % (simdt, plotdt))) moose.setClock(0, simdt) moose.setClock(1, simdt) moose.setClock(2, simdt) moose.setClock(3, simdt) moose.setClock(4, plotdt) for path in model_container_list: print(('Scheduling elements under:', path)) moose.useClock(0, '%s/##[TYPE=Compartment]' % (path), 'init') moose.useClock(1, '%s/##[TYPE=Compartment]' % (path), 'process') moose.useClock(2, '%s/##[TYPE=SynChan],%s/##[TYPE=HHChannel]' % (path, path), 'process') moose.useClock(3, '%s/##[TYPE=SpikeGen],%s/##[TYPE=PulseGen]' % (path, path), 'process') moose.useClock(4, '/data/##[TYPE=Table]', 'process') inited = True moose.reinit()
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 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 resetSimulation(self, runTime, updateInterval, simulationInterval): self.runTime = runTime self.updateInterval = updateInterval self.simulationInterval = simulationInterval self.pause = False moose.reinit() self.simulationReset.emit()
def main(): makeModel() solver = moose.GslStoich("/model/compartment/solver") solver.path = "/model/compartment/##" solver.method = "rk5" mesh = moose.element("/model/compartment/mesh") moose.connect(mesh, "remesh", solver, "remesh") moose.setClock(5, 1.0) # clock for the solver moose.useClock(5, "/model/compartment/solver", "process") moose.reinit() moose.start(100.0) # Run the model for 100 seconds. a = moose.element("/model/compartment/a") b = moose.element("/model/compartment/b") # move most molecules over to b b.conc = b.conc + a.conc * 0.9 a.conc = a.conc * 0.1 moose.start(100.0) # Run the model for 100 seconds. # move most molecules back to a a.conc = a.conc + b.conc * 0.99 b.conc = b.conc * 0.01 moose.start(100.0) # Run the model for 100 seconds. # Iterate through all plots, dump their contents to data.plot. for x in moose.wildcardFind("/model/graphs/conc#"): moose.element(x[0]).xplot("scriptKineticSolver.plot", x[0].name) quit()
def main(): """ This shows the use of SynChan with Izhikevich neuron. This can be used for creating a network of Izhikevich neurons. """ simtime = 200.0 stepsize = 10.0 model_dict = make_model() vm, inject, gk, spike = setup_data_recording(model_dict['neuron'], model_dict['pulse'], model_dict['synapse'], model_dict['spike_in']) mutils.setDefaultDt(elecdt=0.01, plotdt2=0.25) mutils.assignDefaultTicks(solver='ee') moose.reinit() mutils.stepRun(simtime, stepsize) pylab.subplot(411) pylab.plot(pylab.linspace(0, simtime, len(vm.vector)), vm.vector, label='Vm (mV)') pylab.legend() pylab.subplot(412) pylab.plot(pylab.linspace(0, simtime, len(inject.vector)), inject.vector, label='Inject (uA)') pylab.legend() pylab.subplot(413) pylab.plot(spike.vector, pylab.ones(len(spike.vector)), '|', label='input spike times') pylab.legend() pylab.subplot(414) pylab.plot(pylab.linspace(0, simtime, len(gk.vector)), gk.vector, label='Gk (mS)') pylab.legend() pylab.show()
def setupSteadyState(simdt,plotDt): ksolve = moose.Ksolve( '/model/kinetics/ksolve' ) stoich = moose.Stoich( '/model/kinetics/stoich' ) stoich.compartment = moose.element('/model/kinetics') stoich.ksolve = ksolve #ksolve.stoich = stoich stoich.path = "/model/kinetics/##" state = moose.SteadyState( '/model/kinetics/state' ) #### Set clocks here moose.useClock(4, "/model/kinetics/##[]", "process") moose.setClock(4, float(simdt)) moose.setClock(5, float(simdt)) moose.useClock(5, '/model/kinetics/ksolve', 'process' ) moose.useClock(8, '/model/graphs/#', 'process' ) moose.setClock(8, float(plotDt)) moose.reinit() state.stoich = stoich state.showMatrices() state.convergenceCriterion = 1e-8 return ksolve, state
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 simulate(runTime, dt): """ Simulate the cable """ moose.reinit() setupSolver(hsolveDt=dt) moose.start(runTime)
def main(): """ This example builds a dose-response of a bistable model of a chemical system. It uses the kinetic solver *Ksolve* and the steady-state finder *SteadyState*. The model is set up within the script. The basic approach is to increment the control variable, **a** in this case, while monitoring **b**. The algorithm marches through a series of values of the buffered pool **a** and measures resultant values of pool **b**. At each cycle the algorithm calls the steady-state finder. Since **a** is incremented only a small amount on each step, each new steady state is (usually) quite close to the previous one. The exception is when there is a state transition. Here we plot three dose-response curves to illustrate the bistable nature of the system. On the upward going curve in blue, **a** starts low. Here, **b** follows the low arm of the curve and then jumps up to the high value at roughly *log( [a] ) = -0.55*. On the downward going curve in green, **b** follows the high arm of the curve forming a nice hysteretic loop. Eventually **b** has to fall to the low state at about *log( [a] ) = -0.83* Through nasty concentration manipulations, we find the third arm of the curve, which tracks the unstable fixed point. This is in red. We find this arm by setting an initial point close to the unstable fixed point, which the steady-state finder duly locates. We then follow a dose-response curve as with the other arms of the curve. Note that the steady-state solver doesn't always succeed in finding a good solution, despite moving only in small steps. Nevertheless the resultant curves are smooth because it gives up pretty close to the correct value, simply because the successive points are close together. Overall, the system is pretty robust despite the core root-finder computations in GSL being temperamental. In doing a production dose-response series you may wish to sample concentration space logarithmically rather than linearly. """ compartment = makeModel() ksolve = moose.Ksolve( '/model/compartment/ksolve' ) stoich = moose.Stoich( '/model/compartment/stoich' ) stoich.compartment = compartment stoich.ksolve = ksolve stoich.path = "/model/compartment/##" state = moose.SteadyState( '/model/compartment/state' ) moose.reinit() state.stoich = stoich state.convergenceCriterion = 1e-6 moose.seed( 111 ) # Used when generating the samples in state space b = moose.element( '/model/compartment/b' ) a = moose.element( '/model/compartment/a' ) c = moose.element( '/model/compartment/c' ) a.concInit = 0.1 deltaA = 0.002 num = 150 avec = [] bvec = [] moose.reinit() # Now go up. for i in range( 0, num ): moose.start( 1.0 ) # Run the model for 1 seconds. state.settle() # This function finds the steady states. avec.append( a.conc ) bvec.append( b.conc ) a.concInit += deltaA #print i, a.conc, b.conc pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a up' ) # Now go down. avec = [] bvec = [] for i in range( 0, num ): moose.start( 1.0 ) # Run the model for 1 seconds. state.settle() # This function finds the steady states. avec.append( a.conc ) bvec.append( b.conc ) a.concInit -= deltaA #print i, a.conc, b.conc pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a down' ) # Now aim for the middle. We do this by judiciously choosing a # start point that should be closer to the unstable fixed point. avec = [] bvec = [] a.concInit = 0.28 b.conc = 0.15 for i in range( 0, 65 ): moose.start( 1.0 ) # Run the model for 1 seconds. state.settle() # This function finds the steady states. avec.append( a.conc ) bvec.append( b.conc ) a.concInit -= deltaA #print i, a.conc, b.conc pylab.plot( numpy.log10( avec ), numpy.log10( bvec ), label='b vs a mid' ) pylab.ylim( [-1.7, 1.2] ) pylab.legend() pylab.show()
def do_sim(pulsegen, amp): pulsegen.level[0] = amp pulsegen.delay[0] = 50e-3 pulsegen.width[0] = 400e-3 moose.reinit() utils.stepRun(simtime, 10000 * simdt, logger=config.logger)
def main(): """ This example illustrates loading, running, and saving a kinetic model defined in kkit format. It uses a default kkit model but you can specify another using the command line ``python loadKineticModel.py filepath runtime solver``. We use default solver as gsl. The model already defines a couple of plots and sets the runtime 20 secs. """ defaultsolver = "gsl" # Pick any of gsl, gssa, ee.. defaultfile = '../genesis/kkit_objects_example.g' defaultruntime = 20.0 try: sys.argv[1] except IndexError: filepath = defaultfile else: filepath = sys.argv[1] if not os.path.exists(filepath): print ("Filename or path does not exist \"%s\" loading default file \"%s\" " %(filepath ,defaultfile)) filepath = defaultfile try: sys.argv[2] except : runtime = defaultruntime else: runtime = float(sys.argv[2]) try: sys.argv[3] except : solver = defaultsolver else: solver = sys.argv[3] modelId = moose.loadModel( filepath, 'model', solver ) # Increase volume so that the stochastic solver gssa # gives an interesting output #compt = moose.element( '/model/kinetics' ) #compt.volume = 1e-19 moose.reinit() moose.start( runtime ) # Report parameters ''' for x in moose.wildcardFind( '/model/kinetics/##[ISA=PoolBase]' ): print x.name, x.nInit, x.concInit for x in moose.wildcardFind( '/model/kinetics/##[ISA=ReacBase]' ): print x.name, 'num: (', x.numKf, ', ', x.numKb, '), conc: (', x.Kf, ', ', x.Kb, ')' for x in moose.wildcardFind('/model/kinetics/##[ISA=EnzBase]'): print x.name, '(', x.Km, ', ', x.numKm, ', ', x.kcat, ')' ''' # Display all plots. for x in moose.wildcardFind( '/model/#graphs/conc#/#' ): t = numpy.arange( 0, x.vector.size, 1 ) * x.dt pylab.plot( t, x.vector, label=x.name ) pylab.legend() pylab.show() quit()
def main(): """ This illustrates the use of rdesigneur to build a simple dendrite with spines, and then to resize them using spine fields. These are the fields that would be changed dynamically in a simulation with reactions that affect spine geometry. """ makeModel() elec = moose.element('/model/elec') elec.setSpineAndPsdMesh(moose.element('/model/chem/spine'), moose.element('/model/chem/psd')) caDend = moose.vec('/model/chem/dend/Ca') caHead = moose.vec('/model/chem/spine/Ca') caPsd = moose.vec('/model/chem/psd/Ca') eHead = moose.wildcardFind('/model/elec/#head#') graphs = moose.Neutral('/graphs') psdTab = moose.Table2('/graphs/psdTab', len(caPsd)).vec headTab = moose.Table2('/graphs/headTab', len(caHead)).vec dendTab = moose.Table2('/graphs/dendTab', len(caDend)).vec eTab = moose.Table('/graphs/eTab', len(eHead)).vec stimtab = moose.StimulusTable('/stim') stimtab.stopTime = 0.3 stimtab.loopTime = 0.3 stimtab.doLoop = True stimtab.vector = [ 1.0 + numpy.sin(x) for x in numpy.arange(0, 2 * PI, PI / 1000) ] estimtab = moose.StimulusTable('/estim') estimtab.stopTime = 0.001 estimtab.loopTime = 0.001 estimtab.doLoop = True estimtab.vector = [ 1e-9 * numpy.sin(x) for x in numpy.arange(0, 2 * PI, PI / 1000) ] for i in range(len(caPsd)): moose.connect(psdTab[i], 'requestOut', caPsd[i], 'getConc') for i in range(len(caHead)): moose.connect(headTab[i], 'requestOut', caHead[i], 'getConc') for i in range(len(caDend)): moose.connect(dendTab[i], 'requestOut', caDend[i], 'getConc') for i in range(len(eHead)): moose.connect(eTab[i], 'requestOut', eHead[i], 'getVm') moose.connect(stimtab, 'output', caDend, 'setConc', 'OneToAll') dend = moose.element('/model/elec/dend') moose.connect(estimtab, 'output', dend, 'setInject') moose.reinit() moose.start(1) head0 = moose.element('/model/elec/head0') shaft1 = moose.element('/model/elec/shaft1') head2 = moose.element('/model/elec/head2') # Here we scale the spine head length while keeping all vols constt. print("Spine 0: longer head, same vol\nSpine 1: longer shaft") print("Spine 2: Bigger head, same diffScale\n") elecParms = [(i.Rm, i.Cm, i.Ra) for i in (head0, shaft1, head2)] chemParms = [ i.volume for i in (caHead[0], caPsd[0], caHead[1], caPsd[1], caHead[2], caPsd[2]) ] elec.spine[0].headLength *= 4 # 4x length elec.spine[0].headDiameter *= 0.5 # 1/2 x dia # Here we scale the shaft length. Vols are not touched. elec.spine[1].shaftLength *= 2 # 2 x length #Here we scale the spine head vol while retaining diffScale = xArea/len # This gives 4x vol. hdia = elec.spine[2].headDiameter sdsolve = moose.element('/model/chem/spine/dsolve') elec.spine[2].headLength *= 2 # 2x length elec.spine[2].headDiameter *= numpy.sqrt(2) # sqrt(2) x dia hdia = elec.spine[2].headDiameter print("Checking scaling assertions: ") assertEq(elecParms[0][0] * 0.5, head0.Rm) assertEq(elecParms[0][1] * 2, head0.Cm) assertEq(elecParms[0][2] * 16, head0.Ra) assertEq(chemParms[0], caHead[0].volume) assertEq(chemParms[1] * 0.25, caPsd[0].volume) assertEq(elecParms[1][0] * 0.5, shaft1.Rm) assertEq(elecParms[1][1] * 2, shaft1.Cm) assertEq(elecParms[1][2] * 2, shaft1.Ra) assertEq(chemParms[2], caHead[1].volume) assertEq(chemParms[3], caPsd[1].volume) ratio = 2 * numpy.sqrt(2) assertEq(elecParms[2][0] / ratio, head2.Rm) assertEq(elecParms[2][1] * ratio, head2.Cm) assertEq(elecParms[2][2], head2.Ra) assertEq(chemParms[4] * 4, caHead[2].volume) assertEq(chemParms[5] * 2, caPsd[2].volume) print("\nAll assertions cleared") moose.start(2) for i in range(len(psdTab)): pylab.plot(psdTab[i].vector, label='PSD' + str(i)) pylab.legend() pylab.figure() for i in range(len(headTab)): pylab.plot(headTab[i].vector, label='head' + str(i)) pylab.legend() pylab.figure() for i in range(len(dendTab)): pylab.plot(dendTab[i].vector, label='dendCa' + str(i)) pylab.legend() pylab.figure() for i in range(len(eTab)): pylab.plot(eTab[i].vector, label='headVm' + str(i)) #print i, len( eTab[i].vector ), eTab[i].vector pylab.legend() pylab.show() app = QtGui.QApplication(sys.argv) #widget = mv.MoogliViewer( '/model' ) morphology = moogli.read_morphology_from_moose(name="", path='/model/elec') widget = moogli.MorphologyViewerWidget(morphology) widget.show() return app.exec_() quit()
def test_diffshell(): lib = moose.Neutral('/library') for tick in range(0, 7): moose.setClock(tick, dt) moose.setClock(8, 0.005) # set output clock model = moose.Neutral('/model') dend = moose.Compartment('/model/dend') pulse = moose.PulseGen('/model/pulse') data = moose.Neutral('/data') vmtab = moose.Table('/data/dend_Vm') gktab = moose.Table('/data/CaT_Gk') iktab = moose.Table('/data/CaT_Ik') dend.Cm = Cm dend.Rm = Rm dend.Em = Em dend.initVm = Vm_0 dend.diameter = dend_diameter dend.length = dend_length pulse.delay[0] = 8. pulse.width[0] = 500e-3 pulse.level[0] = inject pulse.delay[1] = 1e9 chan = chan_proto.chan_proto('/library/CaL12', param_chan.Cal) m = moose.connect(pulse, 'output', dend, 'injectMsg') moose.connect(vmtab, 'requestOut', dend, 'getVm') chan = addOneChan('CaL12', gbar, dend) moose.connect(gktab, 'requestOut', chan, 'getGk') moose.connect(iktab, 'requestOut', chan, 'getIk') diftab = [] buftab = [] difs, difb = add_difshells_and_buffers(dend, difshell_no, difbuff_no) if pumps: pump = moose.MMPump('/model/dend/pump') pump.Vmax = kcat pump.Kd = km moose.connect(pump, "PumpOut", difs[0], "mmPump") if difs: moose.connect(chan, "IkOut", difs[0], "influx") moose.connect(difs[0], 'concentrationOut', chan, 'concen') for i, dif in enumerate(difs): res_dif = moose.Table('/data/' + difshell_name + str(i)) diftab.append(res_dif) moose.connect(diftab[i], 'requestOut', dif, 'getC') if (difbuff_no): buftab.append([]) for j, buf in enumerate(difb[i]): 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): header += ' difshell_' + str(i) res[:, 4 + i * (difbuff_no + 1)] = diftab[i].vector if (difbuff_no): for j, buf in enumerate(buftab[i]): res[:, 4 + i * (difbuff_no + 1) + j + 1] = buf.vector header += ' difshell_' + str(i) + '_difbuff_' + str(j) np.savetxt(fname, res, header=header, comments='')
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) plotlist = makePlots() for t in numpy.arange(0, runtime, plotdt): moose.start(plotdt) updatePlots(plotlist, t) # save the final result to a file. outfile = '%s.png' % sys.argv[0] plt.savefig(outfile) print(('[INFO] Saved results to %s' % outfile)) 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 ' msg += 'a=%f b=%f, c=%f, d=%f' % (atot2 / atot, btot2 / btot, ctot2 / ctot, dtot2 / dtot) print(msg) print( ('Initial to final (b+c)=%f' % (float(btot2 + ctot2) / (btot + ctot)))) quit()
def main(): """ The funcReacLotkaVolterra example shows how to use function objects as part of differential equation systems in the framework of the MOOSE kinetic solvers. Here the system is set up explicitly using the scripting, in normal use one would expect to use SBML. In this example we set up a Lotka-Volterra system. The equations are readily expressed as a pair of reactions each of whose rate is governed by a function:: x' = x( alpha - beta.y ) y' = -y( gamma - delta.x ) This translates into two reactions:: x ---> z Kf = beta.y - alpha y ---> z Kf = gamma - delta.x Here z is a dummy molecule whose concentration is buffered to zero. The model first runs using default Exponential Euler integration. This is not particularly accurate even with a small timestep. The model is then converted to use the deterministic Kinetic solver Ksolve. This is accurate and faster. Note that we cannot use the stochastic GSSA solver for this system, it cannot handle a reaction term whose rate keeps changing. """ makeModel() for i in range(11, 18): moose.setClock(i, 0.001) moose.setClock(18, 0.1) moose.reinit() moose.start(runtime) # Run the model # Iterate through all plots, dump their contents to data.plot. for x in moose.wildcardFind('/model/graphs/#'): #x.xplot( 'scriptKineticModel.plot', x.name ) t = numpy.arange(0, x.vector.size, 1) * x.dt # sec pylab.plot(t, x.vector, label=x.name) pylab.ylim(0, 2.5) pylab.title("Exponential Euler solution. Note slight error buildup") pylab.legend() pylab.figure() compt = moose.element('/model/lotka') ksolve = moose.Ksolve('/model/lotka/ksolve') stoich = moose.Stoich('/model/lotka/stoich') stoich.compartment = compt stoich.ksolve = ksolve stoich.path = '/model/lotka/##' moose.reinit() moose.start(runtime) # Run the model for i in range(11, 18): moose.setClock(i, 0.1) for x in moose.wildcardFind('/model/graphs/#'): t = numpy.arange(0, x.vector.size, 1) * x.dt # sec pylab.plot(t, x.vector, label=x.name) pylab.ylim(0, 2.5) pylab.title("Runge-Kutta solution.") pylab.legend() pylab.show() quit()
def main(): """ This example illustrates how to run a model at different volumes. The key line is just to set the volume of the compartment:: compt.volume = vol If everything else is set up correctly, then this change propagates through to all reactions molecules. For a deterministic reaction one would not see any change in output concentrations. For a stochastic reaction illustrated here, one sees the level of 'noise' changing, even though the concentrations are similar up to a point. This example creates a bistable model having two enzymes and a reaction. One of the enzymes is autocatalytic. This model is set up within the script rather than using an external file. The model is set up to run using the GSSA (Gillespie Stocahstic systems algorithim) method in MOOSE. To run the example, run the script ``python scaleVolumes.py`` and hit ``enter`` every cycle to see the outcome of stochastic calculations at ever smaller volumes, keeping concentrations the same. """ makeModel() moose.seed(11111) gsolve = moose.Gsolve('/model/compartment/gsolve') stoich = moose.Stoich('/model/compartment/stoich') compt = moose.element('/model/compartment') stoich.compartment = compt stoich.ksolve = gsolve stoich.path = "/model/compartment/##" #moose.setClock( 5, 1.0 ) # clock for the solver #moose.useClock( 5, '/model/compartment/gsolve', 'process' ) a = moose.element('/model/compartment/a') for vol in (1e-19, 1e-20, 1e-21, 3e-22, 1e-22, 3e-23, 1e-23): # Set the volume compt.volume = vol print(('vol = ', vol, ', a.concInit = ', a.concInit, ', a.nInit = ', a.nInit)) moose.reinit() moose.start(100.0) # Run the model for 100 seconds. a = moose.element('/model/compartment/a') b = moose.element('/model/compartment/b') # move most molecules over to b b.conc = b.conc + a.conc * 0.9 a.conc = a.conc * 0.1 moose.start(100.0) # Run the model for 100 seconds. # move most molecules back to a a.conc = a.conc + b.conc * 0.99 b.conc = b.conc * 0.01 moose.start(100.0) # Run the model for 100 seconds. # Iterate through all plots, dump their contents to data.plot. displayPlots() pylab.show(block=False) print('vol = %f ' % vol) response = input("Press enter to go to next plot... ") quit()
def make_network(): """ This snippet sets up a recurrent network of IntFire objects, using SimpleSynHandlers to deal with spiking events. It isn't very satisfactory as activity runs down after a while. It is a good example for using the IntFire, setting up random connectivity, and using SynHandlers. """ global all_done_ done = mp.Value('i', 0) q = mp.Queue() th = mp.Process(target=streamer_handler, args=(done, q)) th.start() size = 1024 dt = 0.2 runsteps = 10 delayMin = 0 delayMax = 4 weightMax = 1 Vmax = 1.0 thresh = 0.4 refractoryPeriod = 0.4 tau = 0.5 connectionProbability = 0.01 random.seed(123) np.random.seed(456) t0 = time.time() network = moose.IntFire('network', size) syns = moose.SimpleSynHandler('/network/syns', size) moose.connect(syns, 'activationOut', network, 'activation', 'OneToOne') moose.le('/network') syns.vec.numSynapses = [1] * size sv = moose.vec('/network/syns/synapse') print('before connect t = %.3f' % (time.time() - t0)) mid = moose.connect(network, 'spikeOut', sv, 'addSpike', 'Sparse') print('after connect t = %.3f' % (time.time() - t0)) #print mid.destFields m2 = moose.element(mid) m2.setRandomConnectivity(connectionProbability, 5489) print('after setting connectivity, t=%.3f' % (time.time() - t0)) #network.vec.Vm = [(Vmax*random.random()) for r in range(size)] network.vec.Vm = np.random.rand(size) * Vmax network.vec.thresh = thresh network.vec.refractoryPeriod = refractoryPeriod network.vec.tau = tau numSynVec = syns.vec.numSynapses print('Middle of setup, t = %.3f' % (time.time() - t0)) numTotSyn = sum(numSynVec) print((numSynVec.size, ', tot = ', numTotSyn, ', numSynVec = ', numSynVec)) for item in syns.vec: h = moose.element(item) h.synapse.delay = delayMin + (delayMax - delayMin) * np.random.rand( len(h.synapse)) h.synapse.weight = np.random.rand(len(h.synapse)) * weightMax print('After setup, t = %.3f' % (time.time() - t0)) numStats = 100 stats = moose.SpikeStats('/stats', numStats) stats.vec.windowLength = 1 # timesteps to put together. plots = moose.Table('/plot', numStats) convergence = size // numStats for i in range(numStats): for j in range(size // numStats): k = i * convergence + j moose.connect(network.vec[k], 'spikeOut', stats.vec[i], 'addSpike') moose.connect(plots, 'requestOut', stats, 'getMean', 'OneToOne') t1 = time.time() moose.reinit() print('reinit time t = %.3f' % (time.time() - t1)) network.vec.Vm = np.random.rand(size) * Vmax print('setting Vm , t = %.3f' % (time.time() - t1)) t1 = time.time() moose.start(runsteps * dt, 1) time.sleep(0.1) done.value = 1 print('runtime, t = %.3f' % (time.time() - t1)) print(network.vec.Vm[99:103], network.vec.Vm[900:903]) res = q.get() for tabPath in res: aWithTime = res[tabPath] a = aWithTime[1::2] b = moose.element(tabPath).vector print(tabPath, len(a), len(b)) if len(a) == len(b): assert np.equal(a, b).all() else: print("Table did not equal size. The last table is allowed to " " have fewer entries.") th.join() print('All done')
def vclamp_demo(simtime=50.0, dt=1e-2): ## It is good practice to modularize test elements inside a ## container container = moose.Neutral('/vClampDemo') ## Create a compartment with properties of a squid giant axon comp = SquidAxon('/vClampDemo/axon') # Create and setup the voltage clamp object clamp = moose.VClamp('/vClampDemo/vclamp') ## The defaults should work fine # clamp.mode = 2 # clamp.tau = 10*dt # clamp.ti = dt # clamp.td = 0 # clamp.gain = comp.Cm / dt ## Setup command voltage time course command = moose.PulseGen('/vClampDemo/command') command.delay[0] = 10.0 command.width[0] = 20.0 command.level[0] = 50.0 command.delay[1] = 1e9 moose.connect(command, 'output', clamp, 'commandIn') ## Connect the Voltage Clamp to the compartemnt moose.connect(clamp, 'currentOut', comp, 'injectMsg') moose.connect(comp, 'VmOut', clamp, 'sensedIn') ## setup stimulus recroding - this is the command pulse stimtab = moose.Table('/vClampDemo/vclamp_command') moose.connect(stimtab, 'requestOut', command, 'getOutputValue') ## Set up Vm recording vmtab = moose.Table('/vClampDemo/vclamp_Vm') moose.connect(vmtab, 'requestOut', comp, 'getVm') ## setup command potential recording - this is the filtered input ## to PID controller commandtab = moose.Table('/vClampDemo/vclamp_filteredcommand') moose.connect(commandtab, 'requestOut', clamp, 'getCommand') ## setup current recording Imtab = moose.Table('/vClampDemo/vclamp_inject') moose.connect(Imtab, 'requestOut', clamp, 'getCurrent') # Scheduling moose.setClock(0, dt) moose.setClock(1, dt) moose.setClock(2, dt) moose.setClock(3, dt) moose.useClock(0, '%s/##[TYPE=Compartment]' % (container.path), 'init') moose.useClock(0, '%s/##[TYPE=PulseGen]' % (container.path), 'process') moose.useClock(1, '%s/##[TYPE=Compartment]' % (container.path), 'process') moose.useClock(2, '%s/##[TYPE=HHChannel]' % (container.path), 'process') moose.useClock(2, '%s/##[TYPE=VClamp]' % (container.path), 'process') moose.useClock(3, '%s/##[TYPE=Table]' % (container.path), 'process') moose.reinit() print(('RC filter in VClamp:: tau:', clamp.tau)) print(('PID controller in VClamp:: ti:', clamp.ti, 'td:', clamp.td, 'gain:', clamp.gain)) moose.start(simtime) print(('Finished simulation for %g seconds' % (simtime))) tseries = linspace(0, simtime, len(vmtab.vector)) subplot(211) title('Membrane potential and clamp voltage') plot(tseries, vmtab.vector, 'g-', label='Vm (mV)') plot(tseries, commandtab.vector, 'b-', label='Filtered command (mV)') plot(tseries, stimtab.vector, 'r-', label='Command (mV)') xlabel('Time (ms)') ylabel('Voltage (mV)') legend() # print len(commandtab.vector) subplot(212) title('Current through clamp circuit') # plot(tseries, stimtab.vector, label='stimulus (uA)') plot(tseries, Imtab.vector, label='injected current (uA)') xlabel('Time (ms)') ylabel('Current (uA)') legend() show()
def testNeuroMeshMultiscale(): elecDt = 50e-6 chemDt = 1e-1 plotDt = 1e-1 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, plotDt) moose.setClock(8, plotDt) 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( 6, '/model/chem/##[ISA=Adaptor]', 'process' ) moose.useClock(7, '/graphs/chem/#', 'process') moose.useClock(8, '/graphs/elec/#', 'process') moose.useClock(5, '/model/chem/#/dsolve', 'process') moose.useClock(6, '/model/chem/#/ksolve', '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 = 1e-9 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, len(x.vector), 1) 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, len(x.vector), 1) 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() ''' print 'All done'
def example(): """Function objects can be used to evaluate expressions with arbitrary number of variables and constants. We can assign expression of the form:: f(c0, c1, ..., cM, x0, x1, ..., xN, y0,..., yP ) where `c_i`'s are constants and `x_i`'s and `y_i`'s are variables. The constants must be defined before setting the expression and variables are connected via messages. The constants can have any name, but the variable names must be of the form x{i} or y{i} where i is increasing integer starting from 0. The `x_i`'s are field elements and you have to set their number first (function.x.num = N). Then you can connect any source field sending out double to the 'input' destination field of the `x[i]`. The `y_i`'s are useful when the required variable is a value field and is not available as a source field. In that case you connect the `requestOut` source field of the function element to the `get{Field}` destination field on the target element. The `y_i`'s are automatically added on connecting. Thus, if you call:: moose.connect(function, 'requestOut', a, 'getSomeField') moose.connect(function, 'requestOut', b, 'getSomeField') then ``a.someField`` will be assigned to ``y0`` and ``b.someField`` will be assigned to ``y1``. In this example we evaluate the expression: ``z = c0 * exp(c1 * x0) * cos(y0)`` with x0 ranging from -1 to +1 and y0 ranging from -pi to +pi. These values are stored in two stimulus tables called xtab and ytab respectively, so that at each timestep the next values of x0 and y0 are assigned to the function. Along with the value of the expression itself we also compute its derivative with respect to y0 and its derivative with respect to time (rate). The former uses a five-point stencil for the numerical differentiation and has a glitch at y=0. The latter uses backward difference divided by dt. Unlike Func class, the number of variables and constants are unlimited in Function and you can set all the variables via messages. """ demo = moose.Neutral('/model') function = moose.Function('/model/function') function.c['c0'] = 1.0 function.c['c1'] = 2.0 #function.x.num = 1 function.expr = 'c0 * exp(c1*x0) * cos(y0) + sin(t)' # mode 0 - evaluate function value, derivative and rate # mode 1 - just evaluate function value, # mode 2 - evaluate derivative, # mode 3 - evaluate rate function.mode = 0 function.independent = 'y0' nsteps = 1000 xarr = np.linspace(0.0, 1.0, nsteps) # Stimulus tables allow you to store sequences of numbers which # are delivered via the 'output' message at each time step. This # is a placeholder and in real scenario you will be using any # sourceFinfo that sends out a double value. input_x = moose.StimulusTable('/xtab') input_x.vector = xarr input_x.startTime = 0.0 input_x.stepPosition = xarr[0] input_x.stopTime = simtime moose.connect(input_x, 'output', function.x[0], 'input') yarr = np.linspace(-np.pi, np.pi, nsteps) input_y = moose.StimulusTable('/ytab') input_y.vector = yarr input_y.startTime = 0.0 input_y.stepPosition = yarr[0] input_y.stopTime = simtime moose.connect(function, 'requestOut', input_y, 'getOutputValue') # data recording result = moose.Table('/ztab') moose.connect(result, 'requestOut', function, 'getValue') derivative = moose.Table('/zprime') moose.connect(derivative, 'requestOut', function, 'getDerivative') rate = moose.Table('/dz_by_dt') moose.connect(rate, 'requestOut', function, 'getRate') x_rec = moose.Table('/xrec') moose.connect(x_rec, 'requestOut', input_x, 'getOutputValue') y_rec = moose.Table('/yrec') moose.connect(y_rec, 'requestOut', input_y, 'getOutputValue') dt = simtime / nsteps for ii in range(32): moose.setClock(ii, dt) moose.reinit() moose.start(simtime) # Uncomment the following lines and the import matplotlib.pyplot as plt on top # of this file to display the plot. plt.subplot(3, 1, 1) plt.plot(x_rec.vector, result.vector, 'r-', label='z = {}'.format(function.expr)) z = function.c['c0'] * np.exp( function.c['c1'] * xarr) * np.cos(yarr) + np.sin( np.arange(len(xarr)) * dt) plt.plot(xarr, z, 'b--', label='numpy computed') plt.xlabel('x') plt.ylabel('z') plt.legend() plt.subplot(3, 1, 2) plt.plot(y_rec.vector, derivative.vector, 'r-', label='dz/dy0') # derivatives computed by putting x values in the analytical formula dzdy = function.c['c0'] * np.exp(function.c['c1'] * xarr) * (-np.sin(yarr)) plt.plot(yarr, dzdy, 'b--', label='numpy computed') plt.xlabel('y') plt.ylabel('dz/dy') plt.legend() plt.subplot(3, 1, 3) # *** BEWARE *** The first two entries are spurious. Entry 0 is # *** from reinit sending out the defaults. Entry 2 is because # *** there is no lastValue for computing real forward difference. plt.plot(np.arange(2, len(rate.vector), 1) * dt, rate.vector[2:], 'r-', label='dz/dt') dzdt = np.diff(z) / dt plt.plot(np.arange(0, len(dzdt), 1.0) * dt, dzdt, 'b--', label='numpy computed') plt.xlabel('t') plt.ylabel('dz/dt') plt.legend() plt.tight_layout() plt.show()
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. """ global nsdf simtime = 100.0 dt = 1e-3 model = moose.Neutral('/model') pulse = moose.PulseGen('/model/pulse') pulse.level[0] = 1.0 pulse.delay[0] = 10 pulse.width[0] = 20 t_lead = moose.SpikeGen('/model/t_lead') t_lead.threshold = 0.5 moose.connect(pulse, 'output', t_lead, 'Vm') nsdf = moose.NSDFWriter('/model/writer') nsdf.filename = 'nsdf_demo.h5' nsdf.mode = 2 #overwrite existing file nsdf.flushLimit = 100 moose.connect(nsdf, 'requestOut', pulse, 'getOutputValue') print('event input', nsdf.eventInput, nsdf.eventInput.num) print(nsdf) nsdf.eventInput.num = 1 ei = nsdf.eventInput[0] print(ei.path) moose.connect(t_lead, 'spikeOut', nsdf.eventInput[0], 'input') tab = moose.Table('spiketab') tab.threshold = t_lead.threshold clock = moose.element('/clock') for ii in range(32): moose.setClock(ii, dt) moose.connect(pulse, 'output', tab, 'spike') print(datetime.now().isoformat()) moose.reinit() moose.start(simtime) print(datetime.now().isoformat()) np.savetxt('nsdf.txt', tab.vector) ################################### # Set the environment attributes ################################### nsdf.stringAttr['title'] = 'NSDF writing demo for moose' nsdf.stringAttr[ 'description'] = '''An example of writing data to NSDF file from MOOSE simulation. In this simulation we generate square pules from a PulseGen object and use a SpikeGen to detect the threshold crossing events of rising edges. We store the pulsegen output as Uniform data and the threshold crossing times as Event data. ''' nsdf.stringAttr['creator'] = getpass.getuser() nsdf.stringVecAttr['software'] = ['python2.7', 'moose3'] nsdf.stringVecAttr['method'] = [''] nsdf.stringAttr['rights'] = '' nsdf.stringAttr['license'] = 'CC-BY-NC' # Specify units. MOOSE is unit agnostic, so we explicitly set the # unit attibutes on individual datasets nsdf.stringAttr['/data/uniform/PulseGen/outputValue/tunit'] = 's' nsdf.stringAttr['/data/uniform/PulseGen/outputValue/unit'] = 'A' eventDataPath = '/data/event/SpikeGen/spikeOut/{}_{}_{}/unit'.format( t_lead.vec.value, t_lead.getDataIndex(), t_lead.fieldIndex) nsdf.stringAttr[eventDataPath] = 's'
########################################################################## # This illustrates some of the capabilities for spine placement. # It has spines whose size increase with distance from the soma. # Further, the angular direction of the spines spirals around the dendrite. ########################################################################## import moose import rdesigneur as rd rdes = rd.rdesigneur( cellProto=[['ballAndStick', 'elec', 10e-6, 10e-6, 2e-6, 300e-6, 50]], spineProto=[['makePassiveSpine()', 'spine']], spineDistrib=[[ 'spine', '#dend#', '3e-6', '-1e-6', '1+p*2e4', '0', 'p*6.28e7', '0' ]], stimList=[['soma', '1', '.', 'inject', '(t>0.02) * 1e-9']], moogList=[['#', '1', '.', 'Vm', 'Soma potential']]) rdes.buildModel() moose.reinit() rdes.displayMoogli(0.0002, 0.025, 0.02)
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 of 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)
def simulateSelected(self): cellnames = [ str(c.text()) for c in self.cellListWidget.selectedItems() ] assert (len(cellnames) == 1) name = cellnames[0] params = self.createCell(name) # hsolve = moose.HSolve('%s/solver' % (params['cell'].path)) # hsolve.dt = simdt # hsolve.target = params['cell'].path mutils.setDefaultDt(elecdt=simdt, plotdt2=plotdt) mutils.assignDefaultTicks(modelRoot=params['modelRoot'], dataRoot=params['dataRoot'], solver='hsolve') delay = float(str(self.delayText.text())) * 1e-3 width = float(str(self.widthText.text())) * 1e-3 levelMin = float(str(self.ampMinText.text())) * 1e-12 levelMax = float(str(self.ampMaxText.text())) * 1e-12 levelStep = float(str(self.ampStepText.text())) * 1e-12 params['stimulus'].delay[0] = delay params['stimulus'].width[0] = width params['stimulus'].level[0] = levelMin simtime = float(str(self.simtimeEdit.text())) * 1e-3 tdlist = [] self.vmAxes.clear() self.vmAxes.set_title('membrane potential at soma') self.vmAxes.set_ylabel('mV') self.vmAxes.get_xaxis().set_visible(False) self.stimAxes.clear() self.stimAxes.set_title('current injected at soma') self.stimAxes.set_ylabel('pA') self.stimAxes.set_xlabel('ms') styles = ['-', '--', '-.', ':'] cnt = int((levelMax - levelMin) / levelStep) ii = 0 while params['stimulus'].level[0] < levelMax: tstart = datetime.now() moose.reinit() moose.start(simtime) tend = datetime.now() td = tend - tstart tdlist.append(td.days * 86400 + td.seconds + td.microseconds * 1e-6) ts = np.linspace(0, simtime, len(params['somaVm'].vector)) vm = params['somaVm'].vector stim = params['injectionCurrent'].vector alpha = 0.1 + 0.9 * params['stimulus'].level[0] / levelMax color = cmap(ii * 1.0 / cnt, cnt) self.vmAxes.plot(ts * 1e3, vm * 1e3, color=color, label='%g pA' % (params['stimulus'].level[0] * 1e12), alpha=0.8) self.stimAxes.plot(ts * 1e3, stim * 1e12, color=color, label='Current (pA)') self.plotCanvas.draw() params['stimulus'].level[0] += levelStep ii += 1 self.gs.tight_layout(self.plotFigure) self.vmAxes.legend() self.plotCanvas.draw() td = np.mean(tdlist) print('Simulating %g s took %g s of computer time' % (simtime, td))
def update(val): global Em global RM global CM global Ca_Basal global Ca_tau global Ca_B global Na_Gbar global K_DR_Gbar global K_A_Gbar global K_M_Gbar global h_Gbar global Ca_T_Gbar global Ca_R_Gbar global Ca_L_Gbar global Ca_N_Gbar global K_SK_Gbar global K_BK_Gbar Em = sliders_list[0].val RM = sliders_list[1].val CM = sliders_list[2].val Ca_Basal = sliders_list[3].val Ca_tau = sliders_list[4].val Ca_B = sliders_list[5].val Na_Gbar = sliders_list[6].val K_DR_Gbar = sliders_list[7].val K_A_Gbar = sliders_list[8].val K_M_Gbar = sliders_list[9].val h_Gbar = sliders_list[10].val Ca_T_Gbar = sliders_list[11].val Ca_R_Gbar = sliders_list[12].val Ca_L_Gbar = sliders_list[13].val Ca_N_Gbar = sliders_list[14].val K_SK_Gbar = sliders_list[15].val K_BK_Gbar = sliders_list[16].val try: # [moose.delete(x) for x in ['/model', '/library']] [moose.delete(x) for x in ['/model']] except: pass rdes = makeModel() text_trap = io.StringIO() # JUst to suppress the inbuilt terminal output sys.stdout = text_trap # JUst to suppress the inbuilt terminal output rdes.buildModel() sys.stdout = sys.__stdout__ # restoring terminal output try: moose.element( '/model/elec/soma/vclamp' ).gain = CM*sm_area/elecPlotDt moose.element( '/model/elec/soma/vclamp' ).tau = 5*elecPlotDt moose.element( '/model/elec/soma/vclamp' ).ti = elecPlotDt moose.element( '/model/elec/soma/vclamp' ).td = 0 except: pass moose.element('/model/elec/soma/Ca_conc').CaBasal = Ca_Basal moose.element('/model/elec/soma/Ca_conc').tau = Ca_tau moose.element('/model/elec/soma/Ca_conc').B = Ca_B moose.reinit() moose.start( runtime ) Vtrace = moose.element('/model/graphs/plot0' ).vector v = np.array(Vtrace) parameters() print('###############################################') l.set_ydata(v) fig.canvas.draw_idle()
def test_ksolver_parallel(nthreads=4): """ 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 as a hybrid of a reaction and a function which sets its rates. Please see rxdFuncDiffusion.py for a variant that uses just a function object to set up the system. """ dt = 0.1 # define the geometry compt = moose.CylMesh('/cylinder') compt.r0 = compt.r1 = 1 # compt.diffLength = 1e-6 compt.x1 = 1e-2 assert compt.numDiffCompts == int( compt.x1 / compt.diffLength), (compt.numDiffCompts, compt.x1 / compt.diffLength) print('No of compartment %d' % compt.numDiffCompts) #define the molecule. Its geometry is defined by its parent volume, cylinder c = moose.Pool('/cylinder/pool') c.diffConst = 1 # define diffusion constant # There is an implicit reaction substrate/product. MOOSE makes it explicit. buf = moose.BufPool('/cylinder/buf') buf.nInit = 1 # The reaction is something entirely peculiar, not a chemical thing. reaction = moose.Reac('/cylinder/reac') reaction.Kb = 0 # so here we set up a function calculation to do the same thing. func = moose.Function('/cylinder/reac/func') func.expr = "(1 - x0) * (0.3 - x0)" func.x.num = 1 #specify number of input variables. #Connect the reaction to the pools moose.connect(reaction, 'sub', c, 'reac') moose.connect(reaction, 'prd', buf, 'reac') #Connect the function to the reaction moose.connect(func, 'valueOut', reaction, 'setNumKf') #Connect the molecules to the func moose.connect(c, 'nOut', func.x[0], 'input') #Set up solvers ksolve = moose.Ksolve('/cylinder/ksolve') ksolve.numThreads = nthreads dsolve = moose.Dsolve('/cylinder/dsolve') stoich = moose.Stoich('/cylinder/stoich') stoich.compartment = compt stoich.ksolve = ksolve stoich.dsolve = dsolve stoich.reacSystemPath = '/cylinder/##' assert stoich.reacSystemPath == '/cylinder/##' for i in range(10, 18): moose.setClock(i, dt) #initialize x = np.arange(0, compt.x1, compt.diffLength) assert len(c.vec) == 10000, len(c.vec) nInit = [(float(q < 0.2) * compt.x1) for q in x] c.vec.nInit = nInit assert np.allclose(c.vec.nInit, nInit), (c.vec.nInit, nInit) expected = [(0.01, 0.0), (2.6704795776286974e-07, 1.2678976830753021e-17), (8.167639617309419e-14, 3.8777269301457245e-24), (2.498062905267963e-20, 1.1860363878961374e-30), (7.64029581501609e-27, 3.6273808003690943e-37)] # Run and plot it. moose.reinit() updateDt = 50 runtime = updateDt * 4 yvec = c.vec.n u1, m1 = np.mean(yvec), np.std(yvec) print(u1, m1) assert np.isclose((u1, m1), expected[0], atol=1e-5).all(), ((u1, m1), expected[0]) t1 = time.time() for i, t in enumerate(range(0, runtime - 1, updateDt)): moose.start(updateDt) yvec = c.vec.n u1, m1 = np.mean(yvec), np.std(yvec) print(u1, m1) np.isclose((u1, m1), expected[i + 1], atol=1e-5).all(), expected[i + 1] return time.time() - t1
def input_output(): """ The PyRun class can take a double input through `trigger` field. Whenever another object sends an input to this field, the `runString` is executed. The fun part of this is that you can use the input value in your python statements in `runString`. This is stored in a local variable called `input_`. You can rename this by setting `inputVar` field. Things become even more interesting when you can send out a value computed using Python. PyRun objects allow you to define a local variable called `output` and whatever value you assign to this, will be sent out through the source field `output` on successful execution of the `runString`. You can rename the output variable by setting `outputVar` field. In this example, we send the output of a pulsegen object sending out the values 1, 2, 3 during each pulse and compute the square of these numbers in Python and set output to this square. The calculated value is assigned to the `output` variable and in turn sent out to a Table object's input and gets recorded. By default PyRun executes the `runString` whenever a `trigger` message is received and when its process method is called at each timestep. In both cases it sends out the `output` value. Since this may cause inaccuracies depending on what the Python statements in `runString` do, a `mode` can be specified to disable one of the above. We set ``mode = 2`` to disable the `process` method. Note that this could also have been done by setting its ``tick = -1``. ``mode = 1`` will disable `trigger` message and ``mode = 0``, the default, enables both. """ model = moose.Neutral('/model') input_pulse = moose.PulseGen('/model/pulse') #: set the baseline output 0 input_pulse.baseLevel = 0.0 #: We make it generate three pulses input_pulse.count = 3 input_pulse.level[0] = 1.0 input_pulse.level[1] = 2.0 input_pulse.level[2] = 3.0 #: Each pulse will appear 1 s after the previous one input_pulse.delay[0] = 1.0 input_pulse.delay[1] = 1.0 input_pulse.delay[2] = 1.0 #: Each pulse is 1 s wide input_pulse.width[0] = 1.0 input_pulse.width[1] = 1.0 input_pulse.width[2] = 1.0 #: Now create the PyRun object pyrun = moose.PyRun('/model/pyrun') pyrun.runString = """ output = input_ * input_ print 'input =', input_ print 'output =', output """ pyrun.mode = 2 # do not run process method moose.connect(input_pulse, 'output', pyrun, 'trigger') output_table = moose.Table('/model/output') moose.connect(pyrun, 'output', output_table, 'input') input_table = moose.Table('/model/input') moose.connect(input_pulse, 'output', input_table, 'input') moose.setClock(0, 0.25) moose.setClock(1, 0.25) moose.setClock(2, 0.25) moose.useClock(0, input_pulse.path, 'process') #: this is unnecessary because the mode=2 ensures that `process` #: does nothing moose.useClock(1, pyrun.path, 'process') moose.useClock(2, '/model/#[ISA=Table]', 'process') moose.reinit() moose.start(10.0) #ts = plt.plot(input_table.vector, label='input') plt.plot(output_table.vector, label='output') plt.legend() plt.show()
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_files/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()
def plotwparms(parms): sm_area = parms[0] sm_vol = parms[1] Na_SGbar = parms[2] KDR_SGbar = parms[3] KA_SGbar = parms[4] KMGbar = parms[5] hGbar = parms[6] CaTGbar = parms[7] CaRGbar = parms[8] CaLGbar = parms[9] KSKGbar = parms[10] KBKGbar = parms[11] CaConc_B = 100000/2/F/0.05/18/sm_area #Derived model parameters sm_diam = 4*sm_vol/sm_area sm_len = sm_area**2/4/sm_vol/np.pi RM = np.maximum(1e-12,1/(1/(R_input*sm_area) - Na_SGbar*a1 - KDR_SGbar*a2 - hGbar*a3 - KA_SGbar*a4 - KMGbar*a5 - CaLGbar*a6 - CaTGbar*a7 - CaRGbar*a8 - KSKGbar*a9 - KBKGbar*a10)) Em = (E_rest/(R_input*sm_area) - Na_SGbar*ENa*a1 - KDR_SGbar*EKDR*a2 - hGbar*Eh*a3 - KA_SGbar*EK*a4 - KMGbar*EK*a5 - CaLGbar*ECa*a6 - CaTGbar*ECa*a7 - CaRGbar*ECa*a8 - KSKGbar*EK*a9 - KBKGbar*EK*a10)/(1/(R_input*sm_area) - Na_SGbar*a1 - KDR_SGbar*a2 - hGbar*a3 - KA_SGbar*a4 - KMGbar*a5 - CaLGbar*a6 - CaTGbar*a7 - CaRGbar*a8 - KSKGbar*a9 - KBKGbar*a10) #ChannelProtos file ChP = 'Optimization/Custom/Real/ChannelProtos_Combe2018' for q in [0,1,2]: #Deleting any previous run of the model try: # [moose.delete(x) for x in ['/model', '/library']] [moose.delete(x) for x in ['/model']] except: pass if q == 0: inp_curr = 25e-12 elif q == 1: inp_curr = 150e-12 elif q == 2: inp_curr = 300e-12 rdes = rd.rdesigneur( elecDt = 10e-6, elecPlotDt = 50e-6, cellProto = [['somaProto', 'soma', sm_diam, sm_len]], chanProto = [ [ChP+'.Na_SChan()', 'Na_Schan'], [ChP+'.KDR_SChan()', 'KDR_Schan'], [ChP+'.KA_SChan()', 'KA_Schan'], [ChP+'.KM_Chan()', 'KM_chan'], [ChP+'.h_Chan()', 'h_chan'], [ChP+'.CaT_Chan()', 'CaT_chan'], [ChP+'.CaR_SChan()', 'CaR_Schan'], [ChP+'.CaL_SChan()', 'CaL_Schan'], [ChP+'.KSK_Chan()', 'KSK_chan'], [ChP+'.KBK_Chan()', 'KBK_chan'], [ChP+'.Ca_Conc()', 'Ca_conc'], ], passiveDistrib = [ ['soma', 'RM', str(RM), 'RA', '1.5', 'Cm', str(Cm), 'initVm', str(E_rest), 'Em', str(Em)], ], chanDistrib = [ ['Na_Schan', 'soma', 'Gbar', str(Na_SGbar)], ['KDR_Schan', 'soma', 'Gbar', str(KDR_SGbar)], ['KA_Schan', 'soma', 'Gbar', str(KA_SGbar)], ['KM_chan', 'soma', 'Gbar', str(KMGbar)], ['h_chan', 'soma', 'Gbar', str(hGbar)], ['CaT_chan', 'soma', 'Gbar', str(CaTGbar)], ['CaR_Schan', 'soma', 'Gbar', str(CaRGbar)], ['CaL_Schan', 'soma', 'Gbar', str(CaLGbar)], ['KBK_chan', 'soma', 'Gbar', str(KBKGbar)], ['KSK_chan', 'soma', 'Gbar', str(KSKGbar)], ['Ca_conc', 'soma', 'thick', '177.9e-6'], ], stimList = [ ['soma', '1', '.', 'inject', f'(t>=3.0813 && t<=3.5813) ? {inp_curr} : 0'], ], plotList = [ ['soma', '1', '.', 'Vm', 'Soma Membrane potential'], ], ) rdes.buildModel() moose.element('/model/elec/soma/Ca_conc').B = CaConc_B moose.element('/model/elec/soma/Ca_conc').tau = CaConc_tau moose.reinit() moose.start( 4 ) outputV_trace = moose.element('/model/graphs/plot0').vector outputV_trace = outputV_trace[60000:75000] if q == 0: output25pA = outputV_trace elif q == 1: output150pA = outputV_trace elif q == 2: output300pA = outputV_trace return [output25pA, output150pA, output300pA]
def main(): global num num = 100 runtime = 100 makeModel() dsolve = moose.element('/model/dsolve') moose.reinit() #moose.start( runtime ) # Run the model for 10 seconds. m = moose.element('/model/compartment/m') rec1 = moose.element('/model/compartment/rec1') rec2 = moose.element('/model/compartment/rec2') rec2m = moose.element('/model/compartment/rec2m') rec21 = moose.element('/model/compartment/rec21') halfWidth = [] timeArr = [] maxFWHH = [] r1 = moose.element('/model/compartment/r1') r2 = moose.element('/model/compartment/r2') r3 = moose.element('/model/compartment/r3') r4 = moose.element('/model/compartment/r4') trialNum = str(m.diffConst) + 'bind' + str(r1.Kf) + 'unbind' + str( r1.Kb) + 'dissoc' + str(r3.Kf) + 'assoc' + str(r3.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, m.vec.conc.size, 1) timeLabel = plt.text(60, 0.4, 'time = 0') line1, = ax.plot(pos, m.vec.conc, label='m') line2, = ax.plot(pos, rec1.vec.conc, label='rec1', linewidth=2) line3, = ax.plot(pos, rec2.vec.conc, label='rec2') line4, = ax.plot(pos, rec2m.vec.conc, label='rec2m') line5, = ax.plot(pos, rec21.vec.conc, label='rec21') plt.legend() fig.canvas.draw() for t in range(0, runtime): moose.start(0.5) aList = m.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(m.vec.conc) line2.set_ydata(rec1.vec.conc) line3.set_ydata(rec2.vec.conc) line4.set_ydata(rec2m.vec.conc) line5.set_ydata(rec21.vec.conc) timeLabel.set_text("time = %d" % t) fig.canvas.draw() maxFWHH.append(max(halfWidth)) print 'max FWHH is', max(halfWidth) fileName = 'data.xml' writeXML(timeArr, halfWidth, maxFWHH, trialNum, fileName)
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') A.diffConst = 0.005 B.diffConst = 0.25 # 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) storeAvec = [] for t in range(0, 500, 100): #if t>900 and t<1100: # print 'before loop',moose.element('/model/chem/dend/A').vec[5].n # for i in range(0,savec-1,1): # moose.element('/model/chem/dend/A').vec[i].n +=2*randper[i] #print 2*randper[5] #print 'in second loop' #print 'after loop',moose.element('/model/chem/dend/A').vec[5].n moose.start(100) print 'in loop', t avec = moose.vec('/model/chem/dend/A').n storeAvec.append(avec) #print storeAvec plt.plot(avec) avec = moose.vec('/model/chem/dend/A').n bvec = moose.vec('/model/chem/dend/B').n #rdes.displayMoogli(0.00005, 0.05, 0.0) #plt.plot(bvec) target = open('mod.txt', 'w') for item in storeAvec[3]: print >> target, item return bvec, avec, storeAvec
def test_func(): """This function creates a Func object evaluating a function of a single variable. It both shows direct evaluation without running a simulation and a case where the x variable comes from another source. """ model = moose.Neutral('/model') data = moose.Neutral('/data') func_1 = moose.Func('%s/func_1' % (model.path)) func_1.mode = 3 # mode = 1 : value, mode = 2 : derivative # Expression is that for tau_m in Traub's NaF channel model func_1.expr = 'x < -30e-3? 1.0e-3 * (0.025 + 0.14 * exp((x + 30.0e-3) / 10.0e-3)): 1.0e-3 * (0.02 + 0.145 * exp(( - x - 30.0e-3) / 10.0e-3))' # First we display the use of Func as a standalone funculator xarr = np.linspace(-120e-3, 40e-3, 1000) values = [] deriv = [] for x in xarr: func_1.var['x'] = x values.append(func_1.value) deriv.append(func_1.derivative) pylab.plot(xarr, values, 'g-', label='f(no-sim)') pylab.plot(xarr, np.array(deriv) / 1000, 'k-.', label="1e-3 * f'(no-sim)") simdt = xarr[1] - xarr[0] input = moose.StimulusTable('%s/xtab' % (model.path)) input.vector = xarr input.startTime = 0.0 input.stepPosition = xarr[0] input.stopTime = xarr[-1] - xarr[0] print((input.startTime, input.stopTime)) moose.connect(input, 'output', func_1, 'xIn') x_tab = moose.Table('/data/xtab') moose.connect(x_tab, 'requestOut', input, 'getOutputValue') y_tab = moose.Table('%s/y' % (data.path)) moose.connect(y_tab, 'requestOut', func_1, 'getValue') yprime_tab = moose.Table('%s/yprime' % (data.path)) moose.connect(yprime_tab, 'requestOut', func_1, 'getDerivative') func_1.mode = 3 # This forces both f ad f' to be computed and sent out moose.setClock(0, simdt) moose.setClock(1, simdt) moose.setClock(2, simdt) moose.setClock(3, simdt) moose.useClock(0, '%s/##[TYPE=StimulusTable]' % (model.path), 'process') moose.useClock(1, '%s/##[TYPE=Func]' % (model.path), 'process') moose.useClock(2, '%s/##[TYPE=DiffAmp]' % (model.path), 'process') moose.useClock(3, '%s/##' % (data.path), 'process') moose.reinit() t = xarr[-1] - xarr[0] print(('Run for', t)) moose.start(t) y = np.asarray(y_tab.vector) yp = np.asarray(yprime_tab.vector) pylab.plot(x_tab.vector, y, 'r-.', label='f(x)') pylab.plot(x_tab.vector, yp / 1000, 'b--', label="1e-3 * f'(x)") pylab.legend() pylab.show()
def main(): """ This illustrates the use of rdesigneur to build a simple dendrite with spines, and to confirm that the chemical contents of the spines align with the electrical. Just a single molecule Ca is involved. It diffuses and we plot the distribution. It causes 'inject' of the relevant compartment to rise. """ makeModel() # Create the output tables graphs = moose.Neutral('/graphs') #dendVm = addPlot( 'model/elec/dend', 'getVm', 'dendVm', 8 ) addPlot('model/chem/dend/Ca[0]', 'getConc', 'dCa0', 18) addPlot('model/chem/dend/Ca[25]', 'getConc', 'dCa25', 18) addPlot('model/chem/dend/Ca[49]', 'getConc', 'dCa49', 18) addPlot('model/chem/spine/Ca[0]', 'getN', 'sCa0', 18) addPlot('model/chem/spine/Ca[25]', 'getN', 'sCa25', 18) addPlot('model/chem/spine/Ca[49]', 'getN', 'sCa49', 18) addPlot('model/chem/psd/Ca[0]', 'getConc', 'pCa0', 18) addPlot('model/chem/psd/Ca[25]', 'getConc', 'pCa25', 18) addPlot('model/chem/psd/Ca[49]', 'getConc', 'pCa49', 18) d = moose.vec('/model/chem/dend/Ca') s = moose.vec('/model/chem/spine/Ca') p = moose.vec('/model/chem/psd/Ca') s[5].nInit = 1000 s[40].nInit = 5000 moose.reinit() moose.start(runtime) fig = plt.figure(figsize=(13, 10)) p1 = fig.add_subplot(311) plotVm(p1, 'dend') plotVm(p1, 'head') plotVm(p1, 'psd') p1.legend() #time = numpy.arange( 0, dendVm.vector.size, 1 ) * dendVm.dt #p1.plot( time, dendVm.vector, label = 'dendVm' ) p2 = fig.add_subplot(312) p2.plot(d.conc, label='idendCa') p2.plot(s.conc, label='ispineCa') p2.plot(p.conc, label='ipsdCa') p2.legend() ''' p2 = fig.add_subplot( 312 ) for i in moose.wildcardFind( '/graphs/#Ca#' ): time = numpy.arange( 0, i.vector.size, 1 ) * i.dt p2.plot( time, i.vector, label = i.name ) p2.legend() ''' p3 = fig.add_subplot(313) p3.plot(getMidpts('dend'), d.conc, label='dendCa') #p3.plot( range( 0, len( d ) ), d.conc, label = 'dendCa' ) p3.plot(getMidpts('spine'), s.conc, label='spineCa') p3.plot(getMidpts('psd'), p.conc, label='psdCa') p3.legend() plt.show() app = QtGui.QApplication(sys.argv) #widget = mv.MoogliViewer( '/model' ) morphology = moogli.read_morphology_from_moose(name="", path='/model/elec') widget = moogli.MorphologyViewerWidget(morphology) widget.show() return app.exec_() quit()
def write_nsdf(): """ Setup a dummy model with a PulseGen vec and dump the outputValue in NSDF file """ simtime = 100.0 dt = 1e-3 elements = 5 model = moose.Neutral('/model') pulsegen = moose.PulseGen('/model/pulse', elements) spikegen = moose.SpikeGen('/model/t_lead', elements) nsdf = moose.NSDFWriter('/model/writer') nsdf.filename = 'nsdf_vec_demo.h5' nsdf.mode = 2 #overwrite existing file # nsdf.eventInput.num = elements nsdf.flushLimit = 100 for ii in range(elements): pulse = pulsegen.vec[ii] t_lead = spikegen.vec[ii] # Just to make the values different for different elements in # the vec ... pulse.level[0] = 1.0 * (ii + 1) pulse.delay[0] = 5 * (ii + 1) pulse.width[0] = 20 t_lead.threshold = 0.5 moose.connect(pulse, 'output', t_lead, 'Vm') moose.connect(nsdf, 'requestOut', pulse, 'getOutputValue') # ei = nsdf.eventInput[ii] # moose.connect(t_lead, 'spikeOut', ei, 'input') # tab = moose.Table('spiketab_{}'.format(ii)) # tab.threshold = t_lead.threshold # moose.connect(pulse, 'output', tab, 'spike') clock = moose.element('/clock') for ii in range(32): moose.setClock(ii, dt) print(('Starting simulation at:', datetime.now().isoformat())) moose.reinit() moose.start(simtime) print(('Finished simulation at:', datetime.now().isoformat())) ################################### # 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' #################################################### ## !! Work in progress: concurrent write via h5py does not work !! #################################################### ## Now write some custom stuff via h5py print('Closing nsdf handle') nsdf.close() #explicitly close the file so we do not interfere with h5py print('Closed nsdf handle') with h5.File(nsdf.filename, 'a') as fd: static = fd.create_group('/data/static') static_pg = static.create_group(pulsegen.className) pulse_info = static_pg.create_dataset('pulse_0', (elements, ), dtype=np.dtype([ ('delay', 'float64'), ('level', 'float64'), ('width', 'float64') ])) map_ = fd.create_group('/map/static') map_pg = map_.create_group(pulsegen.className) map_pulse = map_pg.create_dataset('pulse_0', (elements, ), dtype=h5.special_dtype(vlen=str)) for ii in range(elements): pulse_info['delay', ii] = pulsegen.vec[ii].delay[0] pulse_info['width', ii] = pulsegen.vec[ii].width[0] pulse_info['level', ii] = pulsegen.vec[ii].level[0] map_pulse[ii] = pulsegen.vec[ii].path #TODO: connect this as a dimension scale on pulse_info return nsdf.filename
def main(): """ This example builds a simple multiscale model involving electrical and chemical signaling, but without spatial dimensions. The electrical cell model is in a single compartment and has voltage-gated channels, including a voltage-gated Ca channel for Ca influx, and a K_A channel which is regulated by the chemical pathways. The chemical model has calcium activating Calmodulin which activates CaM-Kinase II. The kinase phosphorylates the K_A channel to inactivate it. The net effect of the multiscale activity is a positive feedback loop where activity increases Ca, which activates the kinase, which reduces K_A, leading to increased excitability of the cell. In this example this results in a bistable neuron. In the resting state the cell does not fire, but if it is activated by a current pulse the cell will continue to fire even after the current is turned off. Application of an inhibitory current restores the cell to its silent state. Both the electrical and chemical models are loaded in from model description files, and these files could be replaced if one wished to define different models. However, there are model-specific Adaptor objects needed to map activity between the models of the two kinds. The Adaptors connect specific model entities between the two models. Here one Adaptor connects the electrical Ca_conc object to the chemical Ca pool. The other Adaptor connects the chemical pool representing the K_A channel to its conductance term in the electrical model. """ runtime = 4 chemDt = 0.005 ePlotDt = 0.5e-3 cPlotDt = 0.0025 makeModel() moose.setClock( 8, ePlotDt ) moose.setClock( 18, cPlotDt ) for i in range( 10, 18 ): moose.setClock( i, chemDt ) graphs = moose.Neutral( '/graphs' ) caplot = addPlot( '/model/elec/soma/Ca_conc', 'getCa', 'somaCa', 8 ) vmplot = addPlot( '/model/elec/soma', 'getVm', 'somaVm', 8 ) ikplot = addPlot( '/model/elec/soma/K_A', 'getIk', 'KAIk', 8 ) addPlot( '/model/chem/kinetics/chan', 'getConc', 'chan', 18 ) addPlot( '/model/chem/kinetics/Ca', 'getConc', 'Ca', 18 ) addPlot( '/model/chem/kinetics/CaM', 'getConc', 'CaM', 18 ) addPlot( '/model/chem/kinetics/Ca_CaM_CaMKII', 'getConc', 'enz', 18 ) hsolve = moose.HSolve( '/model/elec/hsolve' ) hsolve.dt = 50.0e-6 hsolve.target = '/model/elec/soma' moose.reinit() moose.element( '/model/elec/soma' ).inject = 0e-12 moose.start( runtime ) moose.element( '/model/elec/soma' ).inject = 1e-12 moose.start( runtime ) moose.element( '/model/elec/soma' ).inject = 0e-12 moose.start( runtime ) moose.element( '/model/elec/soma' ).inject = -1e-12 moose.start( runtime ) moose.element( '/model/elec/soma' ).inject = 0e-12 moose.start( runtime ) fig = plt.figure( figsize = (12,10) ) t = numpy.arange( 0, caplot.vector.size, 1 ) * caplot.dt p1 = fig.add_subplot( 411 ) p1.plot( t, caplot.vector, label="Ca elec" ) p1.legend() p2 = fig.add_subplot( 412 ) p2.plot( t, vmplot.vector, label="Vm" ) p2.legend() p3 = fig.add_subplot( 413 ) p3.plot( t, ikplot.vector, label="Ik for K_A" ) p3.legend() p4 = fig.add_subplot( 414 ) for x in moose.wildcardFind( '/graphs/#[FIELD(tick)=18]' ): t = numpy.arange( 0, x.vector.size, 1 ) * x.dt p4.plot( t, x.vector, label=x.name ) p4.legend() plt.show() quit()
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 as a hybrid of a reaction and a function which sets its rates. Please see rxdFuncDiffusion.py for a variant that uses just a function object to set up the system. """ dt = 0.1 # define the geometry compt = moose.CylMesh( '/cylinder' ) compt.r0 = compt.r1 = 1 compt.diffLength = 0.2 compt.x1 = 100 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 = 1 # define diffusion constant # There is an implicit reaction substrate/product. MOOSE makes it explicit. buf = moose.BufPool( '/cylinder/buf' ) buf.nInit = 1 # The reaction is something entirely peculiar, not a chemical thing. reaction = moose.Reac( '/cylinder/reac' ) reaction.Kb = 0 # so here we set up a function calculation to do the same thing. func = moose.Function( '/cylinder/reac/func' ) func.expr = "(1 - x0) * (0.3 - x0)" func.x.num = 1 #specify number of input variables. #Connect the reaction to the pools moose.connect( reaction, 'sub', c, 'reac' ) moose.connect( reaction, 'prd', buf, 'reac' ) #Connect the function to the reaction moose.connect( func, 'valueOut', reaction, 'setNumKf' ) #Connect the molecules to the func moose.connect( c, 'nOut', func.x[0], 'input' ) #Set up solvers ksolve = moose.Ksolve( '/cylinder/ksolve' ) 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 = [ (q < 0.2 * compt.x1) for q in x ] # Run and plot it. moose.reinit() 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, 1.05 ) pylab.legend() pylab.show()
def main(): library = moose.Neutral('/library') makePassiveSoma('cell', params['dendL'], params['dendDia']) makeChemProto() rdes = rd.rdesigneur( turnOffElec=True, chemPlotDt=0.1, diffusionLength=params['diffusionL'], cellProto=[['cell', 'soma']], chemProto=[['hydra', 'hydra']], chemDistrib=[['hydra', 'soma', 'install', '1']], plotList=[['soma', '1', 'dend/A', 'n', '# of A'], ['soma', '1', 'dend/B', 'n', '# of B']], # moogList = [['soma', '1', 'dend/A', 'n', 'num of A (number)']] ) moose.le('/library') moose.le('/library/hydra') moose.showfield('/library/soma/soma') rdes.buildModel() #moose.element('/model/chem/dend/B').vec[50].nInit=15.5 A = moose.vec('/model/chem/dend/A') #B = moose.vec('/model/chem/dend/B') # A.concInit=1 # B.concInit=10 moose.element('/model/chem/dend/B').vec[50].nInit = 10.3 #moose.element('/model/chem/dend/B').vec[25].nInit=0 #A.nInit=1 #B.nInit=15 for i in range(0, 49): moose.element('/model/chem/dend/A').vec[i].diffConst = 1 moose.element('/model/chem/dend/B').vec[i].diffConst = 0 for i in range(50, 99): moose.element('/model/chem/dend/A').vec[i].diffConst = 1 moose.element('/model/chem/dend/B').vec[i].diffConst = 0 print "diffconst is ", moose.element( '/model/chem/dend/A').vec[50].diffConst #for i in range(98,99): #moose.element('/model/chem/dend/A').vec[i].diffConst=1e-06 #moose.element('/model/chem/dend/B').vec[i].diffConst=0 #Adot = moose.element('/model/chem/dend/A/Adot') #Bdot = moose.element('/model/chem/dend/B/Bdot') #print "\n\n\t\t Before Run", Adot, Bdot, A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit moose.reinit() moose.start(500) #print "\n\n\t\t After Run", A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit # rdes.display() # rdes.displayMoogli( 1, 400, 0.001 ) avec = moose.vec('/model/chem/dend/A').n bvec = moose.vec('/model/chem/dend/B').n #tab = moose.element( '/model/graphs/plot0') #dt = tab.dt #tvec=[] #tvec.append( tab.vector ) # xplot = [] # xplot.append( avec ) ## t = np.arange( 0, len( tvec[0] ), 1.0 ) * dt plt.plot(bvec) #print bvec, len(bvec), bvec return bvec, avec