### Setup and Run Tests with Tox Source: https://github.com/openbraininstitute/bluecellulab/blob/main/README.rst Install tox and use it to run the test suite or format checks for BlueCelluLab. This is essential for verifying code integrity and adherence to coding standards. ```bash pip install tox tox -e py3 # runs the tests tox -e lint # runs the format checks ``` -------------------------------- ### Quick Start: Create Cell, Add Stimulus, Run Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/README.rst A basic example demonstrating how to create a ball-and-stick cell, add a step stimulus, and run a simulation. This is useful for initial testing and understanding core functionalities. ```python from bluecellulab.cell import create_ball_stick from bluecellulab import Simulation cell = create_ball_stick() sim = Simulation() sim.add_cell(cell) stimulus = cell.add_step(start_time=5.0, stop_time=20.0, level=0.5) sim.run(25, cvode=False) time, voltage = cell.get_time(), cell.get_soma_voltage() # plotting time and voltage ... ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/readme-plot.ipynb Imports necessary libraries for plotting and Bluecellulab simulation, and sets the Seaborn style. ```python import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") from bluecellulab.cell import create_ball_stick from bluecellulab import Simulation ``` -------------------------------- ### Install BlueCelluLab Source: https://github.com/openbraininstitute/bluecellulab/blob/main/README.rst Install the BlueCelluLab package using pip. Ensure you have Python 3.10+ and NEURON >=8.0.2 installed. ```bash pip install bluecellulab ``` -------------------------------- ### Import BlueCelluLab and Supporting Libraries Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-modifications.ipynb Imports necessary libraries for circuit simulation, configuration, logging, and plotting. Ensure these libraries are installed. ```python import json import logging from pathlib import Path from matplotlib import pyplot as plt import seaborn as sns sns.set_style("white") from bluecellulab import CircuitSimulation from bluecellulab.circuit.config import SonataSimulationConfig ``` -------------------------------- ### Import BlueCellulab and Supporting Libraries Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/7-Extra-Simulation/Multiple-protocols.ipynb Imports essential libraries for simulation, cell modeling, and data analysis. Ensure these are installed before running. ```python import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') import numpy as np from pathlib import Path import neuron from bluecellulab import Cell from bluecellulab.simulation import Simulation from bluecellulab.simulation.neuron_globals import NeuronGlobals from bluecellulab.tools import search_threshold_current from bluecellulab.circuit.circuit_access import EmodelProperties from bluecellulab.stimulus import StimulusFactory ``` -------------------------------- ### Get All Stimuli Entries Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Retrieves all stimuli entries defined in the circuit simulation configuration. ```python stimuli_entries = sim.circuit_access.config.get_all_stimuli_entries() stimuli_entries ``` -------------------------------- ### Initializing and Running the Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb This code initializes the simulation with the selected dSTUT cells, enabling stimuli and synapses. It then runs the simulation for a specified duration, starting from a defined time point. ```python sim.instantiate_gids(dstut_cells, add_stimuli=True, add_synapses=True) t_stop = simulation_config_dict["run"]['tstop'] t_start = simulation_config_dict["run"]['tstart'] dt = simulation_config_dict["run"]['dt'] sim.run(t_stop=t_stop, forward_skip=True, forward_skip_value=t_start) ``` -------------------------------- ### Run Simulation and Get Time Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Execute the simulation for a specified duration and retrieve the time vector. This is a standard step after setting up recordings to obtain the data for analysis. ```python sim.run(250, cvode=False) time = cell.get_time() soma_voltage = cell.get_soma_voltage() ``` -------------------------------- ### Configure Logging for Modifications Module Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-modifications.ipynb Enables INFO level logging specifically for the bluecellulab.simulation.modifications module. This helps in observing the modification process during simulation setup. ```python # Enable INFO logging for the modifications module to see what happens logging.basicConfig(level=logging.WARNING) logging.getLogger("bluecellulab.simulation.modifications").setLevel(logging.INFO) ``` -------------------------------- ### Prepare Simulation for Voltage Recording Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/4-epsp/epsp.ipynb Configures the simulation to record voltage changes at a specific dendritic section. This setup is crucial for observing the effects of the introduced current pulse. ```python cell.add_voltage_recording(a_section, 0.5) ``` -------------------------------- ### Initialize Circuit Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Initializes the CircuitSimulation object with the simulation configuration. ```python sim = CircuitSimulation(simulation_config) ``` -------------------------------- ### Get Unique Morphologies Source: https://github.com/openbraininstitute/bluecellulab/blob/main/tests/examples/circuit_hipp_mooc_most_central_10_SP_PC/copy-hoc-morphs.ipynb Extracts unique values from the 'morphology' column of the DataFrame. ```python unique_morphs = df["morphology"].unique() unique_morphs ``` -------------------------------- ### Initialize Circuit Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-modifications.ipynb Initializes a CircuitSimulation object with the specified configuration path. This object is used to run simulations. ```python sim = CircuitSimulation(sim_config_path) ``` -------------------------------- ### Get the shape of the step stimulus current Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/5-stimuli/stimuli.ipynb Retrieves the number of data points in the current array of the step stimulus. ```python step.current.shape ``` -------------------------------- ### Initialize Simulation and Add Cell Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Create a Simulation object and add a cell to it for simulation. ```python sim = Simulation() sim.add_cell(cell) ``` -------------------------------- ### Set Up Hippocampal Cell Model Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/4-epsp/epsp.ipynb Initializes a hippocampal cell model using bluecellulab's Cell class with specified hoc and morphology files. A Simulation object is created and the cell is added to it. A specific dendritic section is selected for EPSP simulation. ```python base_dir = Path(".") # Define the hoc and morphology files hoc_file = base_dir / "hoc" / "cell_seed2_0.hoc" morph_file = base_dir / "morphology" / "011017HP2.asc" cell = Cell(hoc_file, morph_file, template_format="bluepyopt") sim = Simulation() sim.add_cell(cell) a_section = cell.cell.getCell().dend[5] ``` -------------------------------- ### Compile NEURON Mechanisms Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/6-stimuli-sequence/stimuli-sequence.ipynb Compiles custom NEURON mechanisms required for the cell model. Ensure NEURON is installed before running. ```python !nrnivmodl ../mechanisms ``` -------------------------------- ### Plot APWaveform stimulus and get its length Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/5-stimuli/stimuli.ipynb Plots the APWaveform stimulus and determines the total number of time points in the stimulus. ```python apwaveform.plot() len(apwaveform) ``` -------------------------------- ### Run Tests Source: https://github.com/openbraininstitute/bluecellulab/blob/main/docs/source/contributing.md Execute the test suite using tox with the py3 environment. This verifies the functionality of your changes and ensures compatibility. ```bash tox -e py3 ``` -------------------------------- ### Compile NEURON Mechanisms Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/4-epsp/epsp.ipynb Compiles the necessary NEURON mechanisms for the hippocampal cell model. Ensure NEURON is installed before running this command. ```bash !nrnivmodl hippocampus_mechanisms ``` -------------------------------- ### Run Baseline Simulation Without Modifications Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-modifications.ipynb Sets up and runs a baseline simulation without any modifications and disables stimuli for a clean comparison. It then collects voltage traces. ```python # Simulation WITHOUT modifications (baseline) # Note: Also disable stimuli for clean baseline comparison baseline_config = Path("sim_quick_scx_sonata_multicircuit") / "simulation_config_noinput.json" sim_baseline = CircuitSimulation(baseline_config) sim_baseline.instantiate_gids(all_cell_ids, add_stimuli=False, add_synapses=False) sim_baseline.run(t_stop=100.0) traces_baseline = {} for cell_id in sim_baseline.cells: traces_baseline[cell_id] = { "time": sim_baseline.get_time_trace(), "voltage": sim_baseline.get_voltage_trace(cell_id), } ``` -------------------------------- ### Read CSV and Get Unique HOCs Source: https://github.com/openbraininstitute/bluecellulab/blob/main/tests/examples/circuit_hipp_mooc_most_central_10_SP_PC/copy-hoc-morphs.ipynb Reads a CSV file into a pandas DataFrame and extracts unique values from the 'model_template' column. ```python df = pd.read_csv("hoc-and-morphs.csv") unique_hocs = df["model_template"].unique() unique_hocs ``` -------------------------------- ### Get All Cell IDs from Circuit Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-modifications.ipynb Retrieves all cell IDs present in the circuit using bluepysnap. This is useful for instantiating specific cells or all cells in the simulation. ```python from bluepysnap import Simulation as snap_sim import pandas as pd snap_access = snap_sim(sim_config_path) all_nodes = pd.concat([x[1] for x in snap_access.circuit.nodes.get()]) all_cell_ids = all_nodes.index.to_list() print(f"All cells in circuit: {all_cell_ids}") ``` -------------------------------- ### Print Simulation Configuration Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Prints the loaded simulation configuration dictionary to the console in a formatted JSON string. This allows inspection of the simulation parameters. ```python print(json.dumps(simulation_config_dict, indent=4)) ``` -------------------------------- ### Run Simulation and Plot Voltage for H5 Container Morphology Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell_H5_morph_H5_container.ipynb Configures simulation globals, adds the cell to the simulation, applies a step current clamp, runs the simulation, and plots the soma voltage over time for a cell initialized with an H5 container morphology. ```python # set initial voltage ng = NeuronGlobals.get_instance() ng.v_init = -80 sim = Simulation() sim.add_cell(cell) # insert step current clamp of 1.25 nA cell_container.add_step(start_time=20.0, stop_time=100.0, level=1.5) sim.run(tstop=140, cvode=False) time_container, voltage_container = cell_container.get_time(), cell_container.get_soma_voltage() plt.plot(time_container, voltage_container) plt.xlabel("Time (ms)") plt.ylabel("Voltage (mV)") ``` -------------------------------- ### Initialize BluePySnap Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Initializes a BluePySnap simulation object using the provided simulation configuration. ```python snap_access = snap_sim(simulation_config) ``` -------------------------------- ### Access Soma Radius (Ra) Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Retrieves and displays the specific resistance (Ra) of the cell's soma section. This is an example of accessing morphology-related attributes. ```python cell.soma.Ra ``` -------------------------------- ### Run Simulation and Plot Voltage for H5 Morphology Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell_H5_morph_H5_container.ipynb Configures simulation globals, adds the cell to the simulation, applies a step current clamp, runs the simulation, and plots the soma voltage over time for a cell initialized with an H5 morphology. ```python # set initial voltage ng = NeuronGlobals.get_instance() ng.v_init = -80 sim = Simulation() sim.add_cell(cell) # insert step current clamp of 1.25 nA cell.add_step(start_time=20.0, stop_time=100.0, level=1.5) sim.run(tstop=140, cvode=False) time_single_h5_morphology, voltage_single_h5_morphology = cell.get_time(), cell.get_soma_voltage() plt.plot(time_single_h5_morphology, voltage_single_h5_morphology) plt.xlabel("Time (ms)") plt.ylabel("Voltage (mV)") ``` -------------------------------- ### Load and Print Simulation Configuration Modifications Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-modifications.ipynb Loads a simulation configuration from a JSON file and prints the 'conditions' block, which contains modification details. Ensure the simulation config path is correct. ```python from pathlib import Path import json sim_config_path = Path("sim_quick_scx_sonata_multicircuit") / "simulation_config_modifications.json" with open(sim_config_path) as f: config_dict = json.load(f) print(json.dumps(config_dict["conditions"], indent=4)) ``` -------------------------------- ### Get Soma Children Sections Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Lists the direct child sections of the cell's soma. This helps in understanding the hierarchical structure of the cell's morphology. ```python cell.soma.children() ``` -------------------------------- ### Run SONATA Circuit Simulation with Python Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/run_circuit_mpi/README.md Execute the simulation directly using Python. This command specifies the simulation configuration file and enables NWB export. ```python python run_bluecellulab_simulation.py --simulation_config simulation_config_container.json --save-nwb ``` -------------------------------- ### Call Validator Only Once in SSim Constructor Source: https://github.com/openbraininstitute/bluecellulab/blob/main/CHANGELOG.rst Enhances performance by ensuring the validator is called only once within the SSim constructor. This avoids repeated validation overhead during simulation setup. ```python call validator only once in SSim's constructor ``` -------------------------------- ### Configure Logging Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Configures the logging level to WARNING. This snippet sets up basic logging for the simulation. ```python import logging logging.basicConfig( level=logging.WARNING, ) ``` -------------------------------- ### Access Apical Dendrite Length (L) Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Retrieves and displays the length (L) of the first apical dendrite section. This is another example of accessing morphology attributes. ```python cell.apical[0].L ``` -------------------------------- ### Retrieve Simulation Data Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Get the time and voltage data from the simulated cell. Use specific methods like 'get_soma_voltage()' to access voltage from different cell sections. ```python time, voltage = cell.get_time(), cell.get_soma_voltage() ``` -------------------------------- ### Initialize BPAP Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/3-bpap/bpap.ipynb Initializes the BPAP simulation object with a loaded neuron model. This prepares the simulation environment for running. ```python from bluecellulab import BPAP bpap = BPAP(cell) ``` -------------------------------- ### Import BlueCelluLab Source: https://github.com/openbraininstitute/bluecellulab/blob/main/docs/source/compiling-mechanisms.md Import the BlueCelluLab library. Ensure the working directory is set correctly before importing, as it influences NEURON's behavior. ```python import bluecellulab ``` -------------------------------- ### Load Cell with Emodel Properties Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Initializes a Cell object with specified electrophysiology and morphology files, along with electrophysiological model properties. The template_format is set to 'v6'. ```python emodel_properties = EmodelProperties(threshold_current=1.1433533430099487, holding_current=1.4146618843078613, AIS_scaler=1.4561502933502197) cell = Cell(hoc_file, morph_file, template_format="v6", emodel_properties=emodel_properties) ``` -------------------------------- ### Retrieve Recorded Spikes Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Get the precise times of detected spikes from a specific location on the cell (e.g., soma) after running the simulation. Requires spike recording to be enabled beforehand. ```python spikes = cell.get_recorded_spikes(location="soma", threshold=-10) ``` -------------------------------- ### Initialize Single Cell with H5 Morphology Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell_H5_morph_H5_container.ipynb Initializes a single cell simulation using an H5 morphology file. Sets up model properties, cell parameters, and simulation environment. ```python emodel_properties = EmodelProperties(threshold_current=threshold_current, holding_current=holding_current, AIS_scaler=1.0) cell = Cell(template_path=hoc_file, morphology_path=morph_file_single_h5, template_format="v6", emodel_properties=emodel_properties) ``` -------------------------------- ### Selecting dSTUT Cells for Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb This snippet demonstrates how to filter and select specific cell types (dSTUT) from the loaded network data. The selected cell indices are then converted into a list for further simulation setup. ```python dstut_cells = all_nodes[all_nodes["etype"] == "dSTUT"].index.to_list() dstut_cells ``` ```python Result: [('NodeA', 0), ('NodeA', 1), ('NodeB', 0), ('NodeB', 1)] ``` -------------------------------- ### Get Gids of Mtypes and Targets Return Set Source: https://github.com/openbraininstitute/bluecellulab/blob/main/CHANGELOG.rst Fixes a bug where 'get_gids_of_mtypes' and 'get_gids_of_targets' could return duplicated GIDs. The fix ensures they now return a set to avoid duplicates originating from multiple targets or mtypes. ```python get_gids_of_mtypes and get_gids_of_targets to return set to avoid duplicated gids coming from multiple targets or mtypes ``` -------------------------------- ### Run Code Linting Source: https://github.com/openbraininstitute/bluecellulab/blob/main/docs/source/contributing.md Check code formatting using tox with the lint environment. Ensure your code adheres to project style guidelines before submitting. ```bash tox -e lint ``` -------------------------------- ### Helper Function to Get Peak Voltage Index Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/3-bpap/bpap.ipynb Defines a helper function to find the index of the peak voltage within a specified time range of a voltage trace. This is useful for analyzing the timing of action potentials. ```python def get_peak_index(voltage, stim_start: int, stim_end: int) -> int: """Get the peak voltage from a trace.""" return voltage[stim_start:stim_end].argmax() + stim_start ``` -------------------------------- ### Add Ramp Stimulation and Initialize Spike Recording Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Set up a ramp current stimulus and prepare the cell to record spikes by adding a spike detector with a specified threshold. ```python cell = Cell(hoc_file, morph_file, template_format="v6", emodel_properties=emodel_properties) tstim = cell.add_ramp(start_time=10.0, stop_time=30.0, start_level=0.5, stop_level=4.0) sim = Simulation() sim.add_cell(cell) cell.start_recording_spikes(None, location="soma", threshold=-10) ``` -------------------------------- ### Plotting Simulation Results Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/5-stimuli/stimuli.ipynb Generates a two-panel plot showing the neuron's voltage response and the injected current over time. Ensures plots start from time 0 and uses tight layout for better visualization. Requires matplotlib.pyplot as plt. ```python fig, axs = plt.subplots(2, 1, figsize=(12, 8), sharex=True) # 2 rows, 1 column, wider figure, shared x-axis # Plot voltage over time on the first subplot axs[0].plot(time, voltage, marker='.', markersize=0.1, color='k', linewidth=0.15) axs[0].set_title('Time vs Voltage') axs[0].set_xlim(left=0) # Make the plot start from 0 on the x-axis # Plot injected current over time on the second subplot axs[1] = combined_stimulus.plot(axs[1]) axs[1].set_title('Time vs Injected Current') axs[1].set_xlim(left=0) # Make the plot start from 0 on the x-axis plt.tight_layout() # Adjusts subplot params so that subplots fit into the figure area plt.show() ``` -------------------------------- ### Run SONATA Circuit Simulation with Bash Script Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/run_circuit_mpi/README.md Execute the simulation script using bash. This script supports parallel execution via MPI. Modify the 'num_cores' variable to control the number of cores used. ```bash ./run_sonata.sh ``` -------------------------------- ### Initialize Cell with Emodel Properties Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/7-Extra-Simulation/Multiple-protocols.ipynb Creates a Cell object with specified electrical model properties, including threshold current and holding current. This is a prerequisite for running simulations. ```python emodel_properties = EmodelProperties(threshold_current=0.03203125, holding_current=-0.11, AIS_scaler=1.11) cell = Cell(hoc_file, morph_file, template_format="v6", emodel_properties=emodel_properties) ``` -------------------------------- ### Add Alpha Synapse and Record Current Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/4-epsp/epsp.ipynb Sets up an alpha synapse on a specified dendritic section and records the synaptic current. Ensure the 'cell' object and 'a_section' are defined prior to execution. ```python onset = 300.0 tau = 10.0 gmax = 0.0001 e = 0.0 synapse = cell.add_alpha_synapse(onset, tau, gmax, e, section=a_section) current_vector = neuron.h.Vector() _ = current_vector.record(synapse._ref_i) ``` -------------------------------- ### Import Bluecellulab and Plotting Libraries Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Imports necessary libraries for cell simulation, plotting, and circuit access. Includes Cell, Simulation, EmodelProperties, and plotting tools like matplotlib and seaborn. ```python from pathlib import Path from matplotlib import pyplot as plt from matplotlib.pyplot import get_cmap import seaborn as sns sns.set_style("whitegrid") from bluecellulab import Cell, Simulation from bluecellulab.circuit.circuit_access import EmodelProperties from bluecellulab.stimulus.circuit_stimulus_definitions import OrnsteinUhlenbeck, ShotNoise from bluecellulab import RNGSettings ``` -------------------------------- ### Import BlueCelluLab and Analysis Modules Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/6-stimuli-sequence/stimuli-sequence.ipynb Imports necessary classes and functions from BlueCelluLab for cell simulation, analysis, and plotting. ```python from pathlib import Path from bluecellulab.analysis.inject_sequence import apply_multiple_stimuli, StimulusName from bluecellulab import EmodelProperties, Cell import matplotlib.pyplot as plt ``` -------------------------------- ### Compare Simulation Results from H5 Morphology and H5 Container Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell_H5_morph_H5_container.ipynb Plots the simulation results (soma voltage over time) from both an H5 morphology and an H5 container morphology on the same graph for direct comparison. ```python plt.plot(time_single_h5_morphology, voltage_single_h5_morphology, label="H5 morphology", color="blue", linestyle="-") plt.plot(time_container, voltage_container, label="H5 container", color="red", linestyle="-.") plt.xlabel("Time (ms)") plt.ylabel("Voltage (mV)") plt.legend() plt.show() ``` -------------------------------- ### Create and plot a pulse stimulus Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/5-stimuli/stimuli.ipynb Generates a pulse stimulus with parameters for pre-delay, duration, post-delay, pulse width, frequency, and amplitude, then plots it. ```python pulse_stimulus = stim_factory.pulse( pre_delay=10.0, # Pre-stimulus delay (ms) duration=250.0, # Pulse train duration (ms) post_delay=10.0, # Post-stimulus delay (ms) width=10.0, # Pulse width (ms) frequency=25.0, # Pulse frequency (Hz) amplitude=0.5 # Pulse amplitude (nA) ) ax = pulse_stimulus.plot() ``` -------------------------------- ### Import BluePySnap Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Imports the Simulation class from the bluepysnap library. ```python from bluepysnap import Simulation as snap_sim ``` -------------------------------- ### Load and Print Compartment Sets Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Loads compartment sets from a JSON file specified in the simulation configuration and prints them using pprint. ```python import json with open(f"sim_quick_scx_sonata_multicircuit/{simulation_config_dict['compartment_sets_file']}") as f: comp_sets = json.load(f) from pprint import pprint pprint(comp_sets) ``` -------------------------------- ### SONATA Input Stimuli Configuration Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Prints the input stimuli configuration for a SONATA simulation. This section defines how external stimuli are applied to the network, such as current clamps or spike replays. ```python print(json.dumps(simulation_config_dict["inputs"], indent=4)) ``` -------------------------------- ### Run Simulation with Modifications Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-modifications.ipynb Executes a simulation with pre-defined modifications and collects voltage traces for each cell. Ensure the simulation object is already instantiated. ```python # Simulation WITH modifications (already instantiated above) sim.run(t_stop=100.0) traces_with_mods = {} for cell_id in sim.cells: traces_with_mods[cell_id] = { "time": sim.get_time_trace(), "voltage": sim.get_voltage_trace(cell_id), } ``` -------------------------------- ### Add Projections Signature and Docstring Source: https://github.com/openbraininstitute/bluecellulab/blob/main/CHANGELOG.rst Defines the signature and behavior for adding projections in the simulation configuration. It accepts a boolean or a list of strings to specify which projections to add. ```python add_projections: bool | List[str] = False add_projections: If True, adds all of the projection blocks of the BlueConfig. If False, no projections are added. If list, adds only the projections in the list. ``` -------------------------------- ### Create and plot a step stimulus Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/5-stimuli/stimuli.ipynb Generates a step stimulus with specified pre-delay, duration, and post-delay, then plots its current over time. ```python step = stim_factory.step(amplitude=70, pre_delay=50, duration=100, post_delay=50) step.plot() ``` -------------------------------- ### Define Simulation Configuration Path Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Specifies the path to the simulation configuration file, which is compatible with neurodamus. Bluecellulab can use this to repeat subsets of large-scale simulations. ```python simulation_config = Path("sim_quick_scx_sonata_multicircuit") / "simulation_config_compartment_set.json" ``` -------------------------------- ### Import Required Libraries for BPAP Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/3-bpap/bpap.ipynb Import necessary Python libraries including pathlib, itertools, neuron, numpy, matplotlib, scipy, and bluecellulab modules. These are essential for cell simulation, data analysis, and visualization. ```python from pathlib import Path from itertools import islice import neuron import numpy as np from matplotlib.pyplot import get_cmap import matplotlib.pyplot as plt from scipy.optimize import curve_fit from bluecellulab import Cell from bluecellulab.simulation import Simulation from bluecellulab.stimulus.circuit_stimulus_definitions import Hyperpolarizing from bluecellulab.circuit.circuit_access import EmodelProperties ``` -------------------------------- ### Execute Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/4-epsp/epsp.ipynb Runs the neuron simulation for a specified duration with defined time step and global parameters. Sets simulation temperature and initial membrane potential. ```python duration = 450 dt = 0.1 neuron_globals = NeuronGlobals.get_instance() neuron_globals.temperature = 34.0 neuron_globals.v_init = -70.0 sim.run(duration, cvode=False, dt=dt) ``` -------------------------------- ### Create and Simulate Cell Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/readme-plot.ipynb Creates a ball-and-stick cell, adds it to a simulation, applies a step stimulus, and runs the simulation. ```python cell = create_ball_stick() sim = Simulation() sim.add_cell(cell) stimulus = cell.add_step(start_time=5.0, stop_time=20.0, level=0.5) sim.run(25, cvode=False) time, voltage = cell.get_time(), cell.get_soma_voltage() ``` -------------------------------- ### Write All Reports in Single Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Use this snippet to write all reports for single-process simulations. It initializes the ReportManager and writes reports using the cells from the simulation. ```python from bluecellulab.reports.manager import ReportManager report_mgr = ReportManager(sim.circuit_access.config, sim.dt) report_mgr.write_all(sim.cells) ``` -------------------------------- ### Import Libraries Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Imports essential libraries for circuit simulation, plotting, and JSON handling. Sets the plotting style to white using seaborn. ```python import json from pathlib import Path from matplotlib import pyplot as plt import seaborn as sns sns.set_style("white") from bluecellulab import CircuitSimulation from bluecellulab.graph import build_graph, plot_graph ``` -------------------------------- ### Initialize Single Cell with H5 Container Morphology Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell_H5_morph_H5_container.ipynb Initializes a single cell simulation using an H5 container for morphology data. Sets up model properties and cell parameters, referencing the H5 container path. ```python emodel_properties = EmodelProperties(threshold_current=threshold_current, holding_current=holding_current, AIS_scaler=1.0) cell_container = Cell(template_path = hoc_file, morphology_path = morph_h5_container, template_format="v6", emodel_properties=emodel_properties) ``` -------------------------------- ### Inject Stimulus and Run Simulation Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/5-stimuli/stimuli.ipynb Creates a neuron, injects a combined stimulus waveform, runs a simulation, and retrieves time and voltage data. Requires the 'create_ball_stick' function and 'Simulation' class to be available. ```python # in another simulation inject the combined stimulus cell = create_ball_stick() cell.inject_current_waveform(t_content=combined_stimulus.time, i_content=combined_stimulus.current) sim = Simulation(cell) duration = 1500 print("Running the simulation...") sim.run(duration, dt=0.1) print("Done.") time, voltage = cell.get_time(), cell.get_soma_voltage() ``` -------------------------------- ### Compile Neuron Mechanisms with nrnivmodl Source: https://github.com/openbraininstitute/bluecellulab/blob/main/docs/source/compiling-mechanisms.md Use the `nrnivmodl` command to compile neuron mechanisms from .mod files. This command generates an architecture-specific folder (e.g., 'i686', 'x86_64') containing the compiled mechanisms. ```shell nrnivmodl ``` -------------------------------- ### Create Validate Module for Circuit/Simulation Config Source: https://github.com/openbraininstitute/bluecellulab/blob/main/CHANGELOG.rst Establishes a dedicated 'validate' module for handling circuit and simulation configuration validation. This separates validation logic from object creation. ```python create a validate module for circuit/simulation config validation. ``` -------------------------------- ### Set Neuron Simulation Initialization Voltage Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/6-stimuli-sequence/stimuli-sequence.ipynb Configures the initial membrane potential (v_init) for the NEURON simulation. This ensures accurate cell response simulation. ```python from bluecellulab.simulation.neuron_globals import NeuronGlobals ng = NeuronGlobals.get_instance() ng.v_init = -80 ``` -------------------------------- ### Initialize Cell and Add Ramp Stimulus Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/1-singlecell/singlecell.ipynb Initializes a single cell model and adds a ramp current stimulus. Requires pre-defined hoc_file, morph_file, and emodel_properties. ```python cell = Cell(hoc_file, morph_file, template_format="v6", emodel_properties=emodel_properties) cell.add_ramp(start_time=10.0, stop_time=30.0, start_level=0.5, stop_level=4.0) sim = Simulation() sim.add_cell(cell) cell.add_ais_recording(dt=cell.record_dt) ``` -------------------------------- ### Building and Plotting the Synaptic Graph Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb This snippet constructs a graph representing synaptic strengths between dSTUT cells and visualizes it. The graph is saved as a PDF file and displayed. ```python G = build_graph(sim.cells) plt = plot_graph(G, node_size=500, edge_width=0.6, node_distance=1.8) plt.savefig("ex2_sonatagraph.pdf") plt.show() ``` ```python Result:
``` -------------------------------- ### Load Simulation Configuration Source: https://github.com/openbraininstitute/bluecellulab/blob/main/examples/2-sonata-network/sonata-network.ipynb Loads the simulation configuration from a JSON file into a Python dictionary. This configuration is used by neurodamus and Bluecellulab. ```python with open(simulation_config) as f: simulation_config_dict = json.load(f) ```