def saveRecords(records, xvec=None, **kwargs): """saveRecords Given a dictionary of data with (key, numpy array) pair, it saves them to a file 'outfile' :param outfile :param dataDict: :param **kwargs: comment: Adds comments below the header. """ if len(records) == 0: pu.warn("No data in dictionary to save.") return False outfile = kwargs.get('outfile', 'data.moose') clock = moose.Clock('/clock') assert clock.currentTime > 0 yvecs = [] text = "time," + ",".join([str(x) for x in records]) for k in records: try: yvec = records[k].vector except AttributeError as e: yevc = records[k] yvecs.append(yvec) xvec = np.linspace(0, clock.currentTime, len(yvecs[0])) yvecs = [xvec] + yvecs if kwargs.get('comment', ''): text += ("\n" + kwargs['comment']) np.savetxt(outfile, np.array(yvecs).T, delimiter=',', header=text) pu.info("Done writing data to %s" % outfile)
def plotTables(tables, outfile=None, **kwargs): """Plot a list of tables onto one figure only. """ assert type(tables) == dict, "Expected a dict of moose.Table" plt.figure(figsize=(10, 1.5 * len(tables))) subplot = kwargs.get('subplot', True) for i, tname in enumerate(tables): if subplot: plt.subplot(len(tables), 1, i + 1) yvec = tables[tname].vector xvec = np.linspace(0, moose.Clock('/clock').currentTime, len(yvec)) plt.plot(xvec, yvec, label=tname) # This may not be available on older version of matplotlib. try: plt.legend(loc='best', framealpha=0.4) except: plt.legend(loc='best') plt.tight_layout() if outfile: pu.dump("PLOT", "Saving plots to file {}".format(outfile)) try: plt.savefig(outfile, transparent=True) except Exception as e: pu.dump("WARN", "Failed to save figure, plotting onto a window") plt.show() else: plt.show()
def main(): modelname = os.path.join(modeldir, './chem_models/00001-sbml-l3v1.xml' ) model = moose.mooseReadSBML( modelname, '/sbml' ) print( model ) c = moose.Clock('/clock') moose.reinit() moose.start(200) check( )
def make_plot(tables): clk = moose.Clock('/clock') t = clk.currentTime tvec = np.linspace(0, t, len(tables.values()[0].vector)) compts = sorted(tables.keys()) data = [tables[c].vector for c in compts] data = np.vstack(data) plt.plot(tvec, data[0, :]) plt.show()
def reformatTable(table, kwargs): """ Given a table return x and y vectors with proper scaling """ clock = moose.Clock('/clock') if type(table) == moose.Table: vecY = table.vector vecX = np.arange(0, clock.currentTime, len(vecY)) elif type(table) == tuple: vecX, vecY = table return (vecX, vecY)
def main(): modelname = os.path.join(modeldir, 'chem_models/mkp1_feedback_effects_acc4.xml') model = moose.readSBML(modelname, '/model') tables = moose.wildcardFind('/##[TYPE=Table2]') records = {} for t in tables: records[t.path.split('/')[-1]] = t c = moose.Clock('/clock') moose.reinit() moose.start(200) check(tables)
def updatePlots(self): for path, lines in list(self.pathToLine.items()): element = moose.element(path) if isinstance(element, moose.Table2): tab = moose.Table2(path) else: tab = moose.Table(path) data = tab.vector ts = np.linspace(0, moose.Clock('/clock').currentTime, len(data)) for line in lines: line.set_data(ts, data) self.canvas.draw()
def main( ): eeVec = loadAndRun( False ) hsolveVec = loadAndRun( True ) clk = moose.Clock( '/clock' ) print( '[DEBUG] Total entries %s' % len( eeVec )) t = np.linspace(0, clk.currentTime, len( eeVec )) plt.plot(t, eeVec, label = 'ee' ) plt.plot( t, hsolveVec, label = 'hsolve' ) outfile = '%s.png' % sys.argv[0] plt.legend( ) plt.savefig( outfile ) print( '[INFO] Wrote results to %s' % outfile ) return 1
def main(): modelname = './chem_models/mkp1_feedback_effects_acc4.xml' modelType = modelname.split(".")[-1] if modelType == "xml": model = moose.readSBML(modelname, '/model') else: raise IOError("Input is not XML model. Wrong extension %s" % modelType) tables = moose.wildcardFind('/##[TYPE=Table2]') records = {} for t in tables: records[t.path.split('/')[-1]] = t c = moose.Clock('/clock') moose.reinit() moose.start(200) check(tables)
def main( ): print( '[INFO] See the detailed issue in %s/hsolve' % d ) quit() eeVec = loadAndRun( False ) hsolveVec = loadAndRun( True ) clk = moose.Clock( '/clock' ) print( '[DEBUG] Total entries %s' % len( eeVec )) t = pl.linspace(0, clk.currentTime, len( eeVec )) pl.plot(t, eeVec, label = 'ee' ) pl.plot( t, hsolveVec, label = 'hsolve' ) outfile = '%s.png' % sys.argv[0] pl.legend( ) pl.savefig( outfile ) print( '[INFO] Wrote results to %s' % outfile ) pl.show()
def _time(npoints=None): import numpy if npoints is None: try: npoints = len(_plots[0].vec) except IndexError: raise SetupError( 'List of time-points cannot be constructed because ' 'no plots have been set up yet.') begin = 0.0 end = _moose.Clock('/clock').currentTime return numpy.linspace(begin, end, npoints)
def displayPlots(): clock = moose.Clock('/clock') # look up global clock totR = moose.element('/model/graphs/conc1/tot_PSD_R.Co') PP1 = moose.element('/model/moregraphs/conc4/PP1_dash_active.Co') Ca = moose.element('/model/graphs/conc1/Ca.Co') pylab.plot(pylab.linspace(0, clock.currentTime, len(totR.vector)), totR.vector, label='membrane Receptor') pylab.plot(pylab.linspace(0, clock.currentTime, len(PP1.vector)), PP1.vector, label='active PP1') pylab.plot(pylab.linspace(0, clock.currentTime, len(Ca.vector)), Ca.vector, label='Ca') pylab.legend() pylab.show()
def step_run(simtime, steptime, verbose=True): """Run the simulation in steps of `steptime` for `simtime`.""" clock = moose.Clock('/clock') if verbose: print 'Starting simulation for', simtime while clock.currentTime < simtime - steptime: moose.start(steptime) if verbose: print 'Simulated till', clock.currentTime, 's' remaining = simtime - clock.currentTime if remaining > 0: if verbose: print 'Running the remaining', remaining, 's' moose.start(remaining) if verbose: print 'Finished simulation'
def example(): directory = os.path.dirname(granule.__file__) current = os.getcwd() os.chdir(directory) start_time = datetime.now() granule.loadGran98NeuroML_L123(granule.filename) soma_path = '/cells[0]/Gran_0[0]/Soma_0[0]' ca = moose.element('{}/Gran_CaPool_98/data/somaCa'.format(soma_path)) vm = moose.element('{}/data[0]/somaVm[0]'.format(soma_path)) os.chdir(current) writer = nsdf.NSDFWriter('granulecell_incremental.h5', mode='w', compression='gzip') writer.add_model_filecontents([directory]) ca_data = nsdf.UniformData('Ca', unit='mM', dt=granule.plotdt, tunit='s') ca_data.put_data(soma_path, ca.vector) source_ds = writer.add_uniform_ds('GranuleSoma', [soma_path]) writer.add_uniform_data(source_ds, ca_data) vm_data = nsdf.UniformData('Vm', unit='V', dt=granule.plotdt, tunit='s') vm_data.put_data(soma_path, vm.vector) writer.add_uniform_data(source_ds, vm_data) writer.title = 'Sample NSDF file for olfactory bulb granule cell model' writer.description = 'This file stores the entire model' \ ' directory in `/model/filecontent`' writer.tstart = start_time writer.creator = [os.environ['USER']] writer.contributor = ['Subhasis Ray', 'Aditya Gilra'] writer.license = 'CC BY-SA' writer.software = ['Python2.7', 'moose', 'nsdf python library'] writer.method = ['exponential Euler'] clock = moose.Clock('/clock') time_increment = 100 * granule.plotdt while clock.currentTime < runtime: print 'Run till', clock.currentTime vm.clearVec() ca.clearVec() to_run = time_increment if clock.currentTime + time_increment > runtime: to_run = runtime - clock.currentTime moose.start(to_run) vm_data.put_data(soma_path, vm.vector) writer.add_uniform_data(source_ds, vm_data) ca_data.put_data(soma_path, ca.vector) writer.add_uniform_data(source_ds, ca_data) end_time = datetime.now() writer.tend = end_time print 'Finished writing example NSDF file for GranuleCell demo'
def loadedModelsAction(self,modelPath,pluginName): #Harsha: added under file Menu, Recently Loaded Models #All the previously loaded chemical models, solver's and table's ticks are made -1 for model in self._loadedModels: self.disableModel(model[0]) action = QAction(modelPath[1:],self) action.triggered.connect(lambda : self.setPlugin(pluginName, modelPath)) compt = moose.wildcardFind(modelPath + '/##[ISA=ChemCompt]') c = moose.Clock('/clock') self.simulationdt = c.tickDt[7] self.plotdt = c.tickDt[8] if compt: self.simulationdt = c.tickDt[11] self.plotdt = c.tickDt[16] self._loadedModels.append([modelPath,pluginName,action,self.simulationdt,self.plotdt]) if len(self._loadedModels)>5: self._loadedModels.pop(0)
def writeSimulationAnnotation(modelpath): modelAnno = "" plots = "" if moose.exists(modelpath + '/info'): mooseclock = moose.Clock('/clock') modelAnno = "<moose:ModelAnnotation>\n" modelAnnotation = moose.element(modelpath + '/info') modelAnno = modelAnno + "<moose:runTime> " + \ str(modelAnnotation.runtime) + " </moose:runTime>\n" modelAnno = modelAnno + "<moose:solver> " + \ modelAnnotation.solver + " </moose:solver>\n" modelAnno = modelAnno + "<moose:simdt>" + \ str(mooseclock.dts[12]) + " </moose:simdt>\n" modelAnno = modelAnno + "<moose:plotdt> " + \ str(mooseclock.dts[18]) + " </moose:plotdt>\n" plots = "" graphs = moose.wildcardFind(modelpath + "/##[TYPE=Table2]") for gphs in range(0, len(graphs)): gpath = graphs[gphs].neighbors['requestOut'] if len(gpath) != 0: q = moose.element(gpath[0]) ori = q.path name = convertSpecialChar(q.name) graphSpefound = False while not (isinstance(moose.element(q), moose.CubeMesh)): q = q.parent graphSpefound = True if graphSpefound: if not plots: plots = ori[ori.find(q.name) - 1:len(ori)] #plots = '/' + q.name + '/' + name else: plots = plots + "; " + ori[ori.find(q.name) - 1:len(ori)] #plots = plots + "; /" + q.name + '/' + name if plots != " ": modelAnno = modelAnno + "<moose:plots> " + plots + "</moose:plots>\n" modelAnno = modelAnno + "</moose:ModelAnnotation>" return modelAnno
def plotVector(vec, xvec=None, **options): """plotVector: Plot a given vector. On x-axis, plot the time. :param vec: Given vector. :param **kwargs: Optional to pass to maplotlib. """ assert type(vec) == np.ndarray, "Expected type %s" % type(vec) legend = options.get('legend', True) if xvec is None: clock = moose.Clock('/clock') xx = np.linspace(0, clock.currentTime, len(vec)) else: xx = xvec[:] assert len(xx) == len(vec), "Expecting %s got %s" % (len(vec), len(xvec)) plt.plot(xx, vec, label=options.get('label', '')) if legend: # This may not be available on older version of matplotlib. try: plt.legend(loc='best', framealpha=0.4) except: plt.legend(loc='best') if xvec is None: plt.xlabel('Time (sec)') else: plt.xlabel(options.get('xlabel', '')) plt.ylabel = options.get('ylabel', '') plt.title(options.get('title', '')) if (options.get('legend', True)): try: plt.legend(loc='best', framealpha=0.4, prop={'size': 9}) except: plt.legend(loc='best', prop={'size': 9})
def plotTables(tables, outfile=None, **kwargs): """Plot a dict of tables. Each axis will be labeled with dict keys. The dict values must be moose.Table/moose.Table2. :param outfile: Default `None`. If given, plot will be saved to this filepath. :param grid: A tuple with (cols, rows), default is (len(tables)//2+1, 2) :param figsize: Size of figure (W, H) in inches. Default (10, 1.5*len(tables)) """ assert type(tables) == dict, "Expected a dict of moose.Table" plt.figure(figsize=kwargs.get('figsize', (10, 1.5 * len(tables)))) subplot = kwargs.get('subplot', True) gridSize = kwargs.get('grid', (len(tables) // 2 + 1, 2)) for i, tname in enumerate(tables): if subplot: assert gridSize[0] <= 9 plt.subplot(100 * gridSize[0] + 10 * gridSize[1] + (i + 1)) yvec = tables[tname].vector xvec = np.linspace(0, moose.Clock('/clock').currentTime, len(yvec)) plt.plot(xvec, yvec, label=tname) # This may not be available on older version of matplotlib. try: plt.legend(loc='best', framealpha=0.4) except: plt.legend(loc='best') plt.tight_layout() if outfile: pu.dump("PLOT", "Saving plots to file {}".format(outfile)) try: plt.savefig(outfile, transparent=True) except Exception as e: pu.dump("WARN", "Failed to save figure. Errror %s" % e) plt.show() else: plt.show()
def run_simulation(self): # Setup data recording data = moose.Neutral('/data') Vm = moose.Table('/data/Vm') moose.connect(Vm, 'requestData', self.compartments[0], 'get_Vm') # Now schedule the sequence of operations and time resolutions moose.setClock(0, self.dt) moose.setClock(1, self.dt) moose.setClock(2, self.dt) moose.setClock(3, self.dt) moose.setClock(4, self.dt) #quite a hack: current_clamp = self.current_clamp # useClock: First argument is clock no. # Second argument is a wildcard path matching all elements of type Compartment # Last argument is the processing function to be executed at each tick of clock 0 moose.useClock(0, '/model/#[TYPE=Compartment]', 'init') moose.useClock(1, '/model/#[TYPE=Compartment]', 'process') moose.useClock(2, Vm.path, 'process') moose.useClock(3, current_clamp.path, 'process') moose.useClock(4, '/model/#/#[TYPE=HHChannel]', 'process') # Now initialize everything and get set moose.reinit() moose.start(self.sim_time) #handle to the global clock: clock = moose.Clock('/clock') #vectors: self.rec_v = Vm.vec self.t_final = clock.currentTime
# Now initialize everything and get set moose.reinit() # Here we take a simple approach to try current injection experiemnt: # Run the simulation for some time. Then set the `inject` field of the # soma to a positive value and run for some more time. This will # emulate a current injection for that duration. Finally, remove the # current injection by setting the `inject` field back to 0 and run # for some more time to get the discharging curve. # Normally you should use a PulseGen object for this instead of # stopping the simulation midway to set the inject field.. moose.start(50e-3) # Now apply 1 pA current injection to soma soma.inject = 1e-12 # Run for 100 ms moose.start(100e-3) # Stop the current injection soma.inject = 0.0 # Run for 500 ms moose.start(500e-3) clock = moose.Clock('/clock') # Get a handle to the global clock pylab.plot(pylab.linspace(0, clock.currentTime, len(axon_Vm.vector)), axon_Vm.vector, label='Vm of axon') pylab.legend() pylab.show() # # compartmental_neuron.py ends here
def setPlugin(self, name, root='/'): """Set the current plugin to use. This - 1. sets the `plugin` attribute. 2. updates menus by clearing and reinstating menus including anything provided by the plugin. 3. sets the current view to the plugins editor view. """ busyCursor() for model in self._loadedModels: self.disableModel(model[0]) for i in range(0, len(self._loadedModels)): if self._loadedModels[i][0]== root: c = moose.Clock('/clock') compt = moose.wildcardFind(root+'/##[ISA=ChemCompt]') if compt: c.tickDt[11] = self._loadedModels[i][3] c.tickDt[16] = self._loadedModels[i][4] if moose.exists(compt[0].path+'/ksolve'): ksolve = moose.Ksolve( compt[0].path+'/ksolve' ) ksolve.tick = 16 if moose.exists(compt[0].path+'/gsolve'): gsolve = moose.Gsolve( compt[0].path+'/gsolve' ) gsolve.tick = 16 for x in moose.wildcardFind( root+'/data/graph#/#' ): x.tick = 18 else: c.tickDt[7] = self._loadedModels[i][3] c.tickDt[8] = self._loadedModels[i][4] neurons = moose.wildcardFind(root + "/model/cells/##[ISA=Neuron]") for neuron in neurons: #print(neuron) solver = moose.element(neuron.path + "/hsolve") # print("Disabling => ", solver) solver.tick = 7 for x in moose.wildcardFind( root+'/data/graph#/#' ): x.tick = 8 break self.plugin = self.loadPluginClass(str(name))(str(root), self) moose.reinit() # if root != '/' and root not in self._loadedModels: # self._loadedModels[root] = name # for k,v in self._loadedModels.items(): # compt = moose.wildcardFind(k+'/##[ISA=ChemCompt]') # if compt: # if moose.exists(compt[0].path+'/ksolve'): # ksolve = moose.Ksolve( compt[0].path+'/ksolve' ) # ksolve.tick = -1 # if moose.exists(compt[0].path+'/stoich'): # stoich = moose.Stoich( compt[0].path+'/stoich' ) # stoich.tick = -1 # for x in moose.wildcardFind( k+'/data/graph#/#' ): # x.tick = -1 # if root != '/' and root not in self._loadedModels: # self._loadedModels[root] = name # try: # self.plugin = self._plugins[str(name)] # print 'PLUGIN', self.plugin # self.plugin.setModelRoot(root) # except KeyError: # self.plugin = self.loadPluginClass(str(name))(str(root), self) # self._plugins[str(name)] = self.plugin #self.plugin.getEditorView().getCentralWidget().editObject.connect(self.objectEditSlot, QtCore.Qt.UniqueConnection) self.updateMenus() for action in self.pluginsMenu.actions(): if str(action.text()) == str(name): action.setChecked(True) elif action.isChecked(): action.setChecked(False) for subwin in self.mdiArea.subWindowList(): subwin.close() if name != "default" : self.setCurrentView('editor') self.setCurrentView('run') if name == 'kkit': self.objectEditDockWidget.objectNameChanged.connect(self.plugin.getEditorView().getCentralWidget().updateItemSlot) self.objectEditDockWidget.colorChanged.connect(self.plugin.getEditorView().getCentralWidget().updateColorSlot) self.setCurrentView('editor') freeCursor() return self.plugin
def addTimeSeries(self, table, *args, **kwargs): ts = np.linspace(0, moose.Clock('/clock').currentTime, len(table.vector)) return self.canvas.plot(ts, table.vector, *args, **kwargs)
def plotAllData(self): """Plot data from existing tables""" self.axesRef.lines = [] self.pathToLine.clear() self.removeSubmenu.clear() if self.legend is not None: self.legend.set_visible(False) path = self.model.path modelroot = self.model.path time = moose.Clock('/clock').currentTime tabList = [] #for tabId in moose.wildcardFind('%s/##[TYPE=Table]' % (path)): #harsha: policy graphs will be under /model/modelName need to change in kkit #for tabId in moose.wildcardFind('%s/##[TYPE=Table]' % (modelroot)): plotTables = list( moose.wildcardFind(self.graph.path + '/##[TYPE=Table]')) plotTables.extend( moose.wildcardFind(self.graph.path + '/##[TYPE=Table2]')) if len(plotTables) > 0: for tabId in plotTables: tab = moose.Table(tabId) #print("Table =>", tab) line_list = [] tableObject = tab.neighbors['requestOut'] # Not a good way #tableObject.msgOut[0] if len(tableObject) > 0: # This is the default case: we do not plot the same # table twice. But in special cases we want to have # multiple variations of the same table on different # axes. # #Harsha: Adding color to graph for signalling model, check if given path has cubemesh or cylmesh color = '#FFFFFF' if moose.exists(tableObject[0].path + '/info'): color = getColor(tableObject[0].path + '/info') color = str(color[1].name()).upper() lines = self.pathToLine[tab.path] if len(lines) == 0: #Harsha: pass color for plot if exist and not white else random color #print "tab in plotAllData ",tab, tab.path,tab.name field = tab.path.rpartition(".")[-1] if field.endswith("[0]") or field.endswith("_0_"): field = field[:-3] # label = ( tableObject[0].path.partition(self.model.path + "/model[0]/")[-1] # + "." # + field # ) label = (tableObject[0].path.rpartition("/")[-1] + "." + field) self.makeRemovePlotAction(label, tab) if (color != '#FFFFFF'): newLines = self.addTimeSeries(tab, label=label, color=color) else: newLines = self.addTimeSeries(tab, label=label) self.pathToLine[tab.path].update(newLines) for line in newLines: self.lineToDataSource[line] = PlotDataSource( x='/clock', y=tab.path, z='') else: for line in lines: dataSrc = self.lineToDataSource[line] xSrc = moose.element(dataSrc.x) ySrc = moose.element(dataSrc.y) if isinstance(xSrc, moose.Clock): ts = np.linspace(0, time, len(tab.vector)) elif isinstance(xSrc, moose.Table): ts = xSrc.vector.copy() line.set_data(ts, tab.vector.copy()) tabList.append(tab) # if len(tabList) > 0: self.legend = self.canvas.callAxesFn( 'legend', loc='upper right', prop={'size': 10} # , bbox_to_anchor=(1.0, 0.5) , fancybox=True, shadow=False, ncol=1) if self.legend is not None: self.legend.draggable() self.legend.get_frame().set_alpha(0.5) self.legend.set_visible(True) self.canvas.draw()
def updateCurrentTime(self): sys.stdout.flush() self.currentTimeWidget.dispay(str(moose.Clock('/clock').currentTime))