### Install Blue Brain SNAP using pip Source: https://github.com/openbraininstitute/snap/blob/main/README.rst This command installs the Blue Brain SNAP library using pip. Ensure you have pip installed and accessible in your environment. ```shell pip install bluepysnap ``` -------------------------------- ### Access Simulation Timings Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Retrieves the start time, stop time, and time step (dt) of the simulation from the run configuration. These values are essential for understanding the simulation's temporal dynamics. ```python simulation.time_start, simulation.time_stop, simulation.dt ``` -------------------------------- ### Query Nodes using CircuitNodeIds Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb Shows how to perform a `get` query on circuit nodes using a pre-instantiated `CircuitNodeIds` object. The `properties` argument specifies which attributes to retrieve for the matching nodes. ```python result = circuit.nodes.get(ids_from_dict, properties=['layer']) pd.concat([df for _,df in result]) ``` -------------------------------- ### Query Nodes by Specifying IDs Directly in get Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb Illustrates a more direct method for querying circuit nodes by passing a dictionary containing node IDs and population information directly to the `get` function. The library resolves these IDs internally. ```python result = circuit.nodes.get({'node_id': [1, 2], 'population': 'thalamus_neurons'}, properties=['layer']) pd.concat([df for _,df in result]) ``` -------------------------------- ### Query Nodes using Regex for Population Matching Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb Explains how to use regular expressions for querying node properties. This example searches for nodes within the 'thalamus_neurons' population whose 'mtype' property starts with 'VPL'. ```python circuit.nodes['thalamus_neurons'].get({"mtype": {"$regex": "^VPL_.*"}}, properties=['mtype']) ``` -------------------------------- ### Get Available Node Property Names Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb Retrieves and prints the list of all available property names for nodes in the circuit. This helps in understanding what attributes can be used for querying. ```python circuit.nodes.property_names ``` -------------------------------- ### Instantiate CircuitNodeIds from Dictionary Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb Demonstrates how to create a `CircuitNodeIds` object using the `from_dict` method. This object can then be used in subsequent `get` queries. It takes a dictionary where keys are population names and values are lists of node IDs. ```python ids_from_dict = bluepysnap.circuit_ids.CircuitNodeIds.from_dict({'thalamus_neurons': [1]}) print(ids_from_dict) ``` -------------------------------- ### Query Nodes by Population Type Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb Demonstrates how to query nodes based on their population type, as defined in the SONATA circuit configuration. This example retrieves all nodes belonging to 'virtual' population types. ```python result = circuit.nodes.get({'population_type': ['virtual']}) pd.concat([df for _,df in result]) ``` -------------------------------- ### Get All Nodes and Properties in Python Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb This Python code snippet demonstrates how to fetch all available nodes and their properties from the circuit object. It iterates through the results and displays the head of each resulting DataFrame. The primary dependency is the 'circuit' object and the 'display' function, likely from a data visualization library. ```python data = circuit.nodes.get() for _, df in data: display(df.head()) ``` -------------------------------- ### Query Nodes by Multiple Criteria (mtype, population) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb Illustrates querying nodes based on multiple criteria using a dictionary. This example filters nodes by their mtype (using an OR condition for multiple types) and their population (using an AND condition). ```python circuit.nodes.ids({ 'mtype': ['VPL_TC', 'VPL_IN'], 'population': 'thalamus_neurons' }) ``` -------------------------------- ### Iterate Connections with Node Queries Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/11_iter_connections.ipynb Shows how `iter_connections` can accept node queries, such as node set strings or dictionaries, as arguments for source and target nodes. The method resolves these queries on the fly to find connections, demonstrating flexibility in defining connection criteria. The example prints the first 10 connections found. ```python it = edge_population.iter_connections( 'mc2;VPL', # node set {'region': 'mc2;Rt'}, # dict query ) for i, (_source_id, _target_id) in enumerate(it): if i == 10: # Let's only print first 10 print(f'{i+1:2d}: ...') break print(f'{i+1:2d}: source: {_source_id.id:2d} --- target: {_target_id.id:2d}') ``` -------------------------------- ### Query Edges by Source/Target IDs in Python Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb Demonstrates how to query edge populations using known source and target node IDs. It shows filtering edges by specifying both source and target IDs using the `get` method with properties. Dependencies include a Snap edge population object. ```python source_ids = [1] target_ids = [27204] properties = ['@source_node', '@target_node'] edge_population.get({'@source_node': source_ids, '@target_node': target_ids}, properties=properties) ``` -------------------------------- ### Get Edge Count and Node Count in Snap Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb This snippet demonstrates how to retrieve the total number of edges and nodes in a circuit. It then calculates the approximate ratio of edges to nodes, illustrating the scale of the data. This is crucial for understanding potential memory issues when querying edges. ```python n_edges = circuit.edges.size n_nodes = circuit.nodes.size print(f"# of nodes: {n_nodes}") print(f"# of edges: {n_edges}") print(f"There are roughly {n_edges // n_nodes} times more edges than nodes.") ``` -------------------------------- ### Query Edges by Afferent Center Coordinates in Snap Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb This example shows how to query specific edge properties, such as afferent center coordinates, within a defined range. It illustrates two methods: querying across all edge populations and querying within a specific edge population. This helps in filtering edges based on spatial criteria. ```python query = { 'afferent_center_x': [450, 460], 'afferent_center_y': [450, 460], 'afferent_center_z': [450, 460], } properties = list(query) # This query only returns results for one population data = circuit.edges.get(query, properties) for _, df in data: display(df.head()) # Let's query the same but using the edge population edge_population = circuit.edges['thalamus_neurons__thalamus_neurons__chemical'] edge_population.get(query, properties).head() ``` -------------------------------- ### Query Node IDs with Filters (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/02_node_populations.ipynb Illustrates how to query and filter node IDs based on specific properties. Examples include filtering by a single region, multiple properties ('region' and 'mtype'), and using regular expressions for pattern matching ('etype'). ```python node_population.ids() node_population.ids({'region': 'mc2;VPL'}) node_population.ids({'region': 'mc2;VPL', 'mtype': 'VPL_TC'}) node_population.ids({'etype': {'$regex': '.*ltb.*'}, 'region': 'mc2;VPL'}) ``` -------------------------------- ### Retrieve Node Positions and Orientations (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/02_node_populations.ipynb Demonstrates how to get the spatial positions of nodes within a population using `.positions().head()` for a preview. It also shows how to retrieve the orientation matrix for a specific node ID using `.orientations(1)`. ```python node_population.positions().head() node_population.orientations(1) ``` -------------------------------- ### Validate SONATA Circuit Files with BluePySnap Source: https://context7.com/openbraininstitute/snap/llms.txt This code example shows how to validate SONATA circuit files for integrity, required fields, and correct references using the `bluepysnap.circuit_validation.validate` function. It details parameters for controlling the validation process, such as skipping slow checks, showing only errors, and ignoring data type errors. The description lists common validation checks performed by the function. ```python from bluepysnap.circuit_validation import validate # Validate circuit configuration errors = validate( config_file='/path/to/circuit_config.json', skip_slow=False, # Set True to skip slow validation checks only_errors=False, # Set True to only show fatal errors ignore_datatype_errors=False # Set True to ignore dtype mismatches ) # Validation checks include: # - Circuit config file integrity # - Existence of node/edge files and component directories # - Presence of SONATA required fields # - Correctness of edge-to-node bindings # - Existence of morphology files # - Edge indices correctness (slow check) # - All edges reference existing nodes (slow check) # Command line usage: # bluepysnap validate-circuit /path/to/circuit_config.json # bluepysnap validate-circuit /path/to/circuit_config.json --skip-slow # bluepysnap validate-circuit /path/to/circuit_config.json --only-errors ``` -------------------------------- ### Retrieve Report Time Properties in BluePySNAP Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/07_frame_reports.ipynb Fetches and prints the start time, stop time, time step (dt), and time units of a frame report. It may issue a warning if the report's dt differs from the simulation's global dt. ```python print( soma_report.time_start, soma_report.time_stop, soma_report.dt, soma_report.time_units ) ``` -------------------------------- ### Access Neuronal Morphology with BluePySnap Source: https://context7.com/openbraininstitute/snap/llms.txt This snippet demonstrates how to load and analyze detailed neuronal morphologies associated with nodes in a SONATA circuit using BluePySnap. It shows how to access morphology helper objects, retrieve specific morphologies by node ID, get file paths, and extract morphology names. It also highlights that the morphology objects are from the MorphIO library, allowing access to sections, soma, and points. ```python from bluepysnap import Circuit circuit = Circuit('/path/to/circuit_config.json') node_pop = circuit.nodes['layer5'] # Access morphology helper morph_helper = node_pop.morph # Get morphology for a specific node node_id = 42 morph = morph_helper.get(node_id) # Get path to morphology file morph_path = morph_helper.get_filepath(node_id) # Get morphology name morph_name = node_pop.get(group=node_id, properties=Node.MORPHOLOGY) # Morphology object is from MorphIO library # Access sections, points, etc. sections = morph.sections soma = morph.soma points = morph.points ``` -------------------------------- ### Perform Advanced Node Queries in BluePySnap Source: https://context7.com/openbraininstitute/snap/llms.txt This Python code demonstrates advanced node querying capabilities in BluePySnap, allowing complex filtering based on logical operators and property ranges. It shows how to perform range queries, combine multiple properties with implicit AND, use explicit AND/OR operators, and query based on lists of property values. It also includes examples of sampling, limiting results, and retrieving available properties and their unique values. ```python from bluepysnap import Circuit from bluepysnap.sonata_constants import Node circuit = Circuit('/path/to/circuit_config.json') node_pop = circuit.nodes['layer5'] # Range queries (for numeric properties) x_range_ids = node_pop.ids({Node.X: (100.0, 200.0)}) y_range_ids = node_pop.ids({Node.Y: (50.0, 150.0)}) # Multiple property filter (implicit AND) combined_ids = node_pop.ids({ Node.LAYER: 5, Node.MTYPE: 'L5_PC', Node.X: (0, 100) }) # Explicit OR operator or_query_ids = node_pop.ids({ '$or': [ {Node.LAYER: 2}, {Node.LAYER: 3}, {Node.MTYPE: 'L1_SLAC'} ] }) # Explicit AND operator and_query_ids = node_pop.ids({ '$and': [ {Node.LAYER: [2, 3, 4]}, {Node.X: (100, 200)}, {Node.Y: (50, 150)} ] }) # Nested logical operators nested_ids = node_pop.ids({ '$or': [ { '$and': [ {Node.LAYER: 5}, {Node.MTYPE: 'L5_PC'} ] }, { '$and': [ {Node.LAYER: 6}, {Node.MTYPE: 'L6_PC'} ] } ] }) # Property value lists (any match) mtype_list_ids = node_pop.ids({Node.MTYPE: ['L5_PC', 'L5_MC', 'L5_BTC']}) # Combine with sampling and limiting filtered_sample = node_pop.ids( group={Node.LAYER: [4, 5, 6]}, sample=500, # Random sample of 500 limit=None ) # Check available properties props = node_pop.property_names print(f"Available properties: {props}") # Get unique values for a property mtypes = node_pop.property_values(Node.MTYPE) layers = node_pop.property_values(Node.LAYER) ``` -------------------------------- ### Query Node Sets with OR Condition (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb This code demonstrates how to execute an OR query across different properties or node sets. It uses the '$or' key with a list of query dictionaries. In this example, it retrieves nodes that either have 'mtype' as 'VPL_IN' OR 'region' as 'mc2;Rt' from the 'thalamus_neurons' population, returning the specified properties. ```python result = circuit.nodes['thalamus_neurons'].get({ '$or':[ {'mtype': 'VPL_IN'}, {'region': 'mc2;Rt'} ]}, properties=['mtype', 'region']) for pair in result.groupby(['mtype', 'region'], observed=True).groups.keys(): print(pair) ``` -------------------------------- ### Find Chemical Synapses by Edge Type (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb Illustrates how to query edges based on their 'population_type', specifically retrieving 'chemical' synapses. Due to the massive number of edges, a subset of 'edge_id's is queried as an example. This method can be used to filter edges by their synaptic type. ```python circuit.edges.get({'population_type':'chemical', 'edge_id': [*range(5)]}) # Since the number of edges is massive, we only query a fraction of all the `edge_id`s ``` -------------------------------- ### Python: Query Node Properties by IDs Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/03_node_properties.ipynb This Python snippet demonstrates how to retrieve specific properties of nodes filtered by a region. It first obtains the IDs for nodes in the 'mc2;Rt' region and then uses the `get` method to fetch the 'region', 'synapse_class', 'x', 'y', and 'z' properties for these nodes. The output is a pandas DataFrame. ```python Rt_ids = node_population.ids({'region': 'mc2;Rt'}) node_population.get(Rt_ids, properties=['region', 'synapse_class', 'x', 'y', 'z']).head() ``` -------------------------------- ### Query Node Populations with Blue Brain SNAP Source: https://context7.com/openbraininstitute/snap/llms.txt Allows querying and filtering of neuron populations by properties, retrieving spatial positions, and accessing morphological data. It supports filtering by various properties, complex queries with logical operators, retrieving properties as DataFrames or Series, getting 3D positions and orientation matrices, and counting or sampling nodes matching criteria. ```python from bluepysnap import Circuit from bluepysnap.sonata_constants import Node circuit = Circuit('/path/to/circuit_config.json') # Get specific node population node_pop = circuit.nodes['layer5'] # Get all node IDs all_ids = node_pop.ids() # Filter nodes by properties layer5_ids = node_pop.ids({Node.LAYER: 5}) mtype_ids = node_pop.ids({Node.MTYPE: ['L5_PC', 'L5_MC']}) spatial_ids = node_pop.ids({Node.X: (100, 200), Node.Y: (50, 150)}) # Complex queries with logical operators complex_ids = node_pop.ids({ '$or': [ {Node.LAYER: [2, 3]}, {Node.X: (0, 100), Node.MTYPE: 'L1_SLAC'} ] }) # Get node properties as DataFrame properties_df = node_pop.get(group=layer5_ids, properties=[Node.MTYPE, Node.ETYPE]) # Get single node properties as Series single_node = node_pop.get(group=0) # Get 3D positions positions = node_pop.positions(group=layer5_ids) # DataFrame with x, y, z columns # Get orientation matrices orientations = node_pop.orientations(group=layer5_ids) # Get available property names available_props = node_pop.property_names # Get property data types dtypes = node_pop.property_dtypes # Count nodes matching criteria count = node_pop.count(group={Node.LAYER: 5}) # Random sampling sample_ids = node_pop.ids(group={Node.LAYER: 5}, sample=100) # Limit results limited_ids = node_pop.ids(group=None, limit=1000) ``` -------------------------------- ### Access Edge Populations with Blue Brain SNAP Source: https://context7.com/openbraininstitute/snap/llms.txt Enables access to synaptic connectivity data, including source/target neurons, synaptic properties, and connection topology. It allows filtering edges by properties, retrieving edge properties, accessing source and target node populations, and getting afferent, efferent, and pathway edges. It also provides a method to iterate over connections between nodes. ```python from bluepysnap import Circuit from bluepysnap.sonata_constants import Edge circuit = Circuit('/path/to/circuit_config.json') # Get edge population edge_pop = circuit.edges['layer5_connections'] # Get all edge IDs all_edge_ids = edge_pop.ids() # Get edges by property filters strong_synapses = edge_pop.ids({ Edge.SYN_WEIGHT: (0.5, 2.0), Edge.AXONAL_DELAY: (0.1, 1.5) }) # Get edge properties edge_props = edge_pop.get( edge_ids=strong_synapses, properties=[Edge.SYN_WEIGHT, Edge.AXONAL_DELAY, Edge.POST_SECTION_ID] ) # Get source and target node IDs source_target_df = edge_pop.get( edge_ids=[0, 1, 2], properties=[Edge.SOURCE_NODE_ID, Edge.TARGET_NODE_ID] ) # Access source/target node populations source_nodes = edge_pop.source # NodePopulation object target_nodes = edge_pop.target # NodePopulation object # Get afferent edges (incoming connections) for target nodes afferent_edges = edge_pop.afferent_edges(target=[100, 200, 300]) # Get efferent edges (outgoing connections) from source nodes efferent_edges = edge_pop.efferent_edges(source=[10, 20, 30]) # Get pathway edges (connections between specific source and target groups) pathway_edges = edge_pop.pathway_edges( source=[10, 20, 30], target=[100, 200, 300] ) # Iterate over connections between nodes for source_id, target_id, edge_ids in edge_pop.iter_connections( source=[10, 20], target=[100, 200, 300] ): # Process connections props = edge_pop.get(edge_ids, properties=[Edge.SYN_WEIGHT]) print(f"Connection {source_id} -> {target_id}: {len(edge_ids)} synapses") ``` -------------------------------- ### Import BluePySnap Package Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Initializes the BluePySnap environment by importing the necessary package. This is the first step before interacting with simulation data. ```python import bluepysnap ``` -------------------------------- ### Initialize bluepysnap Circuit and Load Data (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/03_node_properties.ipynb Sets up the necessary environment for circuit simulation by importing libraries, defining constants, and loading a circuit from a specified path using bluepysnap. Assumes the circuit file is available. ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm %matplotlib inline import bluepysnap POINT_SIZE = 1 SAMPLE_SIZE = 30000 # To keep the plots constant np.random.seed(0) # load the circuit and store the node population circuit_path = "sonata/circuit_sonata.json" circuit = bluepysnap.Circuit(circuit_path) ``` -------------------------------- ### Access Simulation Configuration Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Retrieves the entire configuration dictionary for the loaded SONATA simulation. This includes details about inputs, network, output, reports, and run parameters. ```python simulation.config ``` -------------------------------- ### Get Edge IDs or Properties using pathway_edges in Python Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb Illustrates retrieving edge IDs or specific properties between known source and target node IDs using the `pathway_edges` function. This function can be used to get just the edge IDs or to fetch properties like `@source_node` and `@target_node`. Dependencies include a Snap edge population object. ```python source_ids = [1] target_ids = [27204] properties = ['@source_node', '@target_node'] # Get just edge IDs edge_population.pathway_edges(source_ids, target_ids) # Get specific properties edge_population.pathway_edges(source_ids, target_ids, properties=properties) ``` -------------------------------- ### Load SONATA Simulation with BluePySnap Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Loads a SONATA simulation by providing the path to the simulation configuration file. This allows access to various simulation properties. ```python simulation_path = "/gpfs/bbp.cscs.ch/project/proj12/NSE/bluepysnap-functional-tests/simulation_config_bluepy_examples.json" simulation = bluepysnap.Simulation(simulation_path) ``` -------------------------------- ### Download SONATA Circuit Data with Python Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/01_circuits.ipynb This snippet downloads a SONATA circuit archive from a URL and extracts its contents. It utilizes Python's `urllib.request` for downloading and `zipfile` for extraction. Ensure you have internet connectivity and sufficient disk space for the download. ```python from urllib.request import urlretrieve from pathlib import Path from zipfile import ZipFile url = "https://zenodo.org/record/6259750/files/thalamus_microcircuit.zip?download=1" extract_dir="." circuit_path = Path('./sonata') if not circuit_path.exists(): zip_path, _ = urlretrieve(url) with ZipFile(zip_path, "r") as f: f.extractall(extract_dir) ``` -------------------------------- ### Import and Load SONATA Circuit with BlueBrain SNAP Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/01_circuits.ipynb This code demonstrates how to import the `bluepysnap` package and load a SONATA circuit from a specified JSON file path. The `bluepysnap.Circuit` class is used for this purpose. The input is the file path to the circuit's JSON configuration. ```python import bluepysnap circuit_path = "sonata/circuit_sonata.json" circuit = bluepysnap.Circuit(circuit_path) ``` -------------------------------- ### Iterate Connections: Return Edge Count Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/11_iter_connections.ipynb Demonstrates using `iter_connections` with `return_edge_count=True` to get the number of edges between each source-target pair. The generator yields tuples of (source_id, target_id, edge_count). ```python source_ids = [1] target_ids = [27204] edge_population = circuit.edges['thalamus_neurons__thalamus_neurons__chemical'] for _source_id, _target_id, _edge_count in edge_population.iter_connections(source_ids, target_ids, return_edge_count=True): print(_source_id, '-', _target_id) print(f'Edge count: {_edge_count}') ``` -------------------------------- ### Load Circuit with BluePySnap Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb Loads a circuit from a specified path using the bluepysnap library. Assumes the circuit file has already been downloaded. Requires the bluepysnap and numpy libraries. ```python import bluepysnap import numpy as np circuit_path = "sonata/circuit_sonata.json" circuit = bluepysnap.Circuit(circuit_path) ``` -------------------------------- ### Load SONATA Circuit with BluePySnap Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/04_edge_properties.ipynb Loads a SONATA circuit from a specified JSON file using the bluepysnap library. This is a prerequisite for accessing circuit and edge data. It imports necessary libraries and initializes the Circuit object. ```python import bluepysnap import matplotlib.pyplot as plt %matplotlib inline # load the circuit and store the node population circuit_path = "sonata/circuit_sonata.json" circuit = bluepysnap.Circuit(circuit_path) ``` -------------------------------- ### Get Node Population Object in BluePySNAP Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/07_frame_reports.ipynb Retrieves the NodePopulation object associated with a specific population from the soma report. This object contains information about the individual nodes (neurons) within that population. ```python node_population = soma_pop.nodes print(f'{node_population.name}: {type(node_population)}') ``` -------------------------------- ### Get Population Names from SomaReport in BluePySNAP Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/07_frame_reports.ipynb Retrieves the names of all populations present within a soma report. This is useful for identifying which neuronal populations are included in the simulation's somatic data. ```python soma_report.population_names ``` -------------------------------- ### Load Simulation Configuration with BluePySnap Source: https://context7.com/openbraininstitute/snap/llms.txt Initializes a Simulation object from a configuration file, providing access to circuit, time parameters, input specifications, and run configurations. Dependencies include the bluepysnap library. ```python from bluepysnap import Simulation # Initialize simulation from config sim = Simulation('/path/to/simulation_config.json') # Access the circuit used in simulation circuit = sim.circuit # Get simulation configuration config = sim.config # Access time parameters t_start = sim.time_start # Returns 0 t_stop = sim.time_stop # End time in ms dt = sim.dt # Time step in ms time_units = sim.time_units # Returns 'ms' # Access simulation conditions conditions = sim.conditions # Get target simulator simulator = sim.simulator # e.g., 'NEURON' # Access node sets (may override circuit node sets) node_sets = sim.node_sets # Access simulation inputs (stimuli, spike trains) inputs = sim.inputs # Access output configuration output_config = sim.output # Access run parameters run_params = sim.run ``` -------------------------------- ### Load Circuit with BluePySnap (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/08_nodesets.ipynb Initializes the BluePySnap library and loads a circuit from a specified JSON file. This is a prerequisite for interacting with circuit components. ```python import bluepysnap import pandas as pd circuit_path = "sonata/circuit_sonata.json" circuit = bluepysnap.Circuit(circuit_path) ``` -------------------------------- ### Load Circuit and Access Node Populations (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/02_node_populations.ipynb Initializes the BluePySnap library, loads a circuit from a specified path, and accesses the names of available node populations. Assumes the circuit file has already been downloaded. ```python import bluepysnap circuit_path = "sonata/circuit_sonata.json" circuit = bluepysnap.Circuit(circuit_path) circuit.nodes.population_names ``` -------------------------------- ### Filter Spike Report Data Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/06_spike_reports.ipynb Filters the spike report based on specified criteria, such as population group, start time, and stop time. This allows for focused analysis of specific subsets of spike data. ```python filtered = spikes.filter(group={'layer':'SP'}, t_start=1, t_stop=100) filtered.report.head() ``` -------------------------------- ### Access and Query Node IDs in BluePySNAP Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/07_frame_reports.ipynb Retrieves node IDs from a population and fetches specific properties (e.g., layer, synapse_class, coordinates) for those nodes using the get method. The .head() displays the first few results. ```python ids = soma_pop.node_ids node_population.get(ids, properties=['layer','synapse_class','x','y','z']).head() ``` -------------------------------- ### Access Targeted Simulator Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Identifies the specific simulator used for running the SONATA simulation, such as CORENEURON. ```python simulation.simulator ``` -------------------------------- ### Access Spike Report Properties (Time, dt) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/06_spike_reports.ipynb Retrieves and prints the start time, end time, and time step (dt) of the spike report. These fundamental properties define the temporal scope of the simulation data. ```python print( spikes.time_start, spikes.time_stop, spikes.dt ) ``` -------------------------------- ### Circuit Initialization API Source: https://context7.com/openbraininstitute/snap/llms.txt Load a SONATA circuit from a configuration file to access static network structure including nodes, edges, and morphologies. ```APIDOC ## Circuit Initialization ### Description Load a SONATA circuit from a configuration file to access static network structure including nodes, edges, and morphologies. ### Method ```python from bluepysnap import Circuit # Initialize circuit from config file circuit = Circuit('/path/to/circuit_config.json') # Access configuration dictionary config = circuit.config # Access node populations (neurons, astrocytes, etc.) nodes = circuit.nodes # Access edge populations (synaptic connections) edges = circuit.edges # Access node sets (predefined neuron groups) node_sets = circuit.node_sets # Check if circuit is partially loaded is_partial = circuit.partial_config ``` ### Parameters N/A for initialization, as it's done via constructor. ### Request Example N/A ### Response #### Success Response (200) - **circuit** (Circuit Object) - Initialized circuit object for further access. - **config** (dict) - Configuration dictionary of the circuit. - **nodes** (NodePopulation Collection) - Collection of node populations. - **edges** (EdgePopulation Collection) - Collection of edge populations. - **node_sets** (NodeSet Collection) - Collection of node sets. - **partial_config** (bool) - Indicates if the circuit configuration is partially loaded. #### Response Example N/A ``` -------------------------------- ### Get Unique Node Population Properties Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/03_node_properties.ipynb This code snippet retrieves all unique values for a specified property (in this case, 'mtype') within the node population. This is useful for understanding the different types of neurons or other entities present in the simulation. ```python node_population.property_values("mtype") ``` -------------------------------- ### Access Simulation Frame Reports Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Accesses the frame reports object, which provides access to various simulation output reports, such as membrane potential or firing rates over time. ```python simulation.reports ``` -------------------------------- ### Initialize bluepysnap Circuit Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/11_iter_connections.ipynb Initializes the bluepysnap Circuit object, which is required before iterating over connections. This step assumes the circuit data has already been downloaded. ```python import bluepysnap import numpy as np from time import time circuit_path = "sonata/circuit_sonata.json" circuit = bluepysnap.Circuit(circuit_path) ``` -------------------------------- ### Get Unique Node Population Property Pairs Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/03_node_properties.ipynb This code retrieves unique pairs of specified properties (e.g., 'mtype' and 'etype') from the node population. It then drops duplicate pairs and returns the unique combinations as a NumPy array, which can be helpful for analyzing co-occurrences of attributes. ```python node_population.get(properties=['mtype','etype']).drop_duplicates().values ``` -------------------------------- ### Fetch Edges Using Node Properties and Queries (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb Demonstrates fetching afferent edges and nodes using different query methods, including node sets and dictionaries representing node properties. It shows how to resolve node IDs internally by passing queries directly to functions. This is useful for finding synapses between specific regions or node sets. ```python print('Fetching connecting edges...') # using a node set display(edge_population.afferent_edges('mc2;VPL')) # using an external node set ext_node_set = bluepysnap.node_sets.NodeSets.from_dict({'ext_mc2;VPL': {'region': 'mc2;VPL'}}) display(edge_population.afferent_edges(ext_node_set['ext_mc2;VPL'])) # using a query display(edge_population.afferent_edges({'region': 'mc2;VPL'})) # just to demonstrate the queries with a node function print("\nFetching source nodes...") # using afferent_edges and properties source_nodes = np.unique(edge_population.afferent_edges({'region': 'mc2;VPL'}, properties=['@source_node'])) display(source_nodes) # using afferent_nodes display(edge_population.afferent_nodes('mc2;VPL')) ``` -------------------------------- ### Find Source/Target Nodes from Known Target/Source IDs in Python Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/10_edge_queries.ipynb Demonstrates how to find source nodes connected to known target IDs and target nodes connected to known source IDs using `afferent_nodes` and `efferent_nodes` respectively. It also shows how to fetch properties of these identified nodes from their respective populations. Dependencies include Snap edge and node population objects. ```python source_ids = [1] target_ids = [27204] # Find connected nodes source_nodes = edge_population.afferent_nodes(target_ids) target_nodes = edge_population.efferent_nodes(source_ids) # Fetch properties of found nodes edge_population.source.get(source_nodes, properties=['mtype', 'etype','layer']).head() edge_population.target.get(target_nodes, properties=['mtype', 'etype','layer']).head() ``` -------------------------------- ### Access Simulation Run Properties Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Accesses the run section of the simulation configuration, which contains parameters like random seed and total simulation time. ```python simulation.run ``` -------------------------------- ### Get Property Data Types for Thalamus Neurons (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/09_node_queries.ipynb This snippet retrieves the data types of all properties associated with the 'thalamus_neurons' node population. It's useful for understanding which properties are categorical, object, or numerical (float) before formulating specific queries, especially for range-based queries. ```python circuit.nodes['thalamus_neurons'].property_dtypes ``` -------------------------------- ### Initialize SONATA Circuit with Blue Brain SNAP Source: https://context7.com/openbraininstitute/snap/llms.txt Loads a SONATA circuit from a configuration file to access static network structure including nodes, edges, and morphologies. It allows access to the configuration, node populations, edge populations, and node sets. It also provides a flag to check if the circuit is partially loaded. ```python from bluepysnap import Circuit # Initialize circuit from config file circuit = Circuit('/path/to/circuit_config.json') # Access configuration dictionary config = circuit.config # Access node populations (neurons, astrocytes, etc.) nodes = circuit.nodes # Access edge populations (synaptic connections) edges = circuit.edges # Access node sets (predefined neuron groups) node_sets = circuit.node_sets # Check if circuit is partially loaded is_partial = circuit.partial_config ``` -------------------------------- ### Access SONATA Circuit Properties with BlueBrain SNAP Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/01_circuits.ipynb This snippet shows how to access the core properties of a loaded SONATA circuit object using BlueBrain SNAP. It includes accessing the circuit's configuration, node populations, edge populations, and node sets. The output varies depending on the circuit's structure. ```python circuit.config ``` ```python circuit.nodes ``` ```python circuit.edges ``` ```python circuit.node_sets ``` -------------------------------- ### Access Simulation Conditions Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Accesses the conditions object for the simulation, if any are defined. This can include information about simulation states or environmental factors. ```python simulation.conditions ``` -------------------------------- ### Access Simulation Spike Reports Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Retrieves the spike report object, allowing access to information about neuronal spiking activity generated during the simulation. ```python simulation.spikes ``` -------------------------------- ### Retrieve Node Positions from Node Set Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/03_node_properties.ipynb This code snippet demonstrates how to get the positions of nodes belonging to a specific node set. It shows two methods: one using the node set's name and another using the node set object directly, which is useful for external node sets. ```python df_Rt = node_population.positions('mc2;Rt') ``` ```python df_VPL = node_population.positions(circuit.node_sets['mc2;VPL']) ``` -------------------------------- ### Access Simulation Circuit Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Retrieves the circuit object associated with the simulation, providing access to the network structure and cell properties. ```python simulation.circuit ``` -------------------------------- ### Validate SONATA Simulation Configuration with BluePySnap Source: https://context7.com/openbraininstitute/snap/llms.txt This Python snippet illustrates how to validate SONATA simulation configuration files for correctness and completeness using `bluepysnap.simulation_validation.validate`. It explains the parameters available for tailoring the validation, such as ignoring data type errors, and enumerates the types of checks performed, including mandatory fields, data types, file paths, and references to node sets. ```python from bluepysnap.simulation_validation import validate # Validate simulation configuration errors = validate( config_file='/path/to/simulation_config.json', ignore_datatype_errors=False ) # Validation checks include: # - All mandatory fields present # - Property data types and values match specification # - Paths in config exist # - Node sets referenced in config exist # - Input spike file node IDs found in source node sets # - Electrode file node IDs found in simulation node set # - Neurodamus helpers and variables exist (if neurodamus available) # Command line usage: # bluepysnap validate-simulation /path/to/simulation_config.json # bluepysnap validate-simulation /path/to/simulation_config.json --ignore-datatype-errors ``` -------------------------------- ### Access and Inspect Edge Population Properties Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/04_edge_properties.ipynb Retrieves a specific edge population from the circuit and lists its available properties. It also demonstrates how to access the name and size of the edge population. This is useful for understanding the data contained within different edge types. ```python # we can also find other edge names with "circuit.edges.population_names" edge_population = circuit.edges["thalamus_neurons__thalamus_neurons__chemical"] print(edge_population.property_names) print("Name:", edge_population.name) print("Population size:", edge_population.size) ``` -------------------------------- ### Query Nodes Using Node Set vs. Query (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/08_nodesets.ipynb Compares the results of querying node IDs using a defined node set ('VPL_TC') versus a direct query with the equivalent criteria. This demonstrates the equivalence and efficiency of using node sets. ```python node_set_result = circuit.nodes.ids('VPL_TC') print(f'Ids found: {len(node_set_result)}') query_result = circuit.nodes.ids({'mtype': 'VPL_TC'}) print(f'Queries result in the same outcome : {node_set_result == query_result}') ``` -------------------------------- ### Load Node Sets from File (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/08_nodesets.ipynb Loads node sets from a JSON file using the `NodeSets.from_file` method. This is useful for working with node sets that are not embedded within the circuit configuration. ```python node_sets_circuit = bluepysnap.node_sets.NodeSets.from_file('./sonata/networks/nodes/node_sets.json') print(f"Contents match: {node_sets_circuit.content == circuit.node_sets.content}") ``` -------------------------------- ### Visualize Synapse Count Distribution Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/04_edge_properties.ipynb Generates a histogram visualizing the distribution of the number of synapses per connection. This is achieved by grouping the queried `synapses` DataFrame by source and target nodes and then plotting the size of each group. Requires matplotlib for plotting. ```python df = synapses.groupby(['@source_node', '@target_node']).size() ax = df.hist(bins=40,edgecolor='black', grid=False) ax.set_xlabel('Number of Synapses per Connection') ax.set_ylabel('Number of Connections') ``` -------------------------------- ### Query Pathway Edges and Properties Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/04_edge_properties.ipynb Queries specific edges within a population based on source and target node properties (mtype and region). It retrieves the '@source_node', '@target_node', and 'u_syn' properties for these specific connections. This allows for targeted analysis of subsets of edges. ```python post= {'mtype': 'VPL_TC', 'region': 'mc2;VPL'} pre = {'mtype': 'Rt_RC', 'region': 'mc2;Rt'} synapses = edge_population.pathway_edges( source=pre, target=post, properties=['@source_node', '@target_node', 'u_syn']) ``` -------------------------------- ### Randomize Connection Order with Shuffle Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/11_iter_connections.ipynb Demonstrates how to randomize the order of connection results by setting the `shuffle` flag to `True` in the `iter_connections` method. This is useful for analyzing data where a consistent order is not required. The output is printed showing source and target node IDs. ```python np.random.seed(0) # Just to keep the results consistent in the notebook it = enumerate(edge_population.iter_connections(range(10), range(10), shuffle=True)) for i, (_source_id, _target_id) in it: print(f'{i+1:2d}: source: {_source_id.id:2d} --- target: {_target_id.id:2d}') ``` -------------------------------- ### Visualize Node Positions by Layer in Snap Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/03_node_properties.ipynb This snippet visualizes the positions of nodes in each layer on a 2D plane (x-y), using different colors for each layer. It retrieves node positions and layer information, samples the data, and plots scatter points for each layer. It requires 'matplotlib.pyplot', 'matplotlib.cm', 'numpy', and assumes 'node_population' is defined and constants like SAMPLE_SIZE and POINT_SIZE are set. ```python # get all cell positions and group by layer df_all = node_population.get(properties=['x', 'y', 'z', 'layer']) df_grouped = df_all.sample(SAMPLE_SIZE).groupby('layer') fig, ax = plt.subplots(nrows=1, ncols=1) colors = cm.gnuplot(np.linspace(0.0, 0.8, len(df_grouped))) for i, (name, group) in enumerate(df_grouped): group.plot(x='x', y='y', c=[colors[i]], kind='scatter', s=POINT_SIZE, ax=ax, label=name) ax.legend(bbox_to_anchor=(1.2, 1.03), loc="upper right"); ``` -------------------------------- ### Access Simulation Node Sets Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Accesses the node sets object, which defines groups of cells or nodes within the simulation's circuit. This is useful for targeting specific populations. ```python simulation.node_sets ``` -------------------------------- ### Access Simulation Time Units Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/05_simulations.ipynb Retrieves the units used for time in the simulation, typically milliseconds (ms). ```python simulation.time_units ``` -------------------------------- ### Access Circuit Node Sets (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/08_nodesets.ipynb Retrieves the content of node sets directly from an already loaded Snap circuit object. Node sets are predefined queries for nodes, useful for efficient selection. ```python circuit.node_sets.content ``` -------------------------------- ### Create Node Sets from Dictionary (Python) Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/08_nodesets.ipynb Dynamically creates a `NodeSets` object from a Python dictionary. This allows for on-the-fly definition of node sets, useful for experimentation or augmenting existing sets without modifying configuration files. ```python node_sets_0_9 = bluepysnap.node_sets.NodeSets.from_dict({'nodes_0-9': {'node_id': [*range(10)]}}) node_sets_0_9.content ``` -------------------------------- ### Plotting All Available Trace Data with Python Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/07_frame_reports.ipynb Plots all available trace data from a FrameReport by calling `filter()` without arguments, followed by `trace()`. This allows visualization of the entire dataset accessible through the report. ```python soma_report.filter().trace(); ``` -------------------------------- ### Plot Synapse Positions by Type in Snap Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/03_node_properties.ipynb This code plots the spatial distribution of synapses in the x-z plane, colored by synapse type. It samples the data for visualization and requires 'matplotlib.pyplot' and assumes 'df_all' is populated with node data including 'synapse_class', 'x', and 'z'. Constants POINT_SIZE and SAMPLE_SIZE are expected to be defined. ```python fig, ax = plt.subplots(nrows=1, ncols=1) df_grouped = df_all.sample(SAMPLE_SIZE).groupby('synapse_class') for color, (name, group) in zip(('r', 'b'), df_grouped): group.plot.scatter(x='x', y='z', s=POINT_SIZE, c=[color], ax=ax, label=name) ax.axis('equal') ax.set_xlabel(u'x (μm)') ax.set_ylabel(u'z (μm)'); ``` -------------------------------- ### Edge Population Access API Source: https://context7.com/openbraininstitute/snap/llms.txt Access synaptic connectivity data including source/target neurons, synaptic properties, and connection topology. ```APIDOC ## Edge Population Access ### Description Access synaptic connectivity data including source/target neurons, synaptic properties, and connection topology. ### Method ```python from bluepysnap import Circuit from bluepysnap.sonata_constants import Edge circuit = Circuit('/path/to/circuit_config.json') # Get edge population edge_pop = circuit.edges['layer5_connections'] # Get all edge IDs all_edge_ids = edge_pop.ids() # Get edges by property filters strong_synapses = edge_pop.ids({ Edge.SYN_WEIGHT: (0.5, 2.0), Edge.AXONAL_DELAY: (0.1, 1.5) }) # Get edge properties edge_props = edge_pop.get( edge_ids=strong_synapses, properties=[Edge.SYN_WEIGHT, Edge.AXONAL_DELAY, Edge.POST_SECTION_ID] ) # Get source and target node IDs source_target_df = edge_pop.get( edge_ids=[0, 1, 2], properties=[Edge.SOURCE_NODE_ID, Edge.TARGET_NODE_ID] ) # Access source/target node populations source_nodes = edge_pop.source # NodePopulation object target_nodes = edge_pop.target # NodePopulation object # Get afferent edges (incoming connections) for target nodes afferent_edges = edge_pop.afferent_edges(target=[100, 200, 300]) # Get efferent edges (outgoing connections) from source nodes efferent_edges = edge_pop.efferent_edges(source=[10, 20, 30]) # Get pathway edges (connections between specific source and target groups) pathway_edges = edge_pop.pathway_edges( source=[10, 20, 30], target=[100, 200, 300] ) # Iterate over connections between nodes for source_id, target_id, edge_ids in edge_pop.iter_connections( source=[10, 20], target=[100, 200, 300] ): # Process connections props = edge_pop.get(edge_ids, properties=[Edge.SYN_WEIGHT]) print(f"Connection {source_id} -> {target_id}: {len(edge_ids)} synapses") ``` ### Parameters #### Path Parameters N/A #### Query Parameters - **edge_ids** (list) - List of edge IDs to query. - **properties** (list) - List of property names to retrieve for edges. - **source** (list) - List of source node IDs for filtering. - **target** (list) - List of target node IDs for filtering. #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **ids() return** (list) - List of edge IDs matching the criteria. - **get() return** (pandas.DataFrame) - DataFrame containing edge properties. - **source** (NodePopulation) - NodePopulation object representing source nodes. - **target** (NodePopulation) - NodePopulation object representing target nodes. - **afferent_edges() return** (list) - List of edge IDs afferent to the specified target nodes. - **efferent_edges() return** (list) - List of edge IDs efferent from the specified source nodes. - **pathway_edges() return** (list) - List of edge IDs between specified source and target nodes. - **iter_connections() yields** (tuple) - Yields source_id, target_id, and a list of edge_ids for connections. #### Response Example N/A ``` -------------------------------- ### Print Node Set Sizes in Python Source: https://github.com/openbraininstitute/snap/blob/main/doc/source/notebooks/11_iter_connections.ipynb This Python snippet calculates and prints the number of source and target nodes in a given set. It's a utility function for understanding the scale of the dataset being processed. ```python target_node_set = 'VPL_TC' print(f'Number of source nodes: {len(edge_population.source.ids(source_node_set))}') print(f'Number of target nodes: {len(edge_population.target.ids(target_node_set))}') ```