def loadModels(filepath): """ load models into moose if file, if moosepath itself it passes back the path and delete solver if exist """ modelpath = '/' loaded = False if os.path.isfile(filepath): fpath, filename = os.path.split(filepath) # print " head and tail ",head, " ",tail # modelpath = filename[filename.rfind('/'): filename.rfind('.')] # print "modelpath ",modelpath # ext = os.path.splitext(filename)[1] # filename = filename.strip() modelpath = '/' + filename[:filename.rfind('.')] modeltype = mtypes.getType(filepath) subtype = mtypes.getSubtype(filepath, modeltype) if subtype == 'kkit' or modeltype == "cspace": moose.loadModel(filepath, modelpath) loaded = True elif subtype == 'sbml': #moose.mooseReadSBML(filename,modelpath) #loaded = True pass else: print("This file is not supported for mergering") modelpath = moose.Shell('/') elif moose.exists(filepath): modelpath = filepath loaded = True return modelpath, loaded
def loadModels(filepath): """ load models into moose if file, if moosepath itself it passes back the path and delete solver if exist """ modelpath = '/' loaded = False if os.path.isfile(filepath) : fpath, filename = os.path.split(filepath) # print " head and tail ",head, " ",tail # modelpath = filename[filename.rfind('/'): filename.rfind('.')] # print "modelpath ",modelpath # ext = os.path.splitext(filename)[1] # filename = filename.strip() modelpath = '/'+filename[:filename.rfind('.')] modeltype = mtypes.getType(filepath) subtype = mtypes.getSubtype(filepath, modeltype) if subtype == 'kkit' or modeltype == "cspace": moose.loadModel(filepath,modelpath) loaded = True elif subtype == 'sbml': #moose.mooseReadSBML(filename,modelpath) #loaded = True pass else: print("This file is not supported for mergering") modelpath = moose.Shell('/') elif moose.exists(filepath): modelpath = filepath loaded = True return modelpath,loaded
def main( runTime ): try: moose.delete('/acc92') print("Deleted old model") except Exception as e: print("Could not clean. model not loaded yet") moose.loadModel('acc92_caBuff.g',loadpath,'gsl') ca = moose.element(loadpath+'/kinetics/Ca') pr = moose.element(loadpath+'/kinetics/protein') clockdt = moose.Clock('/clock').dts moose.setClock(8, 0.1)#simdt moose.setClock(18, 0.1)#plotdt print clockdt print " \t \t simdt ", moose.Clock('/clock').dts[8],"plotdt ",moose.Clock('/clock').dts[18] ori = ca.concInit tablepath = loadpath+'/kinetics/Ca' tableele = moose.element(tablepath) table = moose.Table2(tablepath+'.con') x = moose.connect(table, 'requestOut', tablepath, 'getConc') tablepath1 = loadpath+'/kinetics/protein' tableele1 = moose.element(tablepath1) table1 = moose.Table2(tablepath1+'.con') x1 = moose.connect(table1, 'requestOut', tablepath1, 'getConc') ca.concInit = ori print("[INFO] Running for 4000 with Ca.conc %s " % ca.conc) moose.start(4000) ca.concInit = 5e-03 print("[INFO] Running for 20 with Ca.conc %s " % ca.conc) moose.start(20) ca.concInit = ori moose.start( runTime ) #here give the interval time ca.concInit = 5e-03 print("[INFO] Running for 20 with Ca.conc %s " % ca.conc) moose.start(20) ca.concInit = ori print("[INFO] Running for 2000 with Ca.conc %s " % ca.conc) moose.start(2000) pylab.figure() pylab.subplot(2, 1, 1) t = numpy.linspace(0.0, moose.element("/clock").runTime, len(table.vector)) # sec pylab.plot( t, table.vector, label="Ca Conc (interval- 8000s)" ) pylab.legend() pylab.subplot(2, 1, 2) t1 = numpy.linspace(0.0, moose.element("/clock").runTime, len(table1.vector)) # sec pylab.plot( t1, table1.vector, label="Protein Conc (interval- 8000s)" ) pylab.legend() pylab.savefig( os.path.join( dataDir, '%s_%s.png' % (table1.name, runTime) ) ) print('[INFO] Saving data to csv files in %s' % dataDir) tabPath1 = os.path.join( dataDir, '%s_%s.csv' % (table.name, runTime)) numpy.savetxt(tabPath1, numpy.matrix([t, table.vector]).T, newline='\n') tabPath2 = os.path.join( dataDir, '%s_%s.csv' % (table1.name, runTime) ) numpy.savetxt(tabPath2, numpy.matrix([t1, table1.vector]).T, newline='\n')
def __init__(self, *args): QWidget.__init__(self, *args) #c = moose.ZombiePool('/compartment') c = moose.Compartment('/compartment') moose.loadModel('../Demos/Genesis_files/reaction.g','/rec') for l in moose.wildcardFind('/rec/##[TYPE=ZombiePool]'): if( moose.element(l).path == '/rec/kinetics/Sub'): c = moose.element(l) tablemodel = ObjectFieldsModel(c,['Field','Value'],self) #my_array, self) tableview = QTableView() tableview.setModel(tablemodel) #tableview.setShowGrid(False) vh = tableview.verticalHeader() vh.setVisible(False) hh = tableview.horizontalHeader() hh.setStretchLastSection(True) tableview.setAlternatingRowColors(True) #tableview.resizeColumnsToContents() layout = QVBoxLayout(self) layout.addWidget(tableview) self.setLayout(layout)
def _loadElec( self, efile, elecname ): if ( efile[ len( efile ) - 2:] == ".p" ): self.elecid = moose.loadModel( efile, '/library/' + elecname)[0] print self.elecid elif ( efile[ len( efile ) - 4:] == ".swc" ): self.elecid = moose.loadModel( efile, '/library/' + elecname)[0] else: nm = NeuroML() print "in _loadElec, combineSegments = ", self.combineSegments nm.readNeuroMLFromFile( efile, \ params = {'combineSegments': self.combineSegments, \ 'createPotentialSynapses': True } ) if moose.exists( '/cells' ): kids = moose.wildcardFind( '/cells/#' ) else: kids = moose.wildcardFind( '/library/#[ISA=Neuron],/library/#[TYPE=Neutral]' ) if ( kids[0].name == 'spine' ): kids = kids[1:] assert( len( kids ) > 0 ) self.elecid = kids[0] temp = moose.wildcardFind( self.elecid.path + '/#[ISA=CompartmentBase]' ) transformNMDAR( self.elecid.path ) kids = moose.wildcardFind( '/library/##[0]' ) for i in kids: i.tick = -1
def _loadElec(self, efile, elecname): if (efile[len(efile) - 2:] == ".p"): self.elecid = moose.loadModel(efile, '/library/' + elecname)[0] print(self.elecid) elif (efile[len(efile) - 4:] == ".swc"): self.elecid = moose.loadModel(efile, '/library/' + elecname)[0] else: nm = NeuroML() print("in _loadElec, combineSegments = ", self.combineSegments) nm.readNeuroMLFromFile( efile, \ params = {'combineSegments': self.combineSegments, \ 'createPotentialSynapses': True } ) if moose.exists('/cells'): kids = moose.wildcardFind('/cells/#') else: kids = moose.wildcardFind( '/library/#[ISA=Neuron],/library/#[TYPE=Neutral]') if (kids[0].name == 'spine'): kids = kids[1:] assert (len(kids) > 0) self.elecid = kids[0] temp = moose.wildcardFind(self.elecid.path + '/#[ISA=CompartmentBase]') transformNMDAR(self.elecid.path) kids = moose.wildcardFind('/library/##[0]') for i in kids: i.tick = -1
def loadModels(filename): """ load models into moose if file, if moosepath itself it passes back the path and delete solver if exist """ modelpath = '/' loaded = False if os.path.isfile(filename): modelpath = filename[filename.rfind('/'):filename.rfind('.')] ext = os.path.splitext(filename)[1] filename = filename.strip() modeltype = mtypes.getType(filename) subtype = mtypes.getSubtype(filename, modeltype) if subtype == 'kkit' or modeltype == "cspace": moose.loadModel(filename, modelpath) loaded = True elif subtype == 'sbml': #moose.ReadSBML() pass else: print("This file is not supported for mergering") modelpath = moose.Shell('/') elif moose.exists(filename): modelpath = filename loaded = True ## default is 'ee' solver while loading the model using moose.loadModel, ## yet deleteSolver is called just to be assured if loaded: deleteSolver(modelpath) return modelpath, loaded
def createMultiCompCell(file_name, container_name, library_name, comp_type, channelSet, condSet, rateParams, CaParams=None, CaPoolParams=None, HCNParams=None, cell_RM=None, cell_CM=None, cell_RA=None, cell_initVm=None, cell_Em=None): # Create the channel types and store them in a library to be used by each compartment # in the model createChanLib(library_name, channelSet, rateParams, CaParams, HCNParams) # Load in the model in question if file_name.endswith('.p'): cell = moose.loadModel(file_name, container_name) for comp in moose.wildcardFind(cell.path + '/' + '#[TYPE=' + comp_type + ']'): for chan_name, cond in condSet.items(): SA = np.pi * comp.length * comp.diameter proto = moose.element(library_name + '/' + chan_name) chan = moose.copy(proto, comp, chan_name)[0] chan.Gbar = cond * SA m = moose.connect(chan, 'channel', comp, 'channel') # Add the calcium pool to each compartment in the cell if it has been specified if (CaPoolParams != None): add_calcium(library_name, cell, CaPoolParams, comp_type) for key in channelSet.keys(): if ("Ca" in key): connect_cal2chan(channelSet[key].name, channelSet[key].chan_type, cell, CaPoolParams.caName, comp_type) else: cell = moose.loadModel(file_name, container_name) setCompParameters(cell, comp_type, cell_RM, cell_CM, cell_RA, cell_initVm, cell_Em) for comp in moose.wildcardFind(cell.path + '/' + '#[TYPE=' + comp_type + ']'): for chan_name, cond in condSet.items(): SA = np.pi * comp.length * comp.diameter proto = moose.element(library_name + '/' + chan_name) chan = moose.copy(proto, comp, chan_name)[0] chan.Gbar = cond * SA m = moose.connect(chan, 'channel', comp, 'channel') # Add the calcium pool to each compartment in the cell if it has been specified if (CaPoolParams != None): add_calcium(library_name, cell, CaPoolParams, comp_type) for key in channelSet.keys(): if ("Ca" in key): connect_cal2chan(channelSet[key].name, channelSet[key].chan_type, cell, CaPoolParams.caName, comp_type) return cell
def test_kkit(): """ The script demonstates to convert Chemical (Genesis) file back to Genesis file using moose """ moose.loadModel(os.path.join(cwd, '../data/reaction.g'), '/model') written = moose.writeKkit('/model', 'testsave.g') print(written)
def main(): """This example illustrates loading a kinetic model defined in Genesis format into Moose using loadModel function and using writeSBML function one can save the model into SBML format. \n Moose needs to be compiled with libsbml """ #This command loads the file into the path '/Kholodenko' moose.loadModel('../genesis/Kholodenko.g','/Kholodenko') #Writes model to xml file moose.writeSBML('/Kholodenko','Kholodenko_tosbml.xml')
def main(): """This example illustrates loading a kinetic model defined in Genesis format into Moose using loadModel function and using writeSBML function one can save the model into SBML format. \n libsbml should be installed """ #This command loads the file into the path '/Kholodenko' moose.loadModel('../genesis/Kholodenko.g', '/Kholodenko') #Writes model to xml file written = mooseWriteSBML('/Kholodenko', '../genesis/Kholodenko_tosbml.xml') print(written)
def main(): """This example illustrates loading a kinetic model defined in Genesis format into Moose using loadModel function and using writeSBML function one can save the model into SBML format. \n libsbml should be installed """ #This command loads the file into the path '/Kholodenko' moose.loadModel('../genesis/Kholodenko.g','/Kholodenko') #Writes model to xml file written = mooseWriteSBML('/Kholodenko','../genesis/Kholodenko_tosbml.xml') print(written)
def main(): # Schedule the whole lot moose.setClock( 4, 0.1 ) # for the computational objects moose.setClock( 5, 0.1 ) # clock for the solver moose.setClock( 8, 1.0 ) # for the plots # The wildcard uses # for single level, and ## for recursive. #compartment = makeModel() moose.loadModel( '../Genesis_files/M1719.cspace', '/model', 'ee' ) compartment = moose.element( 'model/kinetics' ) compartment.name = 'compartment' ksolve = moose.Ksolve( '/model/compartment/ksolve' ) stoich = moose.Stoich( '/model/compartment/stoich' ) stoich.compartment = compartment stoich.ksolve = ksolve #ksolve.stoich = stoich stoich.path = "/model/compartment/##" state = moose.SteadyState( '/model/compartment/state' ) moose.useClock( 5, '/model/compartment/ksolve', 'process' ) moose.useClock( 8, '/model/graphs/#', 'process' ) moose.reinit() state.stoich = stoich #state.showMatrices() state.convergenceCriterion = 1e-7 moose.le( '/model/graphs' ) a = moose.element( '/model/compartment/a' ) b = moose.element( '/model/compartment/b' ) c = moose.element( '/model/compartment/c' ) for i in range( 0, 100 ): getState( ksolve, state ) moose.start( 100.0 ) # Run the model for 100 seconds. b = moose.element( '/model/compartment/b' ) c = moose.element( '/model/compartment/c' ) # move most molecules over to b b.conc = b.conc + c.conc * 0.95 c.conc = c.conc * 0.05 moose.start( 100.0 ) # Run the model for 100 seconds. # move most molecules back to a c.conc = c.conc + b.conc * 0.95 b.conc = b.conc * 0.05 moose.start( 100.0 ) # Run the model for 100 seconds. # Iterate through all plots, dump their contents to data.plot. displayPlots() quit()
def loadFile(filename, target, merge=True): """Try to load a model from specified `filename` under the element `target`. if `merge` is True, the contents are just loaded at target. If false, everything is deleted from the parent of target unless the parent is root. Returns ------- a dict containing at least these three entries: modeltype: type of the loaded model. subtype: subtype of the loaded model, None if no specific subtype modelroot: root element of the model, None if could not be located - as is the case with Python scripts """ istext = True with open(filename, 'rb') as infile: istext = mtypes.istextfile(infile) if not istext: print 'Cannot handle any binary formats yet' return None parent, child = posixpath.split(target) p = moose.Neutral(parent) if not merge and p.path != '/': for ch in p.children: moose.delete(ch) try: modeltype = mtypes.getType(filename) subtype = mtypes.getSubtype(filename, modeltype) except KeyError: raise FileLoadError('Do not know how to handle this filetype: %s' % (filename)) pwe = moose.getCwe() if modeltype == 'genesis': if subtype == 'kkit' or subtype == 'prototype': model = moose.loadModel(filename, target) else: print 'Only kkit and prototype files can be loaded.' elif modeltype == 'cspace': model = moose.loadModel(filename, target) elif modeltype == 'xml' and subtype == 'neuroml': model = neuroml.loadNeuroML_L123(filename) else: raise FileLoadError('Do not know how to handle this filetype: %s' % (filename)) moose.setCwe(pwe) # The MOOSE loadModel changes the current working element to newly loaded model. We revert that behaviour # TODO: check with Aditya how to specify the target for # neuroml reader return {'modeltype': modeltype, 'subtype': subtype, 'model': model}
def main(): """Test main""" model = moose.Neutral('/model') moose.loadModel('../Demos/Genesis_files/Kholodenko.g', '/model/Kholodenko') # tab = moose.element('/model/Kholodenko/graphs/conc1/MAPK_PP.Co') # print tab # for t in tab.children: # print t app = QtGui.QApplication(sys.argv) mainwin = QtGui.QMainWindow() mainwin.setWindowTitle('Model tree test') wildcardWidget = SearchWidget() mainwin.setCentralWidget(wildcardWidget) mainwin.show() sys.exit(app.exec_())
def load_neuron_file(fileName, cellPath, RM, RA, CM): cell = moose.loadModel(fileName, cellPath) for child in cell[0].children: for comp in child: comp.RM = RM comp.RA = RA comp.CM = CM
def loadChem(): chem = moose.Neutral( '/model/chem' ) modelId = moose.loadModel( os.path.join( scriptDir, '..', 'genesis', 'chanPhosphByCaMKII.g' ) , '/model/chem', 'gsl' ) nmstoich = moose.element( '/model/chem/kinetics/stoich' )
def main(): """Test main: load a model and display the tree for it""" model = moose.Neutral('/model') moose.loadModel('../Demos/Genesis_files/Kholodenko.g', '/model/Kholodenko') # tab = moose.element('/model/Kholodenko/graphs/conc1/MAPK_PP.Co') # print tab # for t in tab.children: # print t app = QtGui.QApplication(sys.argv) mainwin = QtGui.QMainWindow() mainwin.setWindowTitle('Model tree test') tree = MooseTreeWidget() tree.recreateTree(root='/model/') mainwin.setCentralWidget(tree) mainwin.show() sys.exit(app.exec_())
def main(): solver = "gsl" mfile = '../../Genesis_files/Kholodenko.g' runtime = 5000.0 if ( len( sys.argv ) >= 2 ): solver = sys.argv[1] modelId = moose.loadModel( mfile, 'model', solver ) dt = moose.element( '/clock' ).dt moose.reinit() moose.start( runtime ) # Display all plots. img = mpimg.imread( 'Kholodenko_tut.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 ) * dt ax.plot( t, x[0].vector * 100, 'b-', label='Ras-MKKK * 100' ) ax.plot( t, x[1].vector, 'y-', label='MKKK-P' ) ax.plot( t, x[2].vector, 'm-', label='MKK-PP' ) ax.plot( t, x[3].vector, 'r-', label='MAPK-PP' ) plt.ylabel( 'Conc (mM)' ) plt.xlabel( 'Time (seconds)' ) pylab.legend() pylab.show()
def make_prototype(passive=True): path = '%s/rc19' % (library.path) pfile = 'rc19.p' try: return moose.element(path) except ValueError: pass if not passive: make_na() make_kv() make_km() make_kca() make_cat() make_cahva() make_h() try: proto = moose.element(path) except ValueError: print('Loading model %s to %s' % (pfile, path)) proto = moose.loadModel(pfile, path, 'ee') # hsolve is not functional yet for comp in proto[0].children: comp.initVm = -75e-3 for chan in moose.wildcardFind('%s/##[ISA=HHChannel]'): chan.Gbar *= tadj return proto
def main(standalone=False): mfile = os.path.join(os.path.dirname(__file__), 'OSC_diff_vols.g') runtime = 4000.0 modelId = moose.loadModel(mfile, 'model', 'ee') kin = moose.element('/model/kinetics') compt1 = moose.element('/model/compartment_1') compt1.x1 += kin.x1 compt1.x0 += kin.x1 fixXreacs.fixXreacs('/model') #fixXreacs.restoreXreacs( '/model' ) #fixXreacs.fixXreacs( '/model' ) ks1 = moose.Ksolve('/model/kinetics/ksolve') ds1 = moose.Dsolve('/model/kinetics/dsolve') s1 = moose.Stoich('/model/kinetics/stoich') s1.compartment = moose.element('/model/kinetics') s1.ksolve = ks1 s1.dsolve = ds1 s1.path = '/model/kinetics/##' ks2 = moose.Ksolve('/model/compartment_1/ksolve') ds2 = moose.Dsolve('/model/compartment_1/dsolve') s2 = moose.Stoich('/model/compartment_1/stoich') s2.compartment = moose.element('/model/compartment_1') s2.ksolve = ks2 s2.dsolve = ds2 s2.path = '/model/compartment_1/##' ds2.buildMeshJunctions(ds1) moose.reinit() moose.start(runtime) # I don't have an analytic way to assess oscillations assert (countCrossings('/model/graphs/conc2/M.Co', 0.001) == 4) moose.delete('/model')
def loadChem( neuroCompt, spineCompt, psdCompt ): # We need the compartments to come in with a volume of 1 to match the # original CubeMesh. assert( neuroCompt.volume == 1.0 ) assert( spineCompt.volume == 1.0 ) assert( psdCompt.volume == 1.0 ) assert( neuroCompt.mesh.num == 1 ) #print 'volume = ', neuroCompt.mesh[0].volume #assert( neuroCompt.mesh[0].volume == 1.0 ) #an unfortunate mismatch # So we'll have to resize the volumes of the current compartments to the # new ones. modelId = moose.loadModel( 'x_compt.g', '/model', 'ee' ) chem = moose.element( '/model/model' ) chem.name = 'chem' oldN = moose.element( '/model/chem/compartment_1' ) oldS = moose.element( '/model/chem/compartment_2' ) oldP = moose.element( '/model/chem/kinetics' ) oldN.volume = neuroCompt.mesh[0].volume oldS.volume = spineCompt.mesh[0].volume oldP.volume = psdCompt.mesh[0].volume moveCompt( '/model/chem/kinetics/DEND', oldN, neuroCompt ) moveCompt( '/model/chem/kinetics/SPINE', oldS, spineCompt ) moveCompt( '/model/chem/kinetics/PSD', oldP, psdCompt )
def create_neuron(model, ntype, ghkYN): p_file = find_morph_file(model,ntype) try: cellproto=moose.loadModel(p_file, ntype) except IOError: print('could not load model from {!r}'.format(p_file)) raise #######channels Cond = model.Condset[ntype] for comp in moose.wildcardFind('{}/#[TYPE=Compartment]'.format(ntype)): #If we are using GHK, just create one GHK per compartment, connect it to comp #calcium concentration is connected in a different function if ghkYN: ghkproto=moose.element('/library/ghk') ghk=moose.copy(ghkproto,comp,'ghk')[0] moose.connect(ghk,'channel',comp,'channel') else: ghk=[] for channame in Cond.keys(): c = _util.distance_mapping(Cond[channame], comp) if c > 0: log.debug('Testing Cond If {} {}', channame, c) calciumPermeable = model.Channels[channame].calciumPermeable add_channel.addOneChan(channame, c, comp, ghkYN, ghk, calciumPermeable=calciumPermeable) #Compensate for actual, experimentally estimated spine density. #This gives a model that can be simulated with no explicit spines or #any number of explicitly modeled spines up to the actual spine density: spines.compensate_for_spines(model,comp,model.param_cond.NAME_SOMA) return cellproto
def _loadElec( self, efile, elecname, combineSegments ): library = moose.Neutral( '/library' ) if ( efile[ len( efile ) - 2:] == ".p" ): self.elecid = moose.loadModel( efile, self.model.path + '/' + elecname ) else: nm = NeuroML() nm.readNeuroMLFromFile( efile, \ params = {'combineSegments': combineSegments, \ 'createPotentialSynapses': True } ) if moose.exists( '/cells' ): kids = moose.wildcardFind( '/cells/#' ) else: kids = moose.wildcardFind( '/library/#[ISA=Neuron],/library/#[TYPE=Neutral]' ) if ( kids[0].name == 'spine' ): kids = kids[1:] assert( len( kids ) > 0 ) self.elecid = kids[0] temp = moose.wildcardFind( self.elecid.path + '/#[ISA=CompartmentBase]' ) moose.move( self.elecid, self.model ) self.elecid.name = elecname self._transformNMDAR( self.elecid.path ) kids = moose.wildcardFind( '/library/##[0]' ) for i in kids: i.tick = -1
def test_symcomp_readcell(): model = moose.Neutral("/model") cell = moose.loadModel("symcomp.p", "%s/cell" % (model.path)) pg = moose.PulseGen("/model/pulse") pg.delay[0] = 10e-3 pg.width[0] = 20e-3 pg.level[0] = 1e-6 pg.delay[1] = 1e9 moose.connect(pg, "output", moose.element("/model/cell/d1"), "injectMsg") data = moose.Neutral("/data") tab_soma = moose.Table("%s/soma_Vm" % (data.path)) tab_d1 = moose.Table("%s/d1_Vm" % (data.path)) tab_d2 = moose.Table("%s/d2_Vm" % (data.path)) moose.connect(tab_soma, "requestOut", moose.element("/model/cell/soma"), "getVm") moose.connect(tab_d1, "requestOut", moose.element("/model/cell/d1"), "getVm") moose.connect(tab_d2, "requestOut", moose.element("/model/cell/d2"), "getVm") moose.setClock(0, simdt) moose.setClock(1, simdt) moose.setClock(2, simdt) moose.useClock( 0, "/model/##[ISA=Compartment]", "init" ) # This is allowed because SymCompartment is a subclass of Compartment moose.useClock(1, "/model/##", "process") moose.useClock(2, "/data/##[ISA=Table]", "process") moose.reinit() moose.start(simtime) t = np.linspace(0, simtime, len(tab_soma.vector)) data_matrix = np.vstack((t, tab_soma.vector, tab_d1.vector, tab_d2.vector)) np.savetxt("symcompartment_readcell.txt", data_matrix.transpose()) pylab.plot(t, tab_soma.vector, label="Vm_soma") pylab.plot(t, tab_d1.vector, label="Vm_d1") pylab.plot(t, tab_d2.vector, label="Vm_d2") pylab.show()
def conv(fname): kfile = "./KKIT_MODELS/" + fname + ".g" modelId = moose.loadModel("./KKIT_MODELS/" + fname + ".g", 'model', 'none')[0] sfile = "./SBML_MODELS/" + fname + ".xml" moose.mooseWriteSBML('/model', sfile) moose.delete(modelId)
def _loadElec(self, efile, elecname, combineSegments): library = moose.Neutral('/library') if (efile[len(efile) - 2:] == ".p"): self.elecid = moose.loadModel(efile, self.model.path + '/' + elecname) else: nm = NeuroML() nm.readNeuroMLFromFile( efile, \ params = {'combineSegments': combineSegments, \ 'createPotentialSynapses': True } ) if moose.exists('/cells'): kids = moose.wildcardFind('/cells/#') else: kids = moose.wildcardFind( '/library/#[ISA=Neuron],/library/#[TYPE=Neutral]') if (kids[0].name == 'spine'): kids = kids[1:] assert (len(kids) > 0) self.elecid = kids[0] temp = moose.wildcardFind(self.elecid.path + '/#[ISA=CompartmentBase]') moose.move(self.elecid, self.model) self.elecid.name = elecname self._transformNMDAR(self.elecid.path) kids = moose.wildcardFind('/library/##[0]') for i in kids: i.tick = -1
def main(): #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' ).dt 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 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 runDoser( kkit, ht, plotPos, doseList, var = "Ca", title = "", BDNF = -1 ): ax = plotBoilerplate( char[plotPos], plotPos, title, xlabel = "[{}] ($\mu$M)".format( var ), ylabel = "aS6K ($\mu$M)" ) ax.set_xscale( "log" ) modelId = moose.loadModel( kkit, 'model', 'gsl' ) tmoose = time.time() if BDNF > 0.0: moose.element( '/model/kinetics/BDNF' ).concInit = BDNF * 1e-3 x, y = doseRespMoose( var, doseList ) tmoose = time.time() - tmoose ax.plot( x , y, label = "aS6K_vs_Ca_moose" ) mvec = np.array( y ) jsonDict = hillTau.loadHillTau( ht ) hillTau.scaleDict( jsonDict, hillTau.getQuantityScale( jsonDict ) ) model = hillTau.parseModel( jsonDict ) outputMolIndex = model.molInfo.get( "aS6K" ).index doseMolIndex = model.molInfo.get( var ).index if BDNF > 0.0: model.conc[ model.molInfo.get( "BDNF" ).index ] = BDNF * 1e-3 model.concInit[ model.molInfo.get( "BDNF" ).index ] = BDNF * 1e-3 tht = time.time() x, y = doseResp( model, doseMolIndex, outputMolIndex, doseList ) tht = time.time() - tht ax.plot( x , y, label = "aS6K_vs_" + var ) ax.set_ylim( 0.0, 0.5 ) print( "dose_resp runtimes: t Moose = {:.2f}; t HillTau = {:.4f}: ".format( tmoose, tht) ) htvec = np.array( y ) dy = htvec - mvec print( char[plotPos], ": Dose_resp normalized rms diff =", np.sqrt( np.mean( dy * dy )) / np.max( htvec ))
def create_comp_model(container_name, file_name, comp_RM=None, comp_CM=None, comp_RA=None, comp_ELEAK=None, comp_initVm=None): 'Create compartmental model from *.p file or a *.swc file.' if file_name.endswith('.p'): root_comp = moose.loadModel(file_name, container_name) elif file_name.endswith('swc'): assert comp_RM is not None, "comp_RM needs valid value." assert comp_CM is not None, "comp_CM needs valid value." assert comp_RA is not None, "comp_RA needs valid value." assert comp_ELEAK is not None, "comp_ELEAK needs valid value." assert comp_initVm is not None, "comp_initVm needs valid value." root_comp = moose.loadModel(file_name, container_name) for comp in moose.wildcardFind(root_comp.path+'/#[TYPE=Compartment]'): set_comp_values(comp, comp_RM, comp_CM, comp_RA, comp_initVm, comp_ELEAK) else: raise "Invalid cell model file type." return root_comp
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_files/acc35.g' runtime = 2000.0 if ( len( sys.argv ) == 2 ): solver = sys.argv[1] modelId = moose.loadModel( mfile, 'model', solver ) # Increase volume so that the stochastic solver gssa # gives an interesting output compt = moose.element( '/model/kinetics' ) compt.volume = 5e-19 moose.reinit() moose.start( 500 ) moose.element( '/model/kinetics/PDGFR/PDGF' ).concInit = 0.0001 moose.start( 400 ) moose.element( '/model/kinetics/PDGFR/PDGF' ).concInit = 0.0 moose.start( 2000 ) moose.element( '/model/kinetics/Ca' ).concInit = 0.0 moose.start( 500 ) moose.element( '/model/kinetics/Ca' ).concInit = 0.00008 moose.start( 2000 ) # Display all plots. img = mpimg.imread( 'mapkFB.png' ) fig = plt.figure( figsize=(12, 10 ) ) png = fig.add_subplot( 211 ) imgplot = plt.imshow( img ) ax = fig.add_subplot( 212 ) x = moose.wildcardFind( '/model/#graphs/conc#/#' ) t = numpy.arange( 0, x[0].vector.size, 1 ) * x[0].dt ax.plot( t, x[0].vector, 'b-', label=x[0].name ) ax.plot( t, x[1].vector, 'c-', label=x[1].name ) ax.plot( t, x[2].vector, 'r-', label=x[2].name ) ax.plot( t, x[3].vector, 'm-', label=x[3].name ) plt.ylabel( 'Conc (mM)' ) plt.xlabel( 'Time (seconds)' ) pylab.legend() pylab.show()
def main(): """ This example illustrates loading 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 load_axon(): model = moose.loadModel("axon_passive.p", "/axon") for x in model[0].children: print x.path, x.class_ pulsegen = moose.PulseGen("/pulsegen") pulsegen.delay[0] = simdt * 200 # The Axon.g in oldmoose flips the current every 20 pulses pulsegen.width[0] = simdt * 200 pulsegen.level[0] = inject moose.connect(pulsegen, "outputOut", moose.element("/axon/soma"), "injectMsg") data = moose.Neutral("/data") tab = moose.Table("%s/Vm100" % (data.path)) moose.connect(tab, "requestData", moose.ObjId("/axon/c100"), "get_Vm") pulsetab = moose.Table("/data/inject") moose.connect(pulsetab, "requestData", pulsegen, "get_output") solver = moose.HSolve("/hsolve") solver.dt = simdt solver.target = model.path return { "model": model, "Vm": tab, "inject": pulsetab, "soma": moose.element("/axon/soma"), "pulse": pulsegen, "solver": solver, }
def read_prototype(celltype, cdict): """Read the cell prototype file for the specified class. The channel properties are updated using values in cdict.""" filename = '%s/%s.p' % (config.modelSettings.protodir, celltype) logger.debug('Reading prototype file %s' % (filename)) adjust_chanlib(cdict) cellpath = '%s/%s' % (config.modelSettings.libpath, celltype) if moose.exists(cellpath): return moose.element(cellpath) for handler in logger.handlers: handler.flush() proto = moose.loadModel(filename, cellpath) # If prototype files do not have absolute compartment positions, # set the compartment postions to origin. This will avoid # incorrect assignemnt of position when the x/y/z values in # prototype file is just to for setting the compartment length. if not config.modelSettings.morph_has_postion: for comp in moose.wildcardFind('%s/#[TYPE=Compartment]' % (proto.path)): comp.x = 0.0 comp.y = 0.0 comp.z = 0.0 leveldict = read_keyvals('%s/%s.levels' % (config.modelSettings.protodir, celltype)) depths = read_keyvals('%s/%s.depths' % (config.modelSettings.protodir, celltype)) depthdict = {} for level, depthset in list(depths.items()): if len(depthset) != 1: raise Exception('Depth set must have only one entry.') depthdict[level] = depthset.pop() assign_depths(proto, depthdict, leveldict) config.logger.debug('Read %s with %d compartments' % (celltype, len(moose.wildcardFind('%s/#[TYPE=Compartment]' % (proto.path))))) return proto
def runDoser(kkit, ht, plotPos, title=""): ax = plotBoilerplate(char[plotPos], plotPos, title, xlabel="[Ca] ($\mu$M)", ylabel="[synAMPAR] ($\mu$M)") ax.set_xscale("log") ax.set_xlim(0.01, 10) ax.set_ylim(0, 0.6) modelId = moose.loadModel(kkit, 'model', 'gsl') x, y = doseRespMoose() ax.plot(x, y, label="Syn_vs_Ca_moose") moosey = np.array(y) jsonDict = hillTau.loadHillTau(ht) hillTau.scaleDict(jsonDict, hillTau.getQuantityScale(jsonDict)) model = hillTau.parseModel(jsonDict) outputMolIndex = model.molInfo.get("synAMPAR").index CaMolIndex = model.molInfo.get("Ca").index x, y = doseResp(model, CaMolIndex, outputMolIndex) ax.plot(x, y, label="Syn_vs_Ca") hty = np.array(y) dy = moosey - hty print("Dose-resp normalized rms diff =", np.sqrt(np.mean(dy * dy)) / np.max(hty))
def main(): """ This example illustrates loading, and running a kinetic model for a bistable positive feedback system, defined in kkit format. This is based on Bhalla, Ram and Iyengar, Science 2002. The core of this model is a positive feedback loop comprising of the MAPK cascade, PLA2, and PKC. It receives PDGF and Ca2+ as inputs. This model is quite a large one and due to some stiffness in its equations, it runs somewhat slowly. The simulation illustrated here shows how the model starts out in a state of low activity. It is induced to 'turn on' when a a PDGF stimulus is given for 400 seconds. After it has settled to the new 'on' state, model is made to 'turn off' by setting the system calcium levels to zero for a while. This is a somewhat unphysiological manipulation! """ solver = "gsl" # Pick any of gsl, gssa, ee.. #solver = "gssa" # Pick any of gsl, gssa, ee.. mfile = '../../genesis/acc35.g' runtime = 2000.0 if ( len( sys.argv ) == 2 ): solver = sys.argv[1] modelId = moose.loadModel( mfile, 'model', solver ) # Increase volume so that the stochastic solver gssa # gives an interesting output compt = moose.element( '/model/kinetics' ) compt.volume = 5e-19 moose.reinit() moose.start( 500 ) moose.element( '/model/kinetics/PDGFR/PDGF' ).concInit = 0.0001 moose.start( 400 ) moose.element( '/model/kinetics/PDGFR/PDGF' ).concInit = 0.0 moose.start( 2000 ) moose.element( '/model/kinetics/Ca' ).concInit = 0.0 moose.start( 500 ) moose.element( '/model/kinetics/Ca' ).concInit = 0.00008 moose.start( 2000 ) # Display all plots. img = mpimg.imread( 'mapkFB.png' ) fig = plt.figure( figsize=(12, 10 ) ) png = fig.add_subplot( 211 ) imgplot = plt.imshow( img ) ax = fig.add_subplot( 212 ) x = moose.wildcardFind( '/model/#graphs/conc#/#' ) t = numpy.arange( 0, x[0].vector.size, 1 ) * x[0].dt ax.plot( t, x[0].vector, 'b-', label=x[0].name ) ax.plot( t, x[1].vector, 'c-', label=x[1].name ) ax.plot( t, x[2].vector, 'r-', label=x[2].name ) ax.plot( t, x[3].vector, 'm-', label=x[3].name ) plt.ylabel( 'Conc (mM)' ) plt.xlabel( 'Time (seconds)' ) pylab.legend() pylab.show()
def main(): """ This example illustrates loading 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 main(): """ This is a toy model of synaptic bidirectional plasticity. The model has a small a bistable chemical switch, and a small set of reactions that decode calcium input. One can turn the switch on with short high calcium pulses (over 2 uM for about 10 sec). One can turn it back off again using a long, lower calcium pulse (0.2 uM, 2000 sec). """ method = 'old_gssa' # This is the Gillespie Stoichastic Systems Algorithm if (len(sys.argv) >= 2): method = sys.argv[1] if (method == "gsl"): method = "old_gsl" if (method == "gssa"): method = "old_gssa" # Load in the model and set up to use the specified method modelId = moose.loadModel('./stargazin_synapse.g', 'model', method) moose.start(1000.0) # Run the model for 1000 seconds. Ca = moose.element('/model/kinetics/BULK/Ca') applyInputPulseTrain(Ca, 'concInit', [(1000.0, 1.0e-3), (10.0, 0.08e-3), (50.0, 1.0e-3), (10.0, 0.08e-3), (1000.0, 0.2e-3), (2000.0, 0.08e-3)]) moose.start(2000.0) displayPlots() quit()
def main(): """Test main: load a model and display the tree for it""" model = moose.Neutral('/model') moose.loadModel('../Demos/Genesis_files/Kholodenko.g', '/model/Kholodenko') # tab = moose.element('/model/Kholodenko/graphs/conc1/MAPK_PP.Co') # print tab # for t in tab.children: # print t app = QtGui.QApplication(sys.argv) mainwin = QtGui.QMainWindow() mainwin.setWindowTitle('Model tree test') tree = MooseTreeWidget() tree.recreateTree(root='/model/Kholodenko') mainwin.setCentralWidget(tree) mainwin.show() sys.exit(app.exec_())
def main(): """ This is a toy model of synaptic bidirectional plasticity. The model has a small a bistable chemical switch, and a small set of reactions that decode calcium input. One can turn the switch on with short high calcium pulses (over 2 uM for about 10 sec). One can turn it back off again using a long, lower calcium pulse (0.2 uM, 2000 sec). """ method = 'old_gssa' # This is the Gillespie Stoichastic Systems Algorithm if ( len( sys.argv ) >= 2 ): method = sys.argv[1] if ( method == "gsl" ): method = "old_gsl" if ( method == "gssa" ): method = "old_gssa" # Load in the model and set up to use the specified method modelId = moose.loadModel( './stargazin_synapse.g', 'model', method ) moose.start( 1000.0 ) # Run the model for 1000 seconds. Ca = moose.element( '/model/kinetics/BULK/Ca' ) applyInputPulseTrain(Ca, 'concInit' , [ (1000.0, 1.0e-3) , (10.0, 0.08e-3) , (50.0, 1.0e-3) , (10.0, 0.08e-3) , (1000.0, 0.2e-3) , (2000.0, 0.08e-3) ] ) moose.start(2000.0) displayPlots() quit()
def main(): # Schedule the whole lot moose.setClock(4, 0.1) # for the computational objects moose.setClock(5, 0.2) # clock for the solver moose.setClock(8, 1.0) # for the plots # The wildcard uses # for single level, and ## for recursive. #compartment = makeModel() moose.loadModel('../../genesis/M1719.g', '/model', 'ee') compartment = moose.element('model/kinetics') compartment.name = 'compartment' ksolve = moose.Ksolve('/model/compartment/ksolve') stoich = moose.Stoich('/model/compartment/stoich') stoich.compartment = compartment stoich.ksolve = ksolve #ksolve.stoich = stoich stoich.path = "/model/compartment/##" state = moose.SteadyState('/model/compartment/state') moose.useClock(5, '/model/compartment/ksolve', 'process') moose.useClock(8, '/model/graphs/#', 'process') moose.reinit() state.stoich = stoich #state.showMatrices() state.convergenceCriterion = 1e-7 for i in range(0, 50): getState(ksolve, state) moose.start(100.0) # Run the model for 100 seconds. b = moose.element('/model/compartment/b') c = moose.element('/model/compartment/c') # move most molecules over to b b.conc = b.conc + c.conc * 0.95 c.conc = c.conc * 0.05 moose.start(100.0) # Run the model for 100 seconds. # move most molecules back to a c.conc = c.conc + b.conc * 0.95 b.conc = b.conc * 0.05 moose.start(100.0) # Run the model for 100 seconds. # Iterate through all plots, dump their contents to data.plot. displayPlots() quit()
def main(): # Setup parameters for simulation and plotting simdt = 1e-2 plotDt = 1 # Factors to change in the dose concentration in log scale factorExponent = 10 ## Base: ten raised to some power. factorBegin = -20 factorEnd = 21 factorStepsize = 1 factorScale = 10.0 ## To scale up or down the factors # Load Model and set up the steady state solver. # model = sys.argv[1] # To load model from a file. model = './19085.cspace' modelPath, modelName, modelType = parseModelName(model) outputDir = modelPath modelId = moose.loadModel(model, 'model', 'ee') dosePath = '/model/kinetics/b/DabX' # The dose entity ksolve, state = setupSteadyState(simdt, plotDt) vol = moose.element('/model/kinetics').volume iterInit = 100 solutionVector = [] factorArr = [] enz = moose.element(dosePath) init = float(enz.kcat) # Dose parameter # Change Dose here to . for factor in range(factorBegin, factorEnd, factorStepsize): scale = factorExponent**(factor / factorScale) enz.kcat = init * scale print("scale={:.3f}\tkcat={:.3f}".format(scale, enz.kcat)) for num in range(iterInit): stateType, solStatus, a, vector = getState(ksolve, state, vol) if solStatus == 0: #solutionVector.append(vector[0]/sum(vector)) solutionVector.append(a) factorArr.append(scale) joint = np.array([factorArr, solutionVector]) joint = joint[:, joint[1, :].argsort()] # Plot dose response. Remove NaN from the values else plotting will fail. ax = plt.subplot() # plt.semilogx was failing. not sure why. That is why this convoluted # approach. ax.plot(joint[0, :], joint[1, :], marker="o", label='concA') ax.set_xscale('log') plt.xlabel('Dose') plt.ylabel('Response') plt.suptitle('Dose-Reponse Curve for a bistable system') plt.legend(loc=3) #plt.savefig(outputDir + "/" + modelName +"_doseResponse" + ".png") plt.show() quit()
def main(): # Setup parameters for simulation and plotting simdt= 1e-2 plotDt= 1 # Factors to change in the dose concentration in log scale factorExponent = 10 ## Base: ten raised to some power. factorBegin = -20 factorEnd = 21 factorStepsize = 1 factorScale = 10.0 ## To scale up or down the factors # Load Model and set up the steady state solver. # model = sys.argv[1] # To load model from a file. model = './19085.cspace' modelPath, modelName, modelType = parseModelName(model) outputDir = modelPath modelId = moose.loadModel(model, 'model', 'ee') dosePath = '/model/kinetics/b/DabX' # The dose entity ksolve, state = setupSteadyState( simdt, plotDt) vol = moose.element( '/model/kinetics' ).volume iterInit = 100 solutionVector = [] factorArr = [] enz = moose.element(dosePath) init = float(enz.kcat) # Dose parameter # Change Dose here to . for factor in range(factorBegin, factorEnd, factorStepsize ): scale = factorExponent ** (factor/factorScale) enz.kcat = init * scale print( "scale={:.3f}\tkcat={:.3f}".format( scale, enz.kcat) ) for num in range(iterInit): stateType, solStatus, a, vector = getState( ksolve, state, vol) if solStatus == 0: #solutionVector.append(vector[0]/sum(vector)) solutionVector.append(a) factorArr.append(scale) joint = np.array([factorArr, solutionVector]) joint = joint[:,joint[1,:].argsort()] # Plot dose response. Remove NaN from the values else plotting will fail. ax = plt.subplot() # plt.semilogx was failing. not sure why. That is why this convoluted # approach. ax.plot( joint[0,:], joint[1,:] , marker="o", label = 'concA') ax.set_xscale( 'log' ) plt.xlabel('Dose') plt.ylabel('Response') plt.suptitle('Dose-Reponse Curve for a bistable system') plt.legend(loc=3) #plt.savefig(outputDir + "/" + modelName +"_doseResponse" + ".png") plt.show() quit()
def load_neuron_file(fileName, cellPath, Rm, Ra, Cm, initVm): cell = moose.loadModel(fileName, cellPath) for child in cell[0].children: for comp in child: comp.Rm = Rm comp.Ra = Ra comp.Cm = Cm comp.initVm = initVm
def create_swc_model(root_name, file_name, RM, CM, RA, ELEAK, initVM): if file_name.endswith('.swc'): root_comp = moose.loadModel(file_name, root_name) else: raise ValueError("Please provide valid swc file as input.") for comp in moose.wildcardFind(root_comp.path+'/#[TYPE=Compartment]'): set_comp_values(comp, RM, CM, RA, initVM, ELEAK) return root_comp
def main(): # The wildcard uses # for single level, and ## for recursive. #compartment = makeModel() moose.loadModel('../Genesis_files/M1719.cspace', '/model', 'ee') compartment = moose.element('model/kinetics') compartment.name = 'compartment' ksolve = moose.Ksolve('/model/compartment/ksolve') stoich = moose.Stoich('/model/compartment/stoich') stoich.compartment = compartment stoich.ksolve = ksolve #ksolve.stoich = stoich stoich.path = "/model/compartment/##" state = moose.SteadyState('/model/compartment/state') moose.reinit() state.stoich = stoich #state.showMatrices() state.convergenceCriterion = 1e-7 moose.le('/model/graphs') a = moose.element('/model/compartment/a') b = moose.element('/model/compartment/b') c = moose.element('/model/compartment/c') for i in range(0, 100): getState(ksolve, state) moose.start(100.0) # Run the model for 100 seconds. b = moose.element('/model/compartment/b') c = moose.element('/model/compartment/c') # move most molecules over to b b.conc = b.conc + c.conc * 0.95 c.conc = c.conc * 0.05 moose.start(100.0) # Run the model for 100 seconds. # move most molecules back to a c.conc = c.conc + b.conc * 0.95 b.conc = b.conc * 0.05 moose.start(100.0) # Run the model for 100 seconds. # Iterate through all plots, dump their contents to data.plot. displayPlots() quit()
def main(): """ The script demonstates to convert Chemical (Genesis) file back to Genesis file using moose """ model = moose.loadModel(os.path.join( cwd, '../genesis/reaction.g'), '/model') written = moose.mooseWriteKkit('/model', 'testsave.g') print( written )
def main(): """ This example illustrates parameter tweaking. It uses a kinetic model for a relaxation oscillator, defined in kkit format. We use the gsl solver here. The model looks like this:: _________ | | V | M-----Enzyme---->M* All in compartment A |\ /| ^ | \___basal___/ | | | endo | | exo | _______ | | | \ | V V \ | M-----Enzyme---->M* All in compartment B \ /| \___basal___/ The way it works: We set the run off for a few seconds with the original model parameters. This version oscillates. Then we double the endo and exo forward rates and run it further to show that the period becomes nearly twice as fast. Then we restore endo and exo, and instead double the initial amounts of M. We run it further again to see what happens. This model takes several seconds to run. """ mfile = '../genesis/OSC_Cspace.g' runtime = 4000.0 modelId = moose.loadModel( mfile, 'model', 'gsl' ) moose.reinit() moose.start( runtime ) # Here begins the parameter tweaking. # Now we double the rates of the endo and exo reactions. endo = moose.element( '/model/kinetics/endo' ) endo.Kf *= 2.0 exo = moose.element( '/model/kinetics/exo' ) exo.Kf *= 2.0 moose.start( runtime ) # run it again # Now we restore rates, but double the total amount of M. endo.Kf /= 2.0 exo.Kf /= 2.0 M = moose.element( '/model/kinetics/A/M' ) M.conc += M.concInit # concInit was the starting concentration. moose.start( runtime ) # run it again # Now plot the whole lot. for x in moose.wildcardFind( '/model/#graphs/conc#/#' ): pylab.plot( x.vector, label=x.name ) pylab.legend() pylab.show()
def makeModel(): makeChannelPrototypes() cellId = moose.loadModel( 'dotp.p', '/model', 'Neutral' ) moose.element( '/model/soma' ).inject = 1.7e-9 graphs = moose.Neutral( '/graphs' ) addPlot( '/model/soma', 'getVm', 'somaVm' ) addPlot( '/model/apical_14', 'getVm', 'midVm' ) addPlot( '/model/lat_15_2', 'getVm', 'latVm' ) addPlot( '/model/apical_19', 'getVm', 'tipVm' )
def main(): # Setup parameters for simulation and plotting simdt= 1e-2 plotDt= 1 # Factors to change in the dose concentration in log scale factorExponent = 10 ## Base: ten raised to some power. factorBegin = -20 factorEnd = 21 factorStepsize = 1 factorScale = 10.0 ## To scale up or down the factors # Load Model and set up the steady state solver. # model = sys.argv[1] # To load model from a file. model = './19085.cspace' modelPath, modelName, modelType = parseModelName(model) outputDir = modelPath modelId = moose.loadModel(model, 'model', 'ee') dosePath = '/model/kinetics/b/DabX' # The dose entity ksolve, state = setupSteadyState( simdt, plotDt) vol = moose.element( '/model/kinetics' ).volume iterInit = 1000 solutionVector = [] factorArr = [] enz = moose.element(dosePath) init = enz.kcat # Dose parameter # Change Dose here to . for factor in range(factorBegin, factorEnd, factorStepsize ): scale = factorExponent ** (factor/factorScale) enz.kcat = init * scale print factor for num in range(iterInit): stateType, solStatus, vector = getState( ksolve, state, vol) if solStatus == 0: solutionVector.append(vector[0]/sum(vector)) factorArr.append(scale) joint = np.array([factorArr, solutionVector]) joint = joint[:,joint[1,:].argsort()] # Plot dose response. fig0 = plt.figure() pylab.semilogx(joint[0,:],joint[1,:],marker="o",label = 'concA') pylab.xlabel('Dose') pylab.ylabel('Response') pylab.suptitle('Dose-Reponse Curve for a bistable system') pylab.legend(loc=3) plt.savefig(outputDir + "/" + modelName +"_doseResponse" + ".png") plt.show() plt.close(fig0) quit()
def createMultiCompCell(file_name, container_name, library_name, comp_type, channelSet, condSet, rateParams, CaParams = None, CaPoolParams = None, HCNParams = None, cell_RM = None, cell_CM = None, cell_RA = None, cell_initVm = None, cell_Em = None): # Create the channel types and store them in a library to be used by each compartment # in the model createChanLib(library_name, channelSet, rateParams, CaParams, HCNParams) # Load in the model in question if file_name.endswith('.p'): cell = moose.loadModel(file_name, container_name) for comp in moose.wildcardFind(cell.path + '/' + '#[TYPE=' + comp_type + ']'): for chan_name, cond in condSet.items(): SA = np.pi*comp.length*comp.diameter proto = moose.element(library_name + '/' + chan_name) chan = moose.copy(proto, comp, chan_name)[0] chan.Gbar = cond*SA m = moose.connect(chan, 'channel', comp, 'channel') # Add the calcium pool to each compartment in the cell if it has been specified if (CaPoolParams != None): add_calcium(library_name, cell, CaPoolParams, comp_type) for key in channelSet.keys(): if ("Ca" in key): connect_cal2chan(channelSet[key].name, channelSet[key].chan_type, cell, CaPoolParams.caName, comp_type) else: cell = moose.loadModel(file_name, container_name) setCompParameters(cell, comp_type, cell_RM, cell_CM, cell_RA, cell_initVm, cell_Em) for comp in moose.wildcardFind(cell.path + '/' + '#[TYPE=' + comp_type + ']'): for chan_name, cond in condSet.items(): SA = np.pi*comp.length*comp.diameter proto = moose.element(library_name + '/' + chan_name) chan = moose.copy(proto, comp, chan_name)[0] chan.Gbar = cond*SA m = moose.connect(chan, 'channel', comp, 'channel') # Add the calcium pool to each compartment in the cell if it has been specified if (CaPoolParams != None): add_calcium(library_name, cell, CaPoolParams, comp_type) for key in channelSet.keys(): if ("Ca" in key): connect_cal2chan(channelSet[key].name, channelSet[key].chan_type, cell, CaPoolParams.caName, comp_type) return cell