def clear(erase=True, all=False): ''' Clears all Brian objects. Specifically, it stops all existing Brian objects from being collected by :class:`MagicNetwork` (objects created after clearing will still be collected). If ``erase`` is ``True`` then it will also delete all data from these objects. This is useful in, for example, ``ipython`` which stores persistent references to objects in any given session, stopping the data and memory from being freed up. If ``all=True`` then all Brian objects will be cleared. See also :func:`forget`. ''' if all is False: net = MagicNetwork(level=2) objs = net.groups + net.connections + net.operations else: groups, _ = magic.find_instances(NeuronGroup, all=True) connections, _ = magic.find_instances(Connection, all=True) operations, _ = magic.find_instances(NetworkOperation, all=True) objs = groups+connections+operations for o in objs: o.set_instance_id(-1) if erase: for k, v in o.__dict__.iteritems(): object.__setattr__(o, k, None) gc.collect()
def clear(erase=True, all=False): ''' Clears all Brian objects. Specifically, it stops all existing Brian objects from being collected by :class:`MagicNetwork` (objects created after clearing will still be collected). If ``erase`` is ``True`` then it will also delete all data from these objects. This is useful in, for example, ``ipython`` which stores persistent references to objects in any given session, stopping the data and memory from being freed up. If ``all=True`` then all Brian objects will be cleared. See also :func:`forget`. ''' if all is False: net = MagicNetwork(level=2) objs = net.groups + net.connections + net.operations else: groups, _ = magic.find_instances(NeuronGroup, all=True) connections, _ = magic.find_instances(Connection, all=True) operations, _ = magic.find_instances(NetworkOperation, all=True) objs = groups + connections + operations for o in objs: o.set_instance_id(-1) if erase: for k, v in o.__dict__.iteritems(): object.__setattr__(o, k, None) gc.collect()
def __init__(self, verbose=False, level=1): ''' Set verbose=False to turn off comments. The level variable contains the location of the namespace. ''' (groups, groupnames) = magic.find_instances(NeuronGroup) groups = [g for g in groups if g._owner is g] groupnames = [gn for g, gn in zip(groups, groupnames) if g._owner is g] (connections, connectionnames) = magic.find_instances(Connection) (operations, operationnames) = magic.find_instances(NetworkOperation) if verbose: print "[MagicNetwork] Groups:", groupnames print "[MagicNetwork] Connections:", connectionnames print "[MagicNetwork] Operations:", operationnames # Use set() to discard duplicates Network.__init__(self, list(set(groups)), list(set(connections)), list(set(operations)))
def hist_plot(histmon=None, **plotoptions): """Plot a histogram **Usage** ``hist_plot(histmon,options...)`` Plot the given histogram monitor ``hist_plot(options...)`` Guesses which histogram monitor to use with argument: ``histmon`` is a monitor of histogram type **Notes** Plots only the first n-1 of n bars in the histogram, because the nth bar is for the interval (-,infinity). **Options** Any of PyLab options for bar can be given, as well as: ``showplot=False`` set to ``True`` to run pylab's ``show()`` function ``newfigure=True`` set to ``False`` not to create a new figure with pylab's ``figure()`` function ``xlabel`` label for the x-axis ``ylabel`` label for the y-axis ``title`` title for the plot """ if histmon is None: (histmons, histmonnames) = magic.find_instances(HistogramMonitorBase) if len(histmons) == 0: raise TypeError, "No histogram monitors found." elif len(histmons) > 1: log_info("brian.hist_plot", "Found more than one histogram monitor, using first one.") histmon = histmons[0] # OPTIONS # Defaults myopts = {"title": "", "xlabel": "Time (ms)", "ylabel": "Count", "showplot": False, "newfigure": True} # User options _take_options(myopts, plotoptions) # PLOTTING ROUTINE if myopts["newfigure"]: pylab.figure() pylab.bar(histmon.bins[:-1] / ms, histmon.count[:-1], (histmon.bins[1:] - histmon.bins[:-1]) / ms, **plotoptions) pylab.ylabel(myopts["ylabel"]) pylab.xlabel(myopts["xlabel"]) pylab.title(myopts["title"]) if myopts["showplot"]: pylab.show()
def hist_plot(histmon=None, **plotoptions): """Plot a histogram **Usage** ``hist_plot(histmon,options...)`` Plot the given histogram monitor ``hist_plot(options...)`` Guesses which histogram monitor to use with argument: ``histmon`` is a monitor of histogram type **Notes** Plots only the first n-1 of n bars in the histogram, because the nth bar is for the interval (-,infinity). **Options** Any of PyLab options for bar can be given, as well as: ``showplot=False`` set to ``True`` to run pylab's ``show()`` function ``newfigure=True`` set to ``False`` not to create a new figure with pylab's ``figure()`` function ``xlabel`` label for the x-axis ``ylabel`` label for the y-axis ``title`` title for the plot """ if histmon is None: (histmons, histmonnames) = magic.find_instances(HistogramMonitorBase) if len(histmons) == 0: raise TypeError, "No histogram monitors found." elif len(histmons) > 1: log_info('brian.hist_plot', "Found more than one histogram monitor, using first one.") histmon = histmons[0] # OPTIONS # Defaults myopts = {"title":"", "xlabel":"Time (ms)", "ylabel":"Count", "showplot":False, 'newfigure':True } # User options _take_options(myopts, plotoptions) # PLOTTING ROUTINE if myopts['newfigure']: pylab.figure() pylab.bar(histmon.bins[:-1] / ms, histmon.count[:-1], (histmon.bins[1:] - histmon.bins[:-1]) / ms, **plotoptions) pylab.ylabel(myopts['ylabel']) pylab.xlabel(myopts['xlabel']) pylab.title(myopts["title"]) if myopts["showplot"]: pylab.show()
def guess_clock(clock=None): ''' Tries to guess the clock from global and local namespaces from the caller. Selects the most local clock. Raises an error if several clocks coexist in the same namespace. If a non-None clock is passed, then it is returned (simplifies the code). ''' if clock: return clock # Get variables from the stack (clocks, clocknames) = magic.find_instances(Clock) if len(clocks) > 1: # several clocks: ambiguous # What type of error? raise TypeError("Clock is ambiguous. Please specify it explicitly.") if len(clocks) == 1: return clocks[0] # Fall back on default clock if exists_global_preference('defaultclock'): return get_global_preference('defaultclock') # No clock found raise TypeError("No clock found. Please define a clock.")
def raster_plot(*monitors, **additionalplotoptions): """Raster plot of a :class:`SpikeMonitor` **Usage** ``raster_plot(monitor,options...)`` Plots the spike times of the monitor on the x-axis, and the neuron number on the y-axis ``raster_plot(monitor0,monitor1,...,options...)`` Plots the spike times for all the monitors given, with y-axis defined by placing a spike from neuron n of m in monitor i at position i+n/m ``raster_plot(options...)`` Guesses the monitors to plot automagically **Options** Any of PyLab options for the ``plot`` command can be given, as well as: ``showplot=False`` set to ``True`` to run pylab's ``show()`` function ``newfigure=False`` set to ``True`` to create a new figure with pylab's ``figure()`` function ``xlabel`` label for the x-axis ``ylabel`` label for the y-axis ``title`` title for the plot ``showgrouplines=False`` set to ``True`` to show a line between each monitor ``grouplinecol`` colour for group lines ``spacebetweengroups`` value between 0 and 1 to insert a space between each group on the y-axis ``refresh`` Specify how often (in simulation time) you would like the plot to refresh. Note that this will only work if pylab is in interactive mode, to ensure this call the pylab ``ion()`` command. ``showlast`` If you are using the ``refresh`` option above, plots are much quicker if you specify a fixed time window to display (e.g. the last 100ms). ``redraw`` If you are using more than one realtime monitor, only one of them needs to issue a redraw command, therefore set this to ``False`` for all but one of them. Note that with some IDEs, interactive plotting will not work with the default matplotlib backend, try doing something like this at the beginning of your script (before importing brian):: import matplotlib matplotlib.use('WXAgg') You may need to experiment, try WXAgg, GTKAgg, QTAgg, TkAgg. """ if len(monitors) == 0: (monitors, monitornames) = magic.find_instances(SpikeMonitor) if len(monitors): # OPTIONS # Defaults myopts = { "title": "", "xlabel": "Time (ms)", "showplot": False, "showgrouplines": False, "spacebetweengroups": 0.0, "grouplinecol": "k", 'newfigure': False, 'refresh': None, 'showlast': None, 'redraw': True } plotoptions = {'mew': 0} if len(monitors) == 1: myopts["ylabel"] = 'Neuron number' else: myopts["ylabel"] = 'Group number' # User options _take_options(myopts, additionalplotoptions) plotoptions.update(additionalplotoptions) # PLOTTING ROUTINE spacebetween = myopts['spacebetweengroups'] class SecondTupleArray(object): def __init__(self, obj): self.obj = obj def __getitem__(self, i): return float(self.obj[i][1]) def __len__(self): return len(self.obj) def get_plot_coords(tmin=None, tmax=None): allsn = [] allst = [] for i, m in enumerate(monitors): mspikes = m.spikes if tmin is not None and tmax is not None: x = SecondTupleArray(mspikes) imin = bisect.bisect_left(x, tmin) imax = bisect.bisect_right(x, tmax) mspikes = mspikes[imin:imax] if len(mspikes): sn, st = array(mspikes).T else: sn, st = array([]), array([]) st /= ms if len(monitors) == 1: allsn = [sn] else: allsn.append(i + ( (1. - spacebetween) / float(len(m.source))) * sn) allst.append(st) sn = hstack(allsn) st = hstack(allst) if len(monitors) == 1: nmax = len(monitors[0].source) else: nmax = len(monitors) return st, sn, nmax st, sn, nmax = get_plot_coords() if myopts['newfigure']: pylab.figure() if myopts['refresh'] is None: line, = pylab.plot(st, sn, '.', **plotoptions) else: line, = pylab.plot([], [], '.', **plotoptions) if myopts['refresh'] is not None: pylab.axis(ymin=0, ymax=nmax) if myopts['showlast'] is not None: pylab.axis(xmin=-myopts['showlast'] / ms, xmax=0) ax = pylab.gca() if myopts['showgrouplines']: for i in range(len(monitors)): pylab.axhline(i, color=myopts['grouplinecol']) pylab.axhline(i + (1 - spacebetween), color=myopts['grouplinecol']) pylab.ylabel(myopts['ylabel']) pylab.xlabel(myopts['xlabel']) pylab.title(myopts["title"]) if myopts["showplot"]: pylab.show() if myopts['refresh'] is not None: @network_operation(clock=EventClock(dt=myopts['refresh'])) def refresh_raster_plot(clk): if matplotlib.is_interactive(): if myopts['showlast'] is None: st, sn, nmax = get_plot_coords() line.set_xdata(st) line.set_ydata(sn) ax.set_xlim(0, amax(st)) else: st, sn, nmax = get_plot_coords( clk._t - float(myopts['showlast']), clk._t) ax.set_xlim((clk.t - myopts['showlast']) / ms, clk.t / ms) line.set_xdata(array(st)) line.set_ydata(sn) if myopts['redraw']: pylab.draw() pylab.get_current_fig_manager().canvas.flush_events() monitors[0].contained_objects.append(refresh_raster_plot)
def raster_plot(*monitors, **additionalplotoptions): """Raster plot of a :class:`SpikeMonitor` **Usage** ``raster_plot(monitor,options...)`` Plots the spike times of the monitor on the x-axis, and the neuron number on the y-axis ``raster_plot(monitor0,monitor1,...,options...)`` Plots the spike times for all the monitors given, with y-axis defined by placing a spike from neuron n of m in monitor i at position i+n/m ``raster_plot(options...)`` Guesses the monitors to plot automagically **Options** Any of PyLab options for the ``plot`` command can be given, as well as: ``showplot=False`` set to ``True`` to run pylab's ``show()`` function ``newfigure=False`` set to ``True`` to create a new figure with pylab's ``figure()`` function ``xlabel`` label for the x-axis ``ylabel`` label for the y-axis ``title`` title for the plot ``showgrouplines=False`` set to ``True`` to show a line between each monitor ``grouplinecol`` colour for group lines ``spacebetweengroups`` value between 0 and 1 to insert a space between each group on the y-axis ``refresh`` Specify how often (in simulation time) you would like the plot to refresh. Note that this will only work if pylab is in interactive mode, to ensure this call the pylab ``ion()`` command. ``showlast`` If you are using the ``refresh`` option above, plots are much quicker if you specify a fixed time window to display (e.g. the last 100ms). ``redraw`` If you are using more than one realtime monitor, only one of them needs to issue a redraw command, therefore set this to ``False`` for all but one of them. Note that with some IDEs, interactive plotting will not work with the default matplotlib backend, try doing something like this at the beginning of your script (before importing brian):: import matplotlib matplotlib.use('WXAgg') You may need to experiment, try WXAgg, GTKAgg, QTAgg, TkAgg. """ if len(monitors) == 0: (monitors, monitornames) = magic.find_instances(SpikeMonitor) if len(monitors): # OPTIONS # Defaults myopts = { "title": "", "xlabel": "Time (ms)", "showplot": False, "showgrouplines": False, "spacebetweengroups": 0.0, "grouplinecol": "k", "newfigure": False, "refresh": None, "showlast": None, "redraw": True, } plotoptions = {"mew": 0} if len(monitors) == 1: myopts["ylabel"] = "Neuron number" else: myopts["ylabel"] = "Group number" # User options _take_options(myopts, additionalplotoptions) plotoptions.update(additionalplotoptions) # PLOTTING ROUTINE spacebetween = myopts["spacebetweengroups"] class SecondTupleArray(object): def __init__(self, obj): self.obj = obj def __getitem__(self, i): return float(self.obj[i][1]) def __len__(self): return len(self.obj) def get_plot_coords(tmin=None, tmax=None): allsn = [] allst = [] for i, m in enumerate(monitors): mspikes = m.spikes if tmin is not None and tmax is not None: x = SecondTupleArray(mspikes) imin = bisect.bisect_left(x, tmin) imax = bisect.bisect_right(x, tmax) mspikes = mspikes[imin:imax] if len(mspikes): sn, st = array(mspikes).T else: sn, st = array([]), array([]) st /= ms if len(monitors) == 1: allsn = [sn] else: allsn.append(i + ((1.0 - spacebetween) / float(len(m.source))) * sn) allst.append(st) sn = hstack(allsn) st = hstack(allst) if len(monitors) == 1: nmax = len(monitors[0].source) else: nmax = len(monitors) return st, sn, nmax st, sn, nmax = get_plot_coords() if myopts["newfigure"]: pylab.figure() if myopts["refresh"] is None: line, = pylab.plot(st, sn, ".", **plotoptions) else: line, = pylab.plot([], [], ".", **plotoptions) if myopts["refresh"] is not None: pylab.axis(ymin=0, ymax=nmax) if myopts["showlast"] is not None: pylab.axis(xmin=-myopts["showlast"] / ms, xmax=0) ax = pylab.gca() if myopts["showgrouplines"]: for i in range(len(monitors)): pylab.axhline(i, color=myopts["grouplinecol"]) pylab.axhline(i + (1 - spacebetween), color=myopts["grouplinecol"]) pylab.ylabel(myopts["ylabel"]) pylab.xlabel(myopts["xlabel"]) pylab.title(myopts["title"]) if myopts["showplot"]: pylab.show() if myopts["refresh"] is not None: @network_operation(clock=EventClock(dt=myopts["refresh"])) def refresh_raster_plot(clk): if matplotlib.is_interactive(): if myopts["showlast"] is None: st, sn, nmax = get_plot_coords() line.set_xdata(st) line.set_ydata(sn) ax.set_xlim(0, amax(st)) else: st, sn, nmax = get_plot_coords(clk._t - float(myopts["showlast"]), clk._t) ax.set_xlim((clk.t - myopts["showlast"]) / ms, clk.t / ms) line.set_xdata(array(st)) line.set_ydata(sn) if myopts["redraw"]: pylab.draw() pylab.get_current_fig_manager().canvas.flush_events() monitors[0].contained_objects.append(refresh_raster_plot)