### Brian 2 Configuration File Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/preferences.rst An example of a Brian 2 configuration file, which is placed in the current, user, or installation directory. This sets the C++ compiler preference. ```python codegen.cpp.compiler = 'gcc' ``` -------------------------------- ### Install Brian2 with Pip Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/import.rst Recommended installation command using pip to ensure compatible dependencies are installed. ```bash pip install brian2 ``` -------------------------------- ### Install Pip if Missing Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst In rare cases, you might need to install pip first using this command. ```bash python -m ensurepip ``` -------------------------------- ### Brian 1 Configuration File Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/preferences.rst An example of a Brian 1 global configuration file (`brian_global_config.py`) that sets preferences. ```python from brian.globalprefs import * set_global_preferences(weavecompiler='gcc') ``` -------------------------------- ### Install Brian2 with pip Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Use pip to install or upgrade Brian2. This is the standard method for most users. ```bash python -m pip install -U brian2 ``` -------------------------------- ### Example: Section Morphology Creation Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/multicompartmental.rst This example illustrates creating a Section morphology, allowing individual definition of length and diameter for each compartment at its start and end. ```python # Length and diameter individually defined for each compartment (at start # and end) Section(n=5, diameter=[15, 5, 10, 5, 10, 5]*um, length=[10, 20, 5, 5, 10]*um) ``` -------------------------------- ### Install Brian2 development version from TestPyPI Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install the latest development version of Brian2 from PyPI's test server. Ensure all dependencies are already installed. ```bash python -m pip install --upgrade --pre -i https://test.pypi.org/simple/ Brian2 ``` -------------------------------- ### Install Brian2 development version from GitHub Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install the latest development version of Brian2 directly from its GitHub repository using pip. ```bash python -m pip install git+https://github.com/brian-team/brian2.git ``` -------------------------------- ### Install brian2tools with pip Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install the brian2tools package using pip. ```bash python -m pip install brian2tools ``` -------------------------------- ### Development install Brian2 from local clone Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 in development mode from a local git clone. This allows direct code contributions and testing. ```bash pip install -e . ``` -------------------------------- ### Install Brian2 with Pip Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 using pip from the Python Package Index. It's recommended to use a virtual environment. ```bash python -m pip install brian2 ``` -------------------------------- ### Install supplementary packages with pip Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install useful packages like matplotlib, pytest, and ipython/jupyter using pip. ```bash python -m pip install matplotlib pytest ipython notebook ``` -------------------------------- ### Example of Doctest Usage Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/guidelines/testing.rst This example demonstrates how to write a doctest by including executable code within the 'Examples' block of documentation. It shows a simple expression. ```python >>> from brian2.utils.stringtools import word_substitute >>> expr = 'a*_b+c5+8+f(A)' ``` -------------------------------- ### Install Brian2 on Fedora Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 using the dnf package manager on Fedora Linux. ```bash sudo dnf install python-brian2 ``` -------------------------------- ### Install Brian2 on Ubuntu/Debian Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 using the apt package manager on Debian-based Linux distributions. ```bash sudo apt install python3-brian ``` -------------------------------- ### Preference File Format Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/preferences.rst Illustrates the format of preference files, showing how to set preferences using dotted names and section headers. Comments are supported. ```ini a.b.c = 1 # Comment line [a] b.d = 2 [a.b] b.e = 3 ``` -------------------------------- ### Example NeuronGroup Initialization Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/guidelines/defensive_programming.rst Illustrates a standard initialization of a NeuronGroup. This serves as a baseline for testing input validation. ```python NeuronGroup(N, eqs, reset='V>Vt') ``` -------------------------------- ### Install Brian2 on Ubuntu/Debian Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 using the apt package manager on Ubuntu or Debian systems. The package is automatically updated with system upgrades. ```bash sudo apt update sudo apt install python3-brian ``` -------------------------------- ### Example: Cylinder Morphology Creation Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/multicompartmental.rst This example shows how to create a Cylinder morphology where each compartment has a fixed length and diameter. ```python # Each compartment has fixed length and diameter Cylinder(n=5, diameter=10*um, length=50*um) ``` -------------------------------- ### Import Brian Hears Module Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/brian1hears_bridge.rst Import all components from the Brian Hears module. Ensure Brian 1 is installed. ```python from brian2.hears import * ``` -------------------------------- ### Install Brian2 with Spack Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 using the Spack package manager. Spack is a flexible package manager supporting multiple versions and configurations. ```bash spack install py-brian2 ``` -------------------------------- ### Comprehensive Function Docstring Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/guidelines/documentation.rst A detailed example of a function docstring following standard conventions, including summary, extended description, parameters, return values, raised exceptions, related functions, implementation notes, mathematical formulas, and doctest examples. ```python def foo(var1, var2, long_var_name='hi') : """ A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var1`. Parameters ---------- var1 : array_like Array_like means all those objects -- lists, nested lists, etc. -- that can be converted to an array. We can also refer to variables like `var1`. var2 : int The type above can either refer to an actual Python type (e.g. ``int``), or describe the type of the variable in more detail, e.g. ``(N,) ndarray`` or ``array_like``. Long_variable_name : {'hi', 'ho'}, optional Choices in brackets, default first when optional. Returns ------- describe : type Explanation output : type Explanation tuple : type Explanation items : type even more explaining Raises ------ BadException Because you shouldn't have done that. See Also -------- otherfunc : relationship (optional) newfunc : Relationship (optional), which could be fairly long, in which case the line wraps here. thirdfunc, fourthfunc, fifthfunc Notes ----- Notes about the implementation algorithm (if needed). This can have multiple paragraphs. You may include some math: .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n} And even use a greek symbol like :math:`omega` inline. References ---------- Cite the relevant literature, e.g. [1]_. You may also cite these references in the notes section above. .. [1] O. McNoleg, "The integration of GIS, remote sensing, expert systems and adaptive co-kriging for environmental habitat modelling of the Highland Haggis using object-oriented, fuzzy-logic and neural-network techniques," Computers & Geosciences, vol. 22, pp. 585-588, 1996. Examples -------- These are written in doctest format, and should illustrate how to use the function. >>> a=[1,2,3] >>> print([x + 3 for x in a]) [4, 5, 6] >>> print("a\nb") a b """ pass ``` -------------------------------- ### Create Docker Buildx Builder Source: https://github.com/brian-team/brian2/blob/master/docker/README.md Creates a new Docker buildx builder named 'container' using the docker-container driver. This is a one-time setup. ```bash docker buildx create \ --name container \ --driver=docker-container \ default ``` -------------------------------- ### Import Brian and Setup Matplotlib Source: https://github.com/brian-team/brian2/blob/master/tutorials/2-intro-to-brian-synapses.ipynb Imports the necessary Brian2 library and sets up matplotlib for inline plotting in IPython environments. ```python from brian2 import * %matplotlib inline ``` -------------------------------- ### Run Brian2 Docker Image with JupyterLab Source: https://github.com/brian-team/brian2/blob/master/docker/README.md Starts a JupyterLab instance inside the container. Access it via the link printed to the terminal. ```bash docker run -it --init -p 8888:8888 briansimulator/brian ``` -------------------------------- ### Profiling Summary Output Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/running.rst Example output from `profiling_summary()`, showing the time and percentage contribution of different `CodeObject`s to the total simulation time. This helps identify performance bottlenecks. ```text Profiling summary ================= neurongroup_stateupdater 5.54 s 61.32 % synapses_pre 1.39 s 15.39 % synapses_1_pre 1.03 s 11.37 % spikemonitor 0.59 s 6.55 % neurongroup_thresholder 0.33 s 3.66 % ``` -------------------------------- ### Run Brian2 Docker Image with Bash Source: https://github.com/brian-team/brian2/blob/master/docker/README.md Starts a simple bash terminal inside the container for direct interaction. ```bash docker run -it --init briansimulator/brian /bin/bash ``` -------------------------------- ### Brian2 Standalone Command Line Argument Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/standalone.rst Illustrates how Brian2's C++ standalone device translates Python run arguments into command-line arguments for the compiled binary. This example shows setting a variable 'neurongroup.tau' to 10ms. ```shell ./main --results_dir /full/path/to/results_1 neurongroup.tau=0.01 ``` -------------------------------- ### Run Brian2 test suite Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Execute Brian2's test suite using the pytest utility to verify the installation. ```python import brian2 brian2.test() ``` -------------------------------- ### Example of word_substitute function output Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/guidelines/testing.rst This demonstrates the output of the word_substitute function with specific replacements. Ensure exact output matches for testing. ```python >>> print(word_substitute(expr, {'a':'banana', 'f':'func'})) banana*_b+c5+8+func(A) ``` -------------------------------- ### Synaptic Pre and Post Code Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/advanced/how_brian_works.rst Demonstrates abstract code blocks for synaptic pre and post-synaptic events. These are executed for each neuron index of a neuron that has spiked. ```python a = b ``` -------------------------------- ### Example of deprecated syntax for synapse events Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/compatibility.rst Shows the deprecated arguments 'pre' and 'post' for specifying synapse event actions. The current recommended syntax is 'on_pre' and 'on_post'. ```python pre=..., post=... ``` -------------------------------- ### Get Brian2 Installation Path Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/support.rst This Python code snippet displays the file path of the Brian2 installation. It helps in identifying the specific environment where Brian2 is installed, which is crucial for resolving version conflicts or installation issues. ```pycon >>> print(brian2.__file__) # doctest: +SKIP /home/marcel/anaconda3/envs/brian2_test/lib/python3.9/site-packages/brian2/__init__.py ``` -------------------------------- ### Get Brian2 Version Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/support.rst Use this Python code to print the installed version of the Brian2 library. This is useful for debugging and reporting issues. ```pycon >>> import brian2 >>> print(brian2.__version__) # doctest: +SKIP 2.4.2 ``` ```pycon >>> print(brian2.__version__) # doctest: +SKIP 2.4.2.post408 ``` -------------------------------- ### Getting all stored states from a monitor Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/recording.rst Use the get_states method to retrieve all recorded values from a monitor. This is useful for saving all data to disk, for example, using pickle. ```python import pickle group = NeuronGroup(...) state_mon = StateMonitor(group, 'v', record=...) run(...) data = state_mon.get_states(['t', 'v']) with open('state_mon.pickle', 'w') as f: pickle.dump(data, f) ``` -------------------------------- ### Preference File Format Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/advanced/preferences.rst Illustrates the format of preference files, showing how to set nested preferences using dotted names and section headers. Comments are supported using the '#' symbol. ```ini a.b.c = 1 # Comment line [a] b.d = 2 [a.b] b.e = 3 ``` -------------------------------- ### Install Brian2 with Conda (conda-forge) Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 from the conda-forge channel. It's recommended to install into a separate environment. ```bash conda install -c conda-forge brian2 ``` -------------------------------- ### Build and Push Multi-Platform Brian2 Docker Image Source: https://github.com/brian-team/brian2/blob/master/docker/README.md Builds a multi-platform Docker image (amd64, arm64) using buildx, pushes it to a registry, and tags it. Requires prior `docker login` and builder creation. ```bash docker buildx build \ --builder=container \ --push \ --platform linux/amd64,linux/arm64/v8 \ -o type=image \ -t briansimulator/brian \ -f docker/Dockerfile \ . ``` -------------------------------- ### Implement EmpiricalThreshold behavior (Brian 1 vs Brian 2) Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/neurongroup.rst Shows how to replicate Brian 1's EmpiricalThreshold behavior in Brian 2. Brian 2 uses string expressions for thresholds and handles refractoriness separately. ```python group = NeuronGroup(N,''' dv/dt = (I_L - I_Na - I_K + I)/Cm : volt ...''', threshold=EmpiricalThreshold(threshold=20*mV, refractory=1*ms, state='v')) ``` ```python group = NeuronGroup(N,''' dv/dt = (I_L - I_Na - I_K + I)/Cm : volt ...''', threshold='v > -20*mV', refractory=1*ms) ``` -------------------------------- ### Registering Preferences Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/preferences.rst Example of how to register new preferences using `register_preferences`. This function takes a base name, a description, and keyword arguments for each preference, set to a `BrianPreference` object. ```python register_preferences( 'codegen.c', 'Code generation preferences for the C language', 'compiler'= BrianPreference( validator=is_compiler, docs='...', default='gcc'), ... ) ``` -------------------------------- ### Install brian2tools with conda Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install the brian2tools package from the brian-team conda channel, as it's not yet on conda-forge. ```bash conda install -c brian-team brian2tools ``` -------------------------------- ### Brian2 Standalone Initialization with Array File Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/standalone.rst Shows how Brian2's C++ standalone device uses command-line arguments to specify an initialization file for array variables. The filename includes an MD5 hash of the array content for uniqueness. ```shell ./main neurongroup.tau=static_arrays/init_neurongroup_v_aca4cd6a3f7e526a61bb5a07468b377e.dat ``` -------------------------------- ### Run Multiple Simulations with Different Parameters (Brian2) Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/computation.rst Execute multiple simulation runs while varying model parameters. Use `run_args` to specify new values for parameters or initial conditions for each run. Ensure `build_on_run` is `False` and call `device.build(run=False)` to compile the code before starting the runs. ```python set_device('cpp_standalone', build_on_run=False) seed(111) # same random numbers for each run group = NeuronGroup(10, '''dv/dt = -v / tau : 1 tau : second (shared, constant)''') # 10 simple IF neuron without threshold group.v = 'rand()' mon = StateMonitor(group, 'v', record=0) run(100*ms) device.build(run=False) # Compile the code results = [] # Do 10 runs without recompiling, each time setting group.tau to a new value for tau_value in (np.arange(10)+1)*5*ms: device.run(run_args={group.tau: tau_value}) results.append(mon.v[:]) ``` ```python set_device('cpp_standalone', build_on_run=False) group = NeuronGroup(10, 'dv/dt = -v / (10*ms) : 1') # ten simple IF neurons without threshold mon = StateMonitor(group, 'v', record=True) run(100*ms) # will not call device.build/device.run device.build(run=False) # Compile the code results = [] # Do 10 runs without recompiling, each time initializing v differently for idx in range(10): device.run(run_args={group.v: np.arange(10)*0.01 + 0.1*idx}) results.append(mon.v[0]) ``` ```python set_device('cpp_standalone', build_on_run=False) stim = TimedArray(np.zeros(10), dt=10*ms) group = NeuronGroup(10, 'dv/dt = (stim(t) - v)/ (10*ms) : 1') # time-dependent stimulus mon = StateMonitor(group, 'v', record=True) run(100 * ms) device.build(run=False) results = [] ``` -------------------------------- ### Basic Simulation Loop Comparison Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/networks_and_clocks.rst Illustrates the basic simulation loop structure in Brian 1 and Brian 2. Brian 2 simplifies some boilerplate code. ```python for r in range(100): reinit_default_clock() clear() group1 = NeuronGroup(...) group2 = NeuronGroup(...) syn = Synapses(group1, group2, ...) mon = SpikeMonitor(group2) run(1*second) ``` ```python for r in range(100): reinit_default_clock() clear() group1 = NeuronGroup(...) group2 = NeuronGroup(...) syn = Synapses(group1, group2, ...) mon = SpikeMonitor(group2) run(1*second) ``` -------------------------------- ### Example: Soma Morphology Creation Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/multicompartmental.rst This example demonstrates the creation of a Soma morphology, which always consists of a single compartment. ```python # Soma always has a single compartment Soma(diameter=30*um) ``` -------------------------------- ### Basic Equations Object Initialization Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/equations.rst Demonstrates the basic initialization of an Equations object with a differential equation and a constant value for a parameter. ```python eqs = Equations('dx/dt = x/tau : volt', tau=10*ms) ``` -------------------------------- ### Build Brian2 Package Wheel for Local Architecture Source: https://github.com/brian-team/brian2/blob/master/docker/README.md Builds a package wheel for the local architecture using cibuildwheel. Ensure CIBW_BUILD is set appropriately. ```bash export CIBW_BUILD='cp312-manylinux*' cibuildwheel --platform linux --arch auto64 --output-dir dist ``` -------------------------------- ### Build Brian2 Multi-Arch Package Wheel Source: https://github.com/brian-team/brian2/blob/master/docker/README.md Builds package wheels for multiple architectures (e.g., amd64, aarch64) using cibuildwheel. Requires qemu-user-static for cross-compilation. ```bash export CIBW_BUILD='cp312-manylinux*' cibuildwheel --platform linux --arch auto64,aarch64 --output-dir dist ``` -------------------------------- ### Install supplementary packages with conda Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install useful packages like matplotlib, pytest, and ipython/jupyter using the conda package manager. ```bash conda install matplotlib pytest ipython notebook ``` -------------------------------- ### Create Morphology with Arbitrary Process Names Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/multicompartmental.rst Demonstrates creating a morphology using arbitrary names for attached processes, showing flexibility in naming conventions. ```python morpho = Soma(diameter=30*um) morpho.output_process = Cylinder(length=100*um, diameter=1*um, n=10) morpho.input_process = Cylinder(length=50*um, diameter=2*um, n=5) ``` -------------------------------- ### Install Brian2 on Fedora Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Install Brian2 using the dnf package manager on Fedora systems. The package is automatically updated with system upgrades. ```bash sudo dnf check-update python-brian2 sudo dnf upgrade python-brian2 ``` -------------------------------- ### Start Jupyter Notebook Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/scripts.rst Opens the Jupyter Notebook dashboard in your browser. Use this to open existing notebooks or create new ones for interactive Brian code execution. ```bash jupyter notebook ``` -------------------------------- ### Synaptic Operations: Typical Propagation Example Source: https://github.com/brian-team/brian2/wiki/Abstract-computational-aspects A common example of a synaptic operation during the propagation phase, demonstrating how to update postsynaptic neuron variables using synaptic weights. ```python v[j] += w[s] ``` -------------------------------- ### Use SI Units and Prefixes Source: https://github.com/brian-team/brian2/blob/master/tutorials/1-intro-to-brian-neurons.ipynb Illustrates the use of standard SI units and common prefixes like milli (m) and pico (p). Special abbreviations like mV and pF are also supported. ```python 1000*amp ``` ```python 1e6*volt ``` ```python 1000*namp ``` -------------------------------- ### Scalar Variable Update Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/codegen.rst Illustrates a scalar variable update within a reset statement. This example highlights potential ambiguity regarding whether the update applies to all neurons or a subset. ```Python scalar_variable += 1 ``` -------------------------------- ### Function Docstring Example Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/guidelines/documentation.rst This snippet demonstrates a comprehensive function docstring following a common Python convention, including various sections like Parameters, Returns, Raises, See Also, Notes, and Examples. ```APIDOC ## Function Documentation Example ### Description This is a one-line summary of the function's purpose. It is followed by several sentences providing an extended description, referring to variables using back-ticks. ### Method N/A (This is a Python function example, not an HTTP API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **var1** (array_like) - Description of var1, which can be any object convertible to an array. - **var2** (int) - Description of var2, an integer. - **long_var_name** (str, optional) - Description of long_var_name, with choices {'hi', 'ho'} and a default value. ### Returns - **describe** (type) - Explanation of the 'describe' return value. - **output** (type) - Explanation of the 'output' return value. - **tuple** (type) - Explanation of the 'tuple' return value. - **items** (type) - Explanation of the 'items' return value. ### Raises - **BadException** - Raised when an invalid operation is attempted. ### See Also - **otherfunc** - Optional relationship description. - **newfunc** - Optional relationship description that can wrap. - **thirdfunc**, **fourthfunc**, **fifthfunc** - Other related functions. ### Notes This section provides implementation details, mathematical formulas, and references. .. math:: X(e^{j\omega } ) = x(n)e^{ - j\omega n} ### References - [1] O. McNoleg, "The integration of GIS, remote sensing, expert systems and adaptive co-kriging for environmental habitat modelling of the Highland Haggis using object-oriented, fuzzy-logic and neural-network techniques," Computers & Geosciences, vol. 22, pp. 585-588, 1996. ### Examples ```python >>> a=[1,2,3] >>> print([x + 3 for x in a]) [4, 5, 6] >>> print("a\nb") a b ``` ``` -------------------------------- ### Add Conda-forge Channel Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Permanently add the conda-forge channel to your list of channels for easier installation and updates. ```bash conda config --add channels conda-forge ``` -------------------------------- ### Update Brian2 with Conda (with conda-forge) Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Update an existing Brian2 installation using conda, specifying the conda-forge channel. ```bash conda update -c conda-forge brian2 ``` -------------------------------- ### Documenting Instance Attributes in __init__ Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/guidelines/documentation.rst Document instance attributes directly within the __init__ method using special comment syntax. Supports multi-line docstrings and single-line docstrings. ```python def __init__(a, b, c): #: The docstring for the instance attribute a. #: Can also span multiple lines self.a = a self.b = b #: The docstring for self.b (only one line). self.c = c 'The docstring for self.c, directly *after* its definition' ``` -------------------------------- ### Spike Counting (Brian 1 vs Brian 2) Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/monitors.rst Shows how to use SpikeMonitor for counting spikes, similar to Brian 1's SpikeCounter and PopulationSpikeCounter. Setting `record=False` in Brian 2 saves memory when only counts are needed. ```python counter = SpikeCounter(group) pop_counter = PopulationSpikeCounter(group) #... do the run # Number of spikes for neuron 3: count_3 = counter[3] # Total number of spikes: ``` ```python counter = SpikeMonitor(group, record=False) #... do the run # Number of spikes for neuron 3 count_3 = counter.count[3] # Total number of spikes: ``` -------------------------------- ### Run Simulation with Magic System Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/running.rst Use the 'magic' run system for straightforward simulations where Brian automatically collects objects in the current namespace. This is suitable when you don't need explicit Network object management. ```python G = NeuronGroup(10, 'dv/dt = -v / (10*ms) : 1', threshold='v > 1', reset='v = 0') S = Synapses(G, G, model='w:1', on_pre='v+=w') S.connect('i!=j') S.w = 'rand()' mon = SpikeMonitor(G) run(10*ms) # will include G, S, mon ``` -------------------------------- ### Brian 1 Hears FilterbankGroup Syntax Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/brian1hears_bridge.rst Example of defining a FilterbankGroup with a leaky integrate-and-fire model in Brian 1 Hears. ```python # Leaky integrate-and-fire model with noise and refractoriness eqs = ''' dv/dt = (I-v)/(1*ms)+0.2*xi*(2/(1*ms))**.5 : 1 I : 1 ''' anf = FilterbankGroup(ihc, 'I', eqs, reset=0, threshold=1, refractory=5*ms) ``` -------------------------------- ### Store and Restore Network State for Multiple Runs Source: https://github.com/brian-team/brian2/blob/master/tutorials/3-intro-to-brian-simulations.ipynb Use `net.store()` and `net.restore()` to save and load the network's state before and after running simulations in a loop. This is useful when you need to reset the network to a specific state for each iteration. ```python start_scope() num_inputs = 100 input_rate = 10*Hz weight = 0.1 tau_range = linspace(1, 10, 30)*ms num_tau = len(tau_range) P = PoissonGroup(num_inputs, rates=input_rate) # We make tau a parameter of the group eqs = ''' dv/dt = -v/tau : 1 tau : second ''' # And we have num_tau output neurons, each with a different tau G = NeuronGroup(num_tau, eqs, threshold='v>1', reset='v=0', method='exact') G.tau = tau_range S = Synapses(P, G, on_pre='v += weight') S.connect() M = SpikeMonitor(G) # Now we can just run once with no loop run(1*second) output_rates = M.count/second # firing rate is count/duration plot(tau_range/ms, output_rates) xlabel(r'$\tau$ (ms)') ylabel('Firing rate (sp/s)') ``` -------------------------------- ### NeuronGroup with Euler Method Source: https://github.com/brian-team/brian2/blob/master/tutorials/1-intro-to-brian-neurons.ipynb Example of using the Euler method for differential equations in NeuronGroup. Suitable for simulations where exact integration is not feasible. ```python G = NeuronGroup(1, eqs, method='euler') M = StateMonitor(G, 'v', record=0) G.v = 5 # initial value run(60*ms) plot(M.t/ms, M.v[0]) xlabel('Time (ms)') ylabel('v'); ``` -------------------------------- ### Membrane Equation with Markov State Source: https://github.com/brian-team/brian2/wiki/Markov-models-of-ionic-channels Example of a membrane potential equation that depends on the state of a Markov channel (O). Units are specified as volt. ```plaintext dv/dt = g*O*(E-v) : volt ``` -------------------------------- ### Accessing and Setting Preferences Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/advanced/preferences.rst Demonstrates equivalent ways to access and set preferences using keyword-based and attribute-based syntax. The attribute-based form is useful for interactive work like autocompletion in ipython. ```python prefs['codegen.cpp.compiler'] = 'unix' ``` ```python prefs.codegen.cpp.compiler = 'unix' ``` -------------------------------- ### Accessing and Setting Preferences Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/developer/preferences.rst Demonstrates equivalent keyword-based and attribute-based methods for accessing and setting preferences. Attribute-based access is useful for interactive work with autocompletion. ```python prefs['codegen.c.compiler'] = 'gcc' prefs.codegen.c.compiler = 'gcc' ``` ```python if prefs['codegen.c.compiler'] == 'gcc': ... ``` ```python if prefs.codegen.c.compiler == 'gcc': ... ``` -------------------------------- ### Update Brian2 with Conda (without explicit channel) Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/install.rst Update an existing Brian2 installation using conda, assuming the conda-forge channel has been added. ```bash conda update brian2 ``` -------------------------------- ### Record Multiple Variables (Brian 1 vs Brian 2) Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/introduction/brian1_to_2/monitors.rst Illustrates the difference in recording multiple variables ('v' and 'w') using StateMonitor between Brian 1 (MultiStateMonitor) and Brian 2 (StateMonitor). Brian 2's StateMonitor directly handles multiple variables. ```python mon = MultiStateMonitor(group, ['v', 'w'], record=True) # ... do the run # plot the traces of v and w for neuron 3: plot(mon['v'].times/ms, mon['v'][3]/mV) plot(mon['w'].times/ms, mon['w'][3]/mV) ``` ```python mon = StateMonitor(group, ['v', 'w'], record=True) # ... do the run # plot the traces of v and w for neuron 3: plot(mon.t/ms, mon[3].v/mV) plot(mon.t/ms, mon[3].w/mV) ``` -------------------------------- ### Poisson Input Generation Source: https://github.com/brian-team/brian2/blob/master/docs_sphinx/user/input.rst Use PoissonGroup to generate spikes according to a Poisson point process. This example connects Poisson inputs to a NeuronGroup. ```python P = PoissonGroup(100, np.arange(100)*Hz + 10*Hz) G = NeuronGroup(100, 'dv/dt = -v / (10*ms) : 1') S = Synapses(P, G, on_pre='v+=0.1') S.connect(j='i') ```