API Reference¶
Complete reference for all public functions in Brain Street View.
Experiment discovery¶
- bsv.find_connectivity_experiments(regions, mouse_line='', primary_injection=True, target_regions=None)[source]¶
Query the Allen API for connectivity experiments by injection region.
- Parameters:
regions (list of str) – Brain region acronyms to search for (e.g.
['VISp', 'VISl']). Ignored when target_regions is provided and regions is empty.mouse_line (str, optional) – Transgenic mouse line filter.
''for all lines,'0'for wild-type only.primary_injection (bool, optional) – If True, only return experiments where the region is the primary injection site.
target_regions (str or list of str or None, optional) – If provided, call
fetch_upstream_regions()to discover which source regions project to these target(s), then query experiments injected in those sources. If regions is also non-empty it is used as an additional filter (intersection).
- Returns:
Experiment IDs matching the query.
- Return type:
list of int
- bsv.fetch_upstream_regions(target_regions, min_projection_volume=0.01, mouse_line='')[source]¶
Query the Allen API for brain regions that project TO given target region(s).
Uses the precomputed ProjectionStructureUnionize table to find all anterograde tracing experiments with signal in the target structure(s), then returns the injection site acronyms (= upstream source regions).
- Parameters:
target_regions (str or list of str) – Target brain region acronym(s) (e.g.
'CP'or['CP', 'STR']).min_projection_volume (float, optional) – Minimum projection_volume (mm^3) threshold to count as a projection. Default is 0.01.
mouse_line (str, optional) – Reserved for API consistency with
find_connectivity_experiments(). Not used in the PSU query.
- Returns:
Unique injection-site acronyms of experiments projecting to the target, sorted alphabetically.
- Return type:
list of str
Data retrieval¶
- bsv.fetch_connectivity_data(experiment_ids, save_location, file_name, normalization_method, subtract_other_hemisphere, grouping_method='', allen_atlas_path='', load_all=False, input_regions=None, region_groups=None, export_metadata=True, reload=False, atlas_type='allen', atlas_resolution=10, grouping_bins=5)[source]¶
Download and cache projection density maps for a set of experiments.
- Parameters:
experiment_ids (list of int) – Experiment IDs returned by
find_connectivity_experiments().save_location (str) – Local directory for cached downloads.
file_name (str) – Base name for the cached metadata CSV.
''to skip caching.normalization_method (str) –
'none'or'injectionIntensity'(divide by injection volume).subtract_other_hemisphere (bool) – Subtract the contralateral hemisphere signal.
grouping_method (str, optional) – Group experiments by
'AP','ML','DV', or''(no grouping). For'AP'/'ML'/'DV'the continuous injection-site coordinate is binned into grouping_bins equal-width levels.grouping_bins (int, optional) – Number of equal-width bins (display rows) to split the injection coordinate into when grouping_method is
'AP'/'ML'/'DV'. Default is 5. Empty bins are dropped.allen_atlas_path (str, optional) – Path to the Allen CCF atlas directory.
load_all (bool, optional) – If True, also return individual (non-averaged) projection volumes.
input_regions (list of str, optional) – Region acronyms for region-based grouping.
region_groups (list of int, optional) – Group assignment per region (same length as input_regions).
export_metadata (bool, optional) – Write a per-experiment metadata CSV.
reload (bool, optional) – Re-download even if cached files exist.
atlas_type (str, optional) – Atlas type (default
'allen').atlas_resolution (int, optional) – Atlas resolution in micrometres (10 or 20).
- Returns:
combined_projection (numpy.ndarray) – Averaged projection density array (AP x DV x ML x groups).
combined_injection_info (dict) – Aggregated injection metadata across experiments.
individual_projections (numpy.ndarray or None) – Per-experiment volumes when load_all is True, else None.
experiment_region_info (dict) – Per-experiment region metadata.
- bsv.fetch_connectivity_images(experiment_id, save_file_path)[source]¶
Download the projection density grid for a single experiment.
Downloads
density.rawfrom the Allen API and extracts it into save_file_path. Skips the download if the file already exists.- Parameters:
experiment_id (int) – Allen experiment ID.
save_file_path (str) – Local directory to save the extracted file.
- Returns:
True on success, False on failure.
- Return type:
bool
- bsv.fetch_connectivity_summary(experiment_id, save_file_path)[source]¶
Download injection summary JSON for a single experiment.
- Parameters:
experiment_id (int) – Allen experiment ID.
save_file_path (str) – Local directory to save
injectionSummary_all.json.
- Returns:
True on success, False on failure.
- Return type:
bool
Visualization¶
- bsv.plot_connectivity(experiment_data, allen_atlas_path, output_region, number_of_chunks, number_of_pixels, plane, region_only, smoothing, color_limits, color, normalization_info='unknown', input_regions=None, region_groups=None, experiment_region_info=None, normalize_by_group=False, custom_slices=None, slice_averaging=0, atlas_type='allen', atlas_resolution=10)[source]¶
Plot 2D projection density slices for a target brain region.
- Parameters:
experiment_data (numpy.ndarray) – Projection density array from
fetch_connectivity_data().allen_atlas_path (str) – Path to the Allen CCF atlas directory.
output_region (str) – Target region acronym to visualize (e.g.
'CP').number_of_chunks (int) – Number of evenly spaced slices to display.
number_of_pixels (int) – Number of 2D histogram bins per axis for each slice. The physical bin size adapts to the spatial extent of the region (bin_size ≈ region_extent_voxels / number_of_pixels × atlas_resolution µm).
plane (str) –
'coronal'or'sagittal'.region_only (bool) – Mask the display to the target region boundary.
smoothing (float) – Gaussian smoothing sigma in pixels (0 for none).
color_limits (str or list) –
'global','per_slice', or[min, max].color (list or None) – RGB colour(s) for region groups, or None for default.
normalization_info (str, optional) – Label for the normalization used during data fetch.
input_regions (list of str, optional) – Source region acronyms for grouped display.
region_groups (list of int, optional) – Group assignment per input region.
experiment_region_info (dict, optional) – Per-experiment metadata from
fetch_connectivity_data().normalize_by_group (bool, optional) – Normalize each group independently.
custom_slices (list of int, optional) – Specific slice indices instead of evenly spaced.
slice_averaging (int, optional) – Number of adjacent slices to average around each custom slice.
atlas_type (str, optional) – Atlas type (default
'allen').atlas_resolution (int, optional) – Atlas resolution in micrometres (10 or 20).
- Returns:
proj_array (numpy.ndarray) – Projection matrix for each slice.
proj_coords (list) – Coordinate information for each slice.
- bsv.plot_connectivity_3d(injection_summary, allen_atlas_path, region_to_plot, color=None, plot_patch=True, animate=True, atlas_type='allen', atlas_resolution=10)[source]¶
Render injection sites and a target region as a 3D isosurface.
- Parameters:
injection_summary (dict) – Injection metadata from
fetch_connectivity_data().allen_atlas_path (str) – Path to the Allen CCF atlas directory.
region_to_plot (str) – Target region acronym (e.g.
'CP').color (list, optional) – RGB colour(s) for injection dots.
plot_patch (bool, optional) – Render the region as a solid isosurface (True) or grid (False).
animate (bool, optional) – Create a rotating animation.
atlas_type (str, optional) – Atlas type (default
'allen').atlas_resolution (int, optional) – Atlas resolution in micrometres (10 or 20).
- Returns:
Animation object if animate is True, otherwise the figure.
- Return type:
matplotlib.animation.FuncAnimation or matplotlib.figure.Figure
- bsv.plot_connectivity_matrix(projection_data, allen_atlas_path, target_regions, metric='mean', atlas_type='allen', atlas_resolution=10, normalize_rows=False, normalize_cols=False, cmap='viridis', annotate=True, figsize=None, title=None)[source]¶
Create an N x M connectivity matrix heatmap.
Build a matrix showing connectivity strength from N source regions to M target regions and display it as a heatmap.
- Parameters:
projection_data (dict) – Dictionary mapping source region acronyms to tuples returned by
fetch_connectivity_data:(combined_projection, combined_info, individual_projections, experiment_info). Only the first element (the projection array) is used.allen_atlas_path (str) – Path to the directory containing atlas annotation volume and structure tree files.
target_regions (list of str) – List of target region acronyms (e.g.,
['CP', 'ACB', 'SNr']).metric (str, optional) –
Connectivity metric to compute:
'mean'(default): Mean projection density in target region.'max': Maximum projection density in target region.'volume': Total projection volume (sum of density * voxel volume).
atlas_type (str, optional) – Atlas type (default
'allen').atlas_resolution (int, optional) – Atlas resolution in micrometres (default 10).
normalize_rows (bool, optional) – If True, normalize each row (source) to [0, 1] by dividing by row max.
normalize_cols (bool, optional) – If True, normalize each column (target) to [0, 1] by dividing by col max.
cmap (str, optional) – Matplotlib colormap name (default
'viridis').annotate (bool, optional) – If True, display numeric values in each cell (default True).
figsize (tuple of float, optional) – Figure size
(width, height). If None, auto-calculated from matrix size.title (str, optional) – Plot title. If None, no title is displayed.
- Returns:
connectivity_matrix (numpy.ndarray) – 2D array of shape
(n_sources, n_targets)with connectivity values.fig (matplotlib.figure.Figure) – The matplotlib Figure object.
Examples
>>> from bsv import fetch_connectivity_data, find_connectivity_experiments >>> from bsv import plot_connectivity_matrix >>> source_regions = ['VISam', 'VISp'] >>> projection_data = {} >>> for src in source_regions: ... exp_ids = find_connectivity_experiments(injection_structure=src) ... data = fetch_connectivity_data( ... experiment_ids=exp_ids, ... save_location='./cache', ... file_name=f'{src}_proj' ... ) ... projection_data[src] = data >>> target_regions = ['CP', 'ACB'] >>> matrix, fig = plot_connectivity_matrix( ... projection_data=projection_data, ... allen_atlas_path='./atlas', ... target_regions=target_regions, ... metric='mean' ... )
- bsv.plot_connectivity_multi_region(experiment_data, allen_atlas_path, output_regions, number_of_chunks, number_of_pixels, plane, region_only, smoothing, color_limits, color, normalization_info='unknown', input_regions=None, region_groups=None, experiment_region_info=None, normalize_by_group=False, custom_slices=None, slice_averaging=0)[source]¶
Plot projections to multiple target regions for side-by-side comparison.
- Parameters:
experiment_data (numpy.ndarray) – Projection density array from
fetch_connectivity_data().allen_atlas_path (str) – Path to the Allen CCF atlas directory.
output_regions (list of str) – Target region acronyms (e.g.
['CP', 'ACB']).number_of_chunks (int) – Number of slices per region.
number_of_pixels (int) – Number of 2D histogram bins per axis for each slice. The physical bin size adapts to the spatial extent of the region (bin_size ≈ region_extent_voxels / number_of_pixels × atlas_resolution µm).
plane (str) –
'coronal'or'sagittal'.region_only (bool) – Mask display to each target region boundary.
smoothing (float) – Gaussian smoothing sigma in pixels.
color_limits (str or list) – Colour scale specification.
color (list or None) – RGB colour(s).
normalization_info (str, optional) – Normalization label.
input_regions (list of str, optional) – Source region acronyms for grouped display.
region_groups (list of int, optional) – Group assignment per input region.
experiment_region_info (dict, optional) – Per-experiment metadata.
normalize_by_group (bool, optional) – Normalize each group independently.
custom_slices (list of int, optional) – Specific slice indices.
slice_averaging (int, optional) – Adjacent-slice averaging radius.
- Returns:
proj_matrix_array (dict) –
{region: proj_array}for each output region.proj_coords_array (dict) –
{region: proj_coords}for each output region.
- bsv.plot_injections_combined(experiment_imgs, allen_atlas_path, input_regions, number_of_slices, number_of_pixels, plane, region_only, smoothing, color_limits, color, normalization_method, experiment_region_info=None, atlas_type='allen', atlas_resolution=10)[source]¶
Plot injection sites for multiple regions in a combined grid.
- Parameters:
experiment_imgs (numpy.ndarray) – Projection density array from
fetch_connectivity_data().allen_atlas_path (str) – Path to the Allen CCF atlas directory.
input_regions (list of str) – Source region acronyms to display.
number_of_slices (int) – Number of slices per region.
number_of_pixels (int) – Number of 2D histogram bins per axis for each slice. The physical bin size adapts to the spatial extent of the region (bin_size ≈ region_extent_voxels / number_of_pixels × atlas_resolution µm).
plane (str) –
'coronal'or'sagittal'.region_only (bool) – Mask to the region boundary.
smoothing (float) – Gaussian smoothing sigma in pixels.
color_limits (str or list) – Colour scale specification.
color (list or None) – RGB colour(s).
normalization_method (str) – Normalization label.
experiment_region_info (dict, optional) – Per-experiment metadata.
atlas_type (str, optional) – Atlas type (default
'allen').atlas_resolution (int, optional) – Atlas resolution in micrometres (10 or 20).
- bsv.plot_multi_region_injections(experiment_imgs, allen_atlas_path, input_regions, number_of_slices, number_of_pixels, plane, region_only, smoothing, color_limits, color, normalization_method, experiment_region_info=None)[source]¶
Plot injection sites for each input region separately.
Calls
plot_connectivity()once per region in input_regions.- Parameters:
experiment_imgs (numpy.ndarray) – Projection density array from
fetch_connectivity_data().allen_atlas_path (str) – Path to the Allen CCF atlas directory.
input_regions (list of str) – Source region acronyms.
number_of_slices (int) – Number of slices per region.
number_of_pixels (int) – Number of 2D histogram bins per axis for each slice. The physical bin size adapts to the spatial extent of the region (bin_size ≈ region_extent_voxels / number_of_pixels × atlas_resolution µm).
plane (str) –
'coronal'or'sagittal'.region_only (bool) – Mask to each region boundary.
smoothing (float) – Gaussian smoothing sigma in pixels.
color_limits (str or list) – Colour scale specification.
color (list or None) – RGB colour(s).
normalization_method (str) – Normalization label.
experiment_region_info (dict, optional) – Per-experiment metadata.
- bsv.plot_upstream_projectome(experiment_ids, source_regions, target_region, save_location, allen_atlas_path, atlas_resolution=10, atlas_type='allen', slice_thickness=2, density_percentile=99, static_ap=None, save_path=None, save_gif=None, gif_ap_step=2, gif_fps=8, gif_width=720)[source]¶
Interactive coronal slice viewer of upstream projections into a target region.
Displays a Jupyter widget with a coronal AP slider showing:
Atlas structure boundaries rendered at full atlas resolution
Per-source-region coloured heatmaps of projection density in the target region voxels (intensity ∝ projection density, colour = source region)
Injection site scatter dots sized by injection volume
- Parameters:
experiment_ids (list of int) – Experiment IDs, as returned by
find_connectivity_experiments()with target_regions set.source_regions (list of str) – Source region acronyms to display (subset of upstream regions).
target_region (str) – Target brain region acronym (e.g.
'CP').save_location (str) – Directory where
density.rawand injection summary files are cached.allen_atlas_path (str) – Path to the Allen CCF atlas directory.
atlas_resolution (int, optional) – Atlas resolution in micrometres (default 10).
atlas_type (str, optional) – Atlas type (default
'allen').slice_thickness (int, optional) – Number of 100 µm grid slices averaged either side of the displayed AP index when computing the projection heatmap (default 2).
density_percentile (float, optional) – Percentile of non-zero target-voxel density values used as the colour saturation ceiling (default 99). Lower values make dim signals brighter; raise toward 100 to avoid saturation on bright spots.
static_ap (int or None, optional) – If given, render this single AP slice (100 µm grid index) as a static figure instead of launching the interactive widget — used to produce documentation figures headlessly.
save_path (str or None, optional) – When static_ap is set, save the rendered figure to this path.
save_gif (str or None, optional) – If given, render an animated GIF scrolling through the AP slices that contain the target region and write it to this path (requires Pillow). Skips the interactive widget.
gif_ap_step (int, optional) – Step between AP slices when building the GIF (default 2).
gif_fps (int, optional) – Frames per second of the GIF (default 8).
gif_width (int, optional) – Width in pixels to downscale GIF frames to (default 720).
- bsv.threshold_connectivity(experiment_data, allen_atlas_path, input_region, number_of_chunks, number_of_pixels, plane, region_only, smoothing, color_limits, color, threshold, threshold_method='absolute', normalization_method='none', data_fetch_normalization='unknown', atlas_type='allen', atlas_resolution=10)[source]¶
Threshold projection density and visualize significant signals.
- Parameters:
experiment_data (numpy.ndarray) – Projection density array from
fetch_connectivity_data().allen_atlas_path (str) – Path to the Allen CCF atlas directory.
input_region (str) – Target region acronym (e.g.
'CP').number_of_chunks (int) – Number of slices.
number_of_pixels (int) – Number of 2D histogram bins per axis for each slice. The physical bin size adapts to the spatial extent of the region (bin_size ≈ region_extent_voxels / number_of_pixels × atlas_resolution µm).
plane (str) –
'coronal'or'sagittal'.region_only (bool) – Mask to the target region boundary.
smoothing (float) – Gaussian smoothing sigma in pixels.
color_limits (str or list) – Colour scale specification.
color (list or None) – RGB colour(s).
threshold (float) – Threshold value (interpretation depends on threshold_method).
threshold_method (str, optional) –
'absolute','percentile','zscore', or'relative'.normalization_method (str, optional) – Additional normalization:
'none','region','zscore', or'robust'.data_fetch_normalization (str, optional) – Label for the normalization applied during data fetch.
atlas_type (str, optional) – Atlas type (default
'allen').atlas_resolution (int, optional) – Atlas resolution in micrometres (10 or 20).
- Returns:
proj_array (numpy.ndarray) – Thresholded binary projection matrix.
proj_coords (list) – Coordinate information for each slice.
Analysis¶
- bsv.analyze_cp_subregions(projection_matrix_array, projection_matrix_coordinates_ara, allen_atlas_path_v2, output_slices=None, input_regions=None, region_groups=None, save_csv_path='')[source]¶
Decompose projection density by striatum subregions (CP and NAc).
Uses the Allen v2 atlas to assign projection signal to anatomical subdivisions of the caudate putamen and nucleus accumbens.
- Parameters:
projection_matrix_array (numpy.ndarray) – Projection data from
plot_connectivity().projection_matrix_coordinates_ara (list) – Coordinate info from
plot_connectivity().allen_atlas_path_v2 (str) – Path to directory containing the Allen v2 atlas files (
annotation_volume_v2_20um_by_index.npyandUnifiedAtlas_Label_ontology_v2.csv).output_slices (list of int, optional) – Subset of slice indices to analyse. Default is all slices.
input_regions (list of str, optional) – Source region acronyms (for labelling).
region_groups (list of int, optional) – Group assignment per input region.
save_csv_path (str, optional) – Path to write summary CSV.
''to skip export.
- Returns:
subregion_results (dict) – Per-slice mean intensities and voxel counts by subregion.
global_results (dict) – Global (across-slice) mean intensities by subregion.
- bsv.plot_connectivity_with_subregion_analysis(experiment_data, allen_atlas_path, allen_atlas_path_v2, output_region, number_of_chunks, number_of_pixels, plane, region_only, smoothing, color_limits, color, normalization_info='unknown', input_regions=None, region_groups=None, experiment_region_info=None, normalize_by_group=False, custom_slices=None, slice_averaging=0)[source]¶
Plot projections and run CP subregion analysis in one step.
Combines
plot_connectivity()andanalyze_cp_subregions().- Parameters:
experiment_data (numpy.ndarray) – Projection density array from
fetch_connectivity_data().allen_atlas_path (str) – Path to the Allen CCF atlas directory.
allen_atlas_path_v2 (str) – Path to the Allen v2 atlas directory.
output_region (str) – Target region acronym (e.g.
'CP').number_of_chunks (int) – Number of slices.
number_of_pixels (int) – Number of 2D histogram bins per axis for each slice. The physical bin size adapts to the spatial extent of the region (bin_size ≈ region_extent_voxels / number_of_pixels × atlas_resolution µm).
plane (str) –
'coronal'or'sagittal'.region_only (bool) – Mask to the target region boundary.
smoothing (float) – Gaussian smoothing sigma in pixels.
color_limits (str or list) – Colour scale specification.
color (list or None) – RGB colour(s).
normalization_info (str, optional) – Normalization label.
input_regions (list of str, optional) – Source region acronyms.
region_groups (list of int, optional) – Group assignment per input region.
experiment_region_info (dict, optional) – Per-experiment metadata.
normalize_by_group (bool, optional) – Normalize each group independently.
custom_slices (list of int, optional) – Specific slice indices.
slice_averaging (int, optional) – Adjacent-slice averaging radius.
- Returns:
proj_array (numpy.ndarray) – Projection matrix.
proj_coords (list) – Coordinate information.
subregion_results (dict or None) – Subregion analysis results (None if region is not CP).
global_results (dict or None) – Global subregion results (None if region is not CP).
Atlas utilities¶
- bsv.atlas_utils.get_atlas_files(atlas_type='allen', atlas_resolution=10)[source]¶
Return annotation volume and structure tree filenames for an atlas.
- Parameters:
atlas_type (str, optional) –
'allen'or a custom atlas name.atlas_resolution (int, optional) – Resolution in micrometres (10 or 20 for Allen).
- Returns:
(annotation_filename, structure_tree_filename).- Return type:
tuple of str
- bsv.atlas_utils.load_atlas(allen_atlas_path, atlas_type='allen', atlas_resolution=10)[source]¶
Load the annotation volume and structure tree for an atlas.
- Parameters:
allen_atlas_path (str) – Path to the atlas directory.
atlas_type (str, optional) –
'allen'or a custom atlas name.atlas_resolution (int, optional) – Resolution in micrometres (10 or 20 for Allen).
- Returns:
av (numpy.ndarray) – Annotation volume (AP x DV x ML).
st (pandas.DataFrame) – Structure tree.
- bsv.atlas_utils.load_structure_tree(filepath)[source]¶
Load a structure tree CSV as a DataFrame.
- Parameters:
filepath (str) – Path to the CSV file.
- Return type:
pandas.DataFrame
- bsv.atlas_utils.find_structure_indices(st, region_name)[source]¶
Find structure indices matching a region name (prefix match like MATLAB version). Returns 1-based indices matching the annotation volume ‘by_index’ convention.