allensdk.core package

Submodules

allensdk.core.brain_observatory_cache module

class allensdk.core.brain_observatory_cache.BrainObservatoryCache(cache=True, manifest_file='brain_observatory_manifest.json', base_uri=None)[source]

Bases: allensdk.api.cache.Cache

Cache class for storing and accessing data from the Brain Observatory. By default, this class will cache any downloaded metadata or files in well known locations defined in a manifest file. This behavior can be disabled.

Parameters:

cache: boolean

Whether the class should save results of API queries to locations specified in the manifest file. Queries for files (as opposed to metadata) must have a file location. If caching is disabled, those locations must be specified in the function call (e.g. get_ophys_experiment_data(file_name=’file.nwb’)).

manifest_file: string

File name of the manifest to be read. Default is “brain_observatory_manifest.json”.

Attributes

api: BrainObservatoryApi instance The object used for making API queries related to the Brain Observatory.
CELL_SPECIMENS_KEY = 'CELL_SPECIMENS'
EXPERIMENTS_KEY = 'EXPERIMENTS'
EXPERIMENT_CONTAINERS_KEY = 'EXPERIMENT_CONTAINERS'
EXPERIMENT_DATA_KEY = 'EXPERIMENT_DATA'
MANIFEST_VERSION = None
STIMULUS_MAPPINGS_KEY = 'STIMULUS_MAPPINGS'
build_manifest(file_name)[source]

Construct a manifest for this Cache class and save it in a file.

Parameters:

file_name: string

File location to save the manifest.

get_all_cre_lines()[source]

Return a list of all cre driver lines in the data set.

get_all_imaging_depths()[source]

Return a list of all imaging depths in the data set.

get_all_reporter_lines()[source]

Return a list of all reporter lines in the data set.

get_all_session_types()[source]

Return a list of all stimulus sessions in the data set.

get_all_stimuli()[source]

Return a list of all stimuli in the data set.

get_all_targeted_structures()[source]

Return a list of all targeted structures in the data set.

get_cell_specimens(file_name=None, ids=None, experiment_container_ids=None, simple=True, filters=None)[source]

Return cell specimens that have certain properies.

Parameters:

file_name: string

File name to save/read the cell specimens. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

ids: list

List of cell specimen ids.

experiment_container_ids: list

List of experiment container ids.

simple: boolean

Whether or not to simplify the dictionary properties returned by this method to a more concise subset.

filters: list of dicts

List of filter dictionaries. The Allen Brain Observatory web site can generate filters in this format to reproduce a filtered set of cells found there. To see what these look like, visit http://observatory.brain-map.org/visualcoding, perform a cell search and apply some filters (e.g. find cells in a particular area), then click the “view these cells in the AllenSDK” link on the bottom-left of the search results page. This will take you to a page that contains a code sample you can use to apply those same filters via this argument. For more detail on the filter syntax, see BrainObservatoryApi.dataframe_query.

Returns:

list of dictionaries

get_experiment_containers(file_name=None, ids=None, targeted_structures=None, imaging_depths=None, cre_lines=None, transgenic_lines=None, simple=True)[source]

Get a list of experiment containers matching certain criteria.

Parameters:

file_name: string

File name to save/read the experiment containers. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

ids: list

List of experiment container ids.

targeted_structures: list

List of structure acronyms. Must be in the list returned by BrainObservatoryCache.get_all_targeted_structures().

imaging_depths: list

List of imaging depths. Must be in the list returned by BrainObservatoryCache.get_all_imaging_depths().

cre_lines: list

List of cre lines. Must be in the list returned by BrainObservatoryCache.get_all_cre_lines().

transgenic_lines: list

List of transgenic lines. Must be in the list returned by BrainObservatoryCache.get_all_cre_lines() or. BrainObservatoryCache.get_all_reporter_lines().

simple: boolean

Whether or not to simplify the dictionary properties returned by this method to a more concise subset.

Returns:

list of dictionaries

get_ophys_experiment_data(ophys_experiment_id, file_name=None)[source]

Download the NWB file for an ophys_experiment (if it hasn’t already been downloaded) and return a data accessor object.

Parameters:

file_name: string

File name to save/read the data set. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

ophys_experiment_id: integer

id of the ophys_experiment to retrieve

Returns:

BrainObservatoryNwbDataSet

get_ophys_experiments(file_name=None, ids=None, experiment_container_ids=None, targeted_structures=None, imaging_depths=None, cre_lines=None, transgenic_lines=None, stimuli=None, session_types=None, simple=True)[source]

Get a list of ophys experiments matching certain criteria.

Parameters:

file_name: string

File name to save/read the ophys experiments. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

ids: list

List of ophys experiment ids.

experiment_container_ids: list

List of experiment container ids.

targeted_structures: list

List of structure acronyms. Must be in the list returned by BrainObservatoryCache.get_all_targeted_structures().

imaging_depths: list

List of imaging depths. Must be in the list returned by BrainObservatoryCache.get_all_imaging_depths().

cre_lines: list

List of cre lines. Must be in the list returned by BrainObservatoryCache.get_all_cre_lines().

transgenic_lines: list

List of transgenic lines. Must be in the list returned by BrainObservatoryCache.get_all_cre_lines() or. BrainObservatoryCache.get_all_reporter_lines().

stimuli: list

List of stimulus names. Must be in the list returned by BrainObservatoryCache.get_all_stimuli().

session_types: list

List of stimulus session type names. Must be in the list returned by BrainObservatoryCache.get_all_session_types().

simple: boolean

Whether or not to simplify the dictionary properties returned by this method to a more concise subset.

Returns:

list of dictionaries

allensdk.core.brain_observatory_nwb_data_set module

class allensdk.core.brain_observatory_nwb_data_set.BrainObservatoryNwbDataSet(nwb_file)[source]

Bases: object

FILE_METADATA_MAPPING = {'ophys_experiment_id': 'general/session_id', 'session_type': 'general/session_type', 'fov': 'general/fov', 'sex': 'general/subject/sex', 'imaging_depth': 'general/optophysiology/imaging_plane_1/imaging depth', 'device_string': 'general/devices/2-photon microscope', 'session_start_time': 'session_start_time', 'indicator': 'general/optophysiology/imaging_plane_1/indicator', 'genotype': 'general/subject/genotype', 'age': 'general/subject/age', 'excitation_lambda': 'general/optophysiology/imaging_plane_1/excitation_lambda', 'generated_by': 'general/generated_by', 'experiment_container_id': 'general/experiment_container_id', 'targeted_structure': 'general/optophysiology/imaging_plane_1/location', 'specimen_name': 'general/specimen_name'}
MOTION_CORRECTION_DATASETS = ['MotionCorrection/2p_image_series/xy_translations', 'MotionCorrection/2p_image_series/xy_translation']
PIPELINE_DATASET = 'brain_observatory_pipeline'
STIMULUS_TABLE_TYPES = {'abstract_feature_series': ['drifting_gratings', 'static_gratings'], 'indexed_time_series': ['natural_movie_one', 'natural_movie_two', 'natural_movie_three', 'natural_scenes', 'locally_sparse_noise', 'locally_sparse_noise_4deg', 'locally_sparse_noise_8deg']}
SUPPORTED_PIPELINE_VERSION = '1.0'
get_cell_specimen_ids()[source]

Returns an array of cell IDs for all cells in the file

Returns:cell specimen IDs: list
get_cell_specimen_indices(cell_specimen_ids=None)[source]

Given a list of cell specimen ids, return their index based on their order in this file.

Parameters:cell_specimen_ids: list of cell specimen ids
get_corrected_fluorescence_traces(cell_specimen_ids=None)[source]

Returns an array of neuropil-corrected fluorescence traces for all ROIs and the timestamps for each datapoint

Parameters:

cell_specimen_ids: list or array (optional)

List of cell IDs to return traces for. If this is None (default) then all are returned

Returns:

timestamps: 2D numpy array

Timestamp for each fluorescence sample

traces: 2D numpy array

Corrected fluorescence traces for each cell

get_dff_traces(cell_specimen_ids=None)[source]

Returns an array of dF/F traces for all ROIs and the timestamps for each datapoint

Parameters:

cell_specimen_ids: list or array (optional)

List of cell IDs to return data for. If this is None (default) then all are returned

Returns:

timestamps: 2D numpy array

Timestamp for each fluorescence sample

dF/F: 2D numpy array

dF/F values for each cell

get_fluorescence_timestamps()[source]

Returns an array of timestamps in seconds for the fluorescence traces

get_fluorescence_traces(cell_specimen_ids=None)[source]

Returns an array of fluorescence traces for all ROI and the timestamps for each datapoint

Parameters:

cell_specimen_ids: list or array (optional)

List of cell IDs to return traces for. If this is None (default) then all are returned

Returns:

timestamps: 2D numpy array

Timestamp for each fluorescence sample

traces: 2D numpy array

Fluorescence traces for each cell

get_locally_sparse_noise_stimulus_template(stimulus, mask_off_screen=True)[source]

Return an array of the stimulus template for the specified stimulus.

Parameters:

stimulus: string

Which locally sparse noise stimulus to retrieve. Must be one of:

stimulus_info.LOCALLY_SPARSE_NOISE stimulus_info.LOCALLY_SPARSE_NOISE_4DEG stimulus_info.LOCALLY_SPARSE_NOISE_8DEG

mask_off_screen: boolean

Set off-screen regions of the stimulus to LocallySparseNoise.LSN_OFF_SCREEN.

Returns:

tuple: (template, off-screen mask)

get_max_projection()[source]

Returns the maximum projection image for the 2P movie.

Returns:max projection: np.ndarray
get_metadata()[source]

Returns a dictionary of meta data associated with each experiment, including Cre line, specimen number, visual area imaged, imaging depth

Returns:metadata: dictionary
get_motion_correction()[source]

Returns a Panda DataFrame containing the x- and y- translation of each image used for image alignment

get_neuropil_r(cell_specimen_ids=None)[source]

Returns a scalar value of r for neuropil correction of flourescence traces

Parameters:

cell_specimen_ids: list or array (optional)

List of cell IDs to return traces for. If this is None (default) then results for all are returned

Returns:

r: 1D numpy array, len(r)=len(cell_specimen_ids)

Scalar for neuropil subtraction for each cell

get_neuropil_traces(cell_specimen_ids=None)[source]

Returns an array of fluorescence traces for all ROIs and the timestamps for each datapoint

Parameters:

cell_specimen_ids: list or array (optional)

List of cell IDs to return traces for. If this is None (default) then all are returned

Returns:

timestamps: 2D numpy array

Timestamp for each fluorescence sample

traces: 2D numpy array

Neuropil fluorescence traces for each cell

get_roi_ids()[source]

Returns an array of IDs for all ROIs in the file

Returns:ROI IDs: list
get_roi_mask(cell_specimen_ids=None)[source]

Returns an array of all the ROI masks

Parameters:

cell specimen IDs: list or array (optional)

List of cell IDs to return traces for. If this is None (default) then all are returned

Returns:

List of ROI_Mask objects

get_roi_mask_array(cell_specimen_ids=None)[source]

Return a numpy array containing all of the ROI masks for requested cells. If cell_specimen_ids is omitted, return all masks.

Parameters:

cell_specimen_ids: list

List of cell specimen ids. Default None.

Returns:

np.ndarray: NxWxH array, where N is number of cells

get_running_speed()[source]

Returns the mouse running speed in cm/s

get_session_type()[source]

Returns the type of experimental session, presently one of the following: three_session_A, three_session_B, three_session_C

Returns:session type: string
get_spontaneous_activity_stimulus_table()[source]

Return the spontaneous activity stimulus table, if it exists.

Returns:stimulus table: pd.DataFrame
get_stimulus_table(stimulus_name)[source]

Return a stimulus table given a stimulus name

get_stimulus_template(stimulus_name)[source]

Return an array of the stimulus template for the specified stimulus.

Parameters:

stimulus_name: string

Must be one of the strings returned by list_stimuli().

Returns:

stimulus table: pd.DataFrame

list_stimuli()[source]

Return a list of the stimuli presented in the experiment.

Returns:stimuli: list of strings
save_analysis_arrays(*datasets)[source]
save_analysis_dataframes(*tables)[source]
allensdk.core.brain_observatory_nwb_data_set.align_running_speed(dxcm, dxtime, timestamps)[source]

If running speed timestamps differ from fluorescence timestamps, adjust by inserting NaNs to running speed.

Returns:tuple: dxcm, dxtime
allensdk.core.brain_observatory_nwb_data_set.make_display_mask(display_shape=(1920, 1200))[source]

Build a display-shaped mask that indicates which pixels are on screen after warping the stimulus.

allensdk.core.brain_observatory_nwb_data_set.mask_stimulus_template(template_display_coords, template_shape, display_mask=None, threshold=1.0)[source]

Build a mask for a stimulus template of a given shape and display coordinates that indicates which part of the template is on screen after warping.

Parameters:

template_display_coords: list

list of (x,y) display coordinates

template_shape: tuple

(width,height) of the display template

display_mask: np.ndarray

boolean 2D mask indicating which display coordinates are on screen after warping.

threshold: float

Fraction of pixels associated with a template display coordinate that should remain on screen to count as belonging to the mask.

Returns:

tuple: (template mask, pixel fraction)

allensdk.core.brain_observatory_nwb_data_set.warp_stimulus_coords(vertices, distance=15.0, mon_height_cm=32.5, mon_width_cm=51.0, mon_res=(1920, 1200), eyepoint=(0.5, 0.5))[source]

For a list of screen vertices, provides a corresponding list of texture coordinates.

Parameters:

vertices: numpy.ndarray

[[x0,y0], [x1,y1], ...] A set of vertices to convert to texture positions.

distance: float

distance from the monitor in cm.

mon_height_cm: float

monitor height in cm

mon_width_cm: float

monitor width in cm

mon_res: tuple

monitor resolution (x,y)

eyepoint: tuple

Returns:

np.ndarray

x,y coordinates shaped like the input that describe what pixel coordinates are displayed an the input coordinates after warping the stimulus.

allensdk.core.cell_types_cache module

class allensdk.core.cell_types_cache.CellTypesCache(cache=True, manifest_file='cell_types_manifest.json', base_uri=None)[source]

Bases: allensdk.api.cache.Cache

Cache class for storing and accessing data from the Cell Types Database. By default, this class will cache any downloaded metadata or files in well known locations defined in a manifest file. This behavior can be disabled.

Parameters:

cache: boolean

Whether the class should save results of API queries to locations specified in the manifest file. Queries for files (as opposed to metadata) must have a file location. If caching is disabled, those locations must be specified in the function call (e.g. get_ephys_data(file_name=’file.nwb’)).

manifest_file: string

File name of the manifest to be read. Default is “cell_types_manifest.json”.

Attributes

api: CellTypesApi instance The object used for making API queries related to the Cell Types Database
CELLS_KEY = 'CELLS'
EPHYS_DATA_KEY = 'EPHYS_DATA'
EPHYS_FEATURES_KEY = 'EPHYS_FEATURES'
EPHYS_SWEEPS_KEY = 'EPHYS_SWEEPS'
MANIFEST_VERSION = None
MARKER_KEY = 'MARKER'
MORPHOLOGY_FEATURES_KEY = 'MORPHOLOGY_FEATURES'
RECONSTRUCTION_KEY = 'RECONSTRUCTION'
build_manifest(file_name)[source]

Construct a manifest for this Cache class and save it in a file.

Parameters:

file_name: string

File location to save the manifest.

get_all_features(dataframe=False, require_reconstruction=True)[source]

Download morphology and electrophysiology features for all cells and merge them into a single table.

Parameters:

dataframe: boolean

Return the output as a Pandas DataFrame. If False, return a list of dictionaries.

require_reconstruction: boolean

Only return ephys and morphology features for cells that have reconstructions. Default True.

get_cells(file_name=None, require_morphology=False, require_reconstruction=False, reporter_status=None)[source]

Download metadata for all cells in the database and optionally return a subset filtered by whether or not they have a morphology or reconstruction.

Parameters:

file_name: string

File name to save/read the cell metadata as JSON. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

require_morphology: boolean

Filter out cells that have no morphological images.

require_reconstruction: boolean

Filter out cells that have no morphological reconstructions.

reporter_status: list

Filter for cells that have one or more cell reporter statuses.

get_ephys_data(specimen_id, file_name=None)[source]

Download electrophysiology traces for a single cell in the database.

Parameters:

specimen_id: int

The ID of a cell specimen to download.

file_name: string

File name to save/read the ephys features metadata as CSV. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

Returns:

NwbDataSet

A class instance with helper methods for retrieving stimulus and response traces out of an NWB file.

get_ephys_features(dataframe=False, file_name=None)[source]

Download electrophysiology features for all cells in the database.

Parameters:

file_name: string

File name to save/read the ephys features metadata as CSV. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

dataframe: boolean

Return the output as a Pandas DataFrame. If False, return a list of dictionaries.

get_ephys_sweeps(specimen_id, file_name=None)[source]

Download sweep metadata for a single cell specimen.

Parameters:

specimen_id: int

ID of a cell.

get_morphology_features(dataframe=False, file_name=None)[source]

Download morphology features for all cells with reconstructions in the database.

Parameters:

file_name: string

File name to save/read the ephys features metadata as CSV. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

dataframe: boolean

Return the output as a Pandas DataFrame. If False, return a list of dictionaries.

get_reconstruction(specimen_id, file_name=None)[source]

Download and open a reconstruction for a single cell in the database.

Parameters:

specimen_id: int

The ID of a cell specimen to download.

file_name: string

File name to save/read the reconstruction SWC. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

Returns:

Morphology

A class instance with methods for accessing morphology compartments.

get_reconstruction_markers(specimen_id, file_name=None)[source]

Download and open a reconstruction marker file for a single cell in the database.

Parameters:

specimen_id: int

The ID of a cell specimen to download.

file_name: string

File name to save/read the reconstruction marker. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

Returns:

Morphology

A class instance with methods for accessing morphology compartments.

class allensdk.core.cell_types_cache.ReporterStatus[source]

Valid strings for filtering by cell reporter status.

INDETERMINATE = 'cre reporter indeterminate'
NA = 'not applicable'
NEGATIVE = 'cre reporter negative'
POSITIVE = 'cre reporter positive'

allensdk.core.dat_utilities module

class allensdk.core.dat_utilities.DatUtilities[source]

Bases: object

classmethod save_voltage(output_path, v, t)[source]

Save a single voltage output result into a simple text format.

The output file is one t v pair per line.

Parameters:

output_path : string

file name for output

v : numpy array

voltage

t : numpy array

time

allensdk.core.json_utilities module

class allensdk.core.json_utilities.JsonComments[source]

Bases: object

classmethod read_file(file_name)[source]
classmethod read_string(json_string)[source]
classmethod remove_comments(json_string)[source]

Strip single and multiline javascript-style comments.

Parameters:

json : string

Json string with javascript-style comments.

Returns:

string

Copy of the input with comments removed.

Note: A JSON decoder MAY accept and ignore comments.

classmethod remove_multiline_comments(json_string)[source]

Rebuild input without substrings matching /.../.

Parameters:

json_string : string

may or may not contain multiline comments.

Returns:

string

Copy of the input without the comments.

allensdk.core.json_utilities.json_handler(obj)[source]

Used by write_json convert a few non-standard types to things that the json package can handle.

allensdk.core.json_utilities.read(file_name)[source]

Shortcut reading JSON from a file.

allensdk.core.json_utilities.read_url(url, method='POST')[source]
allensdk.core.json_utilities.read_url_get(url)[source]

Transform a JSON contained in a file into an equivalent nested python dict.

Parameters:

url : string

where to get the json.

Returns:

dict

Python version of the input

Note: if the input is a bare array or literal, for example,

the output will be of the corresponding type.

allensdk.core.json_utilities.read_url_post(url)[source]

Transform a JSON contained in a file into an equivalent nested python dict.

Parameters:

url : string

where to get the json.

Returns:

dict

Python version of the input

Note: if the input is a bare array or literal, for example,

the output will be of the corresponding type.

allensdk.core.json_utilities.write(file_name, obj)[source]

Shortcut for writing JSON to a file. This also takes care of serializing numpy and data types.

allensdk.core.json_utilities.write_string(obj)[source]

Shortcut for writing JSON to a string. This also takes care of serializing numpy and data types.

allensdk.core.mouse_connectivity_cache module

class allensdk.core.mouse_connectivity_cache.MouseConnectivityCache(resolution=None, cache=True, manifest_file='mouse_connectivity_manifest.json', ccf_version=None, base_uri=None)[source]

Bases: allensdk.api.cache.Cache

Cache class for storing and accessing data related to the adult mouse Connectivity Atlas. By default, this class will cache any downloaded metadata or files in well known locations defined in a manifest file. This behavior can be disabled.

Parameters:

resolution: int

Resolution of grid data to be downloaded when accessing projection volume, the annotation volume, and the annotation volume. Must be one of (10, 25, 50, 100). Default is 25.

ccf_version: string

Desired version of the Common Coordinate Framework. This affects the annotation volume (get_annotation_volume) and structure masks (get_structure_mask). Must be one of (MouseConnectivityApi.CCF_2015, MouseConnectivityApi.CCF_2016). Default: MouseConnectivityApi.CCF_2016

cache: boolean

Whether the class should save results of API queries to locations specified in the manifest file. Queries for files (as opposed to metadata) must have a file location. If caching is disabled, those locations must be specified in the function call (e.g. get_projection_density(file_name=’file.nrrd’)).

manifest_file: string

File name of the manifest to be read. Default is “mouse_connectivity_manifest.json”.

Attributes

resolution: int Resolution of grid data to be downloaded when accessing projection volume, the annotation volume, and the annotation volume. Must be one of (10, 25, 50, 100). Default is 25.
api: MouseConnectivityApi instance Used internally to make API queries.
ANNOTATION_KEY = 'ANNOTATION'
CCF_VERSION_KEY = 'CCF_VERSION'
DATA_MASK_KEY = 'DATA_MASK'
EXPERIMENTS_KEY = 'EXPERIMENTS'
INJECTION_DENSITY_KEY = 'INJECTION_DENSITY'
INJECTION_FRACTION_KEY = 'INJECTION_FRACTION'
MANIFEST_VERSION = 1.0
PROJECTION_DENSITY_KEY = 'PROJECTION_DENSITY'
STRUCTURES_KEY = 'STRUCTURES'
STRUCTURE_MASK_KEY = 'STRUCTURE_MASK'
STRUCTURE_TREE_KEY = 'STRUCTURE_TREE'
STRUCTURE_UNIONIZES_KEY = 'STRUCTURE_UNIONIZES'
TEMPLATE_KEY = 'TEMPLATE'
build_manifest(file_name)[source]

Construct a manifest for this Cache class and save it in a file.

Parameters:

file_name: string

File location to save the manifest.

filter_experiments(experiments, cre=None, injection_structure_ids=None)[source]

Take a list of experiments and filter them by cre status and injection structure.

Parameters:

cre: boolean or list

If True, return only cre-positive experiments. If False, return only cre-negative experiments. If None, return all experients. If list, return all experiments with cre line names in the supplied list. Default None.

injection_structure_ids: list

Only return experiments that were injected in the structures provided here. If None, return all experiments. Default None.

filter_structure_unionizes(unionizes, is_injection=None, structure_ids=None, include_descendants=False, hemisphere_ids=None)[source]

Take a list of unionzes and return a subset of records filtered by injection status, structure, and hemisphere.

Parameters:

is_injection: boolean

If True, only return unionize records that disregard non-injection pixels. If False, only return unionize records that disregard injection pixels. If None, return all records. Default None.

structure_ids: list

Only return unionize records for a set of structures. If None, return all records. Default None.

include_descendants: boolean

Include all descendant records for specified structures. Default False.

hemisphere_ids: list

Only return unionize records that disregard pixels outside of a hemisphere. or set of hemispheres. Left = 1, Right = 2, Both = 3. If None, include all records [1, 2, 3]. Default None.

get_annotation_volume(file_name=None)[source]

Read the annotation volume. Download it first if it doesn’t exist.

Parameters:

file_name: string

File name to store the annotation volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

get_data_mask(experiment_id, file_name=None)[source]

Read a data mask volume for a single experiment. Download it first if it doesn’t exist. Data mask is a binary mask of voxels that have valid data. Only use valid data in analysis!

Parameters:

experiment_id: int

ID of the experiment to download/read. This corresponds to section_data_set_id in the API.

file_name: string

File name to store the template volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

get_experiment_structure_unionizes(experiment_id, file_name=None, is_injection=None, structure_ids=None, include_descendants=False, hemisphere_ids=None)[source]

Retrieve the structure unionize data for a specific experiment. Filter by structure, injection status, and hemisphere.

Parameters:

experiment_id: int

ID of the experiment of interest. Corresponds to section_data_set_id in the API.

file_name: string

File name to save/read the experiments list. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

is_injection: boolean

If True, only return unionize records that disregard non-injection pixels. If False, only return unionize records that disregard injection pixels. If None, return all records. Default None.

structure_ids: list

Only return unionize records for a specific set of structures. If None, return all records. Default None.

include_descendants: boolean

Include all descendant records for specified structures. Default False.

hemisphere_ids: list

Only return unionize records that disregard pixels outside of a hemisphere. or set of hemispheres. Left = 1, Right = 2, Both = 3. If None, include all records [1, 2, 3]. Default None.

get_experiments(dataframe=False, file_name=None, cre=None, injection_structure_ids=None)[source]

Read a list of experiments that match certain criteria. If caching is enabled, this will save the whole (unfiltered) list of experiments to a file.

Parameters:

dataframe: boolean

Return the list of experiments as a Pandas DataFrame. If False, return a list of dictionaries. Default False.

file_name: string

File name to save/read the structures table. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

cre: boolean or list

If True, return only cre-positive experiments. If False, return only cre-negative experiments. If None, return all experients. If list, return all experiments with cre line names in the supplied list. Default None.

injection_structure_ids: list

Only return experiments that were injected in the structures provided here. If None, return all experiments. Default None.

get_injection_density(experiment_id, file_name=None)[source]

Read an injection density volume for a single experiment. Download it first if it doesn’t exist. Injection density is the proportion of projecting pixels in a grid voxel only including pixels that are part of the injection site in [0,1].

Parameters:

experiment_id: int

ID of the experiment to download/read. This corresponds to section_data_set_id in the API.

file_name: string

File name to store the template volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

get_injection_fraction(experiment_id, file_name=None)[source]

Read an injection fraction volume for a single experiment. Download it first if it doesn’t exist. Injection fraction is the proportion of pixels in the injection site in a grid voxel in [0,1].

Parameters:

experiment_id: int

ID of the experiment to download/read. This corresponds to section_data_set_id in the API.

file_name: string

File name to store the template volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

get_ontology(*args, **kwargs)[source]

Read the list of adult mouse structures and return an Ontology instance.

Parameters:

file_name: string

File name to save/read the structures table. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

get_projection_density(experiment_id, file_name=None)[source]

Read a projection density volume for a single experiment. Download it first if it doesn’t exist. Projection density is the proportion of of projecting pixels in a grid voxel in [0,1].

Parameters:

experiment_id: int

ID of the experiment to download/read. This corresponds to section_data_set_id in the API.

file_name: string

File name to store the template volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

get_projection_matrix(experiment_ids, projection_structure_ids, hemisphere_ids=None, parameter='projection_volume', dataframe=False)[source]
get_reference_space(structure_file_name=None, annotation_file_name=None)[source]

Build a ReferenceSpace from this cache’s annotation volume and structure tree. The ReferenceSpace does operations that relate brain structures to spatial domains.

Parameters:

structure_file_name: string

File name to save/read the structures table. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

annotation_file_name: string

File name to store the annotation volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

get_structure_mask(structure_id, file_name=None, annotation_file_name=None)[source]

Read a 3D numpy array shaped like the annotation volume that has non-zero values where voxels belong to a particular structure. This will take care of identifying substructures.

Parameters:

structure_id: int

ID of a structure.

file_name: string

File name to store the structure mask. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

annotation_file_name: string

File name to store the annotation volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

Notes

If you are making large numbers of masks, there is a faster structure mask generator in ReferenceSpace.many_structure_masks. We will be migrating this function in a future release.

get_structure_tree(file_name=None)[source]

Read the list of adult mouse structures and return an StructureTree instance.

Parameters:

file_name: string

File name to save/read the structures table. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

get_structure_unionizes(experiment_ids, is_injection=None, structure_ids=None, include_descendants=False, hemisphere_ids=None)[source]

Get structure unionizes for a set of experiment IDs. Filter the results by injection status, structure, and hemisphere.

Parameters:

experiment_ids: list

List of experiment IDs. Corresponds to section_data_set_id in the API.

is_injection: boolean

If True, only return unionize records that disregard non-injection pixels. If False, only return unionize records that disregard injection pixels. If None, return all records. Default None.

structure_ids: list

Only return unionize records for a specific set of structures. If None, return all records. Default None.

include_descendants: boolean

Include all descendant records for specified structures. Default False.

hemisphere_ids: list

Only return unionize records that disregard pixels outside of a hemisphere. or set of hemispheres. Left = 1, Right = 2, Both = 3. If None, include all records [1, 2, 3]. Default None.

get_structures(*args, **kwargs)[source]

Read the list of adult mouse structures and return a Pandas DataFrame.

Parameters:

file_name: string

File name to save/read the structures table. If file_name is None, the file_name will be pulled out of the manifest. If caching is disabled, no file will be saved. Default is None.

get_template_volume(file_name=None)[source]

Read the template volume. Download it first if it doesn’t exist.

Parameters:

file_name: string

File name to store the template volume. If it already exists, it will be read from this file. If file_name is None, the file_name will be pulled out of the manifest. Default is None.

make_structure_mask(structure_ids, annotation)[source]

Look at an annotation volume and identify voxels that have values in a list of structure ids.

Parameters:

structure_ids: list

List of IDs to look for in the annotation volume

annotation: np.ndarray

Numpy array filled with IDs.

allensdk.core.nwb_data_set module

class allensdk.core.nwb_data_set.NwbDataSet(file_name, spike_time_key=None)[source]

Bases: object

A very simple interface for exracting electrophysiology data from an NWB file.

DEPRECATED_SPIKE_TIMES = 'aibs_spike_times'
SPIKE_TIMES = 'spike_times'
fill_sweep_responses(fill_value=0.0, sweep_numbers=None)[source]

Fill sweep response arrays with a single value.

Parameters:

fill_value: float

Value used to fill sweep response array

sweep_numbers: list

List of integer sweep numbers to be filled (default all sweeps)

get_experiment_sweep_numbers()[source]

Get all of the sweep numbers for experiment epochs in the file, not including test sweeps.

get_pipeline_version()[source]

Returns the AI pipeline version number, stored in the metadata field ‘generated_by’. If that field is missing, version 0.0 is returned.

Returns:int tuple: (major, minor)
get_spike_times(sweep_number, key=None)[source]

Return any spike times stored in the NWB file for a sweep.

Parameters:

sweep_number: int

index to access

key : string

label where the spike times are stored (default NwbDataSet.SPIKE_TIMES)

Returns:

list

list of spike times in seconds relative to the start of the sweep

get_sweep(sweep_number)[source]

Retrieve the stimulus, response, index_range, and sampling rate for a particular sweep. This method hides the NWB file’s distinction between a “Sweep” and an “Experiment”. An experiment is a subset of of a sweep that excludes the initial test pulse. It also excludes any erroneous response data at the end of the sweep (usually for ramp sweeps, where recording was terminated mid-stimulus).

Some sweeps do not have an experiment, so full data arrays are returned. Sweeps that have an experiment return full data arrays (include the test pulse) with any erroneous data trimmed from the back of the sweep.

Parameters:

sweep_number: int

Returns:

dict

A dictionary with ‘stimulus’, ‘response’, ‘index_range’, and ‘sampling_rate’ elements. The index range is a 2-tuple where the first element indicates the end of the test pulse and the second index is the end of valid response data.

get_sweep_metadata(sweep_number)[source]

Retrieve the sweep level metadata associated with each sweep. Includes information on stimulus parameters like its name and amplitude as well as recording quality metadata, like access resistance and seal quality.

Parameters:

sweep_number: int

Returns:

dict

A dictionary with ‘aibs_stimulus_amplitude_pa’, ‘aibs_stimulus_name’, ‘gain’, ‘initial_access_resistance’, ‘seal’ elements. These specific fields are ones encoded in the original AIBS in vitro .nwb files.

get_sweep_numbers()[source]

Get all of the sweep numbers in the file, including test sweeps.

set_spike_times(sweep_number, spike_times, key=None)[source]

Set or overwrite the spikes times for a sweep.

Parameters:

sweep_number : int

index to access

key : string

where the times are stored (default NwbDataSet.SPIKE_TIME)

spike_times: np.array

array of spike times in seconds

set_sweep(sweep_number, stimulus, response)[source]

Overwrite the stimulus or response of an NWB file. If the supplied arrays are shorter than stored arrays, they are padded with zeros to match the original data size.

Parameters:

sweep_number: int

stimulus: np.array

Overwrite the stimulus with this array. If None, stimulus is unchanged.

response: np.array

Overwrite the response with this array. If None, response is unchanged.

allensdk.core.ontology module

class allensdk.core.ontology.Ontology(*args, **kwargs)[source]

Bases: object

Note

Deprecated from 0.12.5 Ontology has been replaced by StructureTree.

get_child_ids(structure_ids)[source]

Find the set of ids that are immediate children of one or more structures.

Parameters:

structure_ids: iterable

Any iterable type that contains structure ids that can be cast to integers.

Returns:

set

Set of child structure ids

get_children(structure_ids)[source]

Find the set of structures that are immediate children of one or more structures.

Parameters:

structure_ids: iterable

Any iterable type that contains structure ids that can be cast to integers.

Returns:

pandas.DataFrame

Set of child structures

get_descendant_ids(structure_ids)[source]

Find the set of the ids of structures that are descendants of one or more structures. The returned set will include the input structure ids.

Parameters:

structure_ids: iterable

Any iterable type that contains structure ids that can be cast to integers.

Returns:

set

Set of descendant structure ids.

get_descendants(structure_ids)[source]

Find the set of structures that are descendants of one or more structures. The returned set will include the input structures.

Parameters:

structure_ids: iterable

Any iterable type that contains structure ids that can be cast to integers.

Returns:

pandas.DataFrame

Set of descendant structures.

structure_descends_from(child_id, parent_id)[source]

Return whether one structure id is a descendant of another structure id.

allensdk.core.reference_space module

class allensdk.core.reference_space.ReferenceSpace(structure_tree, annotation, resolution)[source]

Bases: object

static check_and_write(base_dir, structure_id, fn)[source]

A many_structure_masks callback that writes the mask to a nrrd file if the file does not already exist.

check_coverage(structure_ids, domain_mask)[source]

Determines whether a spatial domain is completely covered by structures in a set.

Parameters:

structure_ids : list of int

Specifies the set of structures to check.

domain_mask : numpy ndarray

Same shape as annotation. 1 inside the mask, 0 out. Specifies spatial domain.

Returns:

numpy ndarray :

1 where voxels are missing from the candidate, 0 where the candidate exceeds the domain

direct_voxel_counts()[source]

Determines the number of voxels directly assigned to one or more structures.

Returns:

dict :

Keys are structure ids, values are the number of voxels directly assigned to those structures.

direct_voxel_map
downsample(target_resolution)[source]

Obtain a smaller reference space by downsampling

Parameters:

target_resolution : tuple of numeric

Resolution in microns of the output space.

interpolator : string

Method used to interpolate the volume. Currently only ‘nearest’ is supported

Returns:

ReferenceSpace :

A new ReferenceSpace with the same structure tree and a downsampled annotation.

get_slice_image(axis, position, cmap=None)[source]

Produce a AxBx3 RGB image from a slice in the annotation

Parameters:

axis : int

Along which to slice the annotation volume. 0 is coronal, 1 is horizontal, and 2 is sagittal.

position : int

In microns. Take the slice from this far along the specified axis.

cmap : dict, optional

Keys are structure ids, values are rgb triplets. Defaults to structure color_hex_triplets.

Returns:

np.ndarray :

RGB image array.

Notes

If you assign a custom colormap, make sure that you take care of the background in addition to the structures.

make_structure_mask(structure_ids, direct_only=False)[source]

Return an indicator array for one or more structures

Parameters:

structure_ids : list of int

Make a mask that indicates the union of these structures’ voxels

direct_only : bool, optional

If True, only include voxels directly assigned to a structure in the mask. Otherwise include voxels assigned to descendants.

Returns:

numpy ndarray :

Same shape as annotation. 1 inside mask, 0 outside.

many_structure_masks(structure_ids, output_cb=None, direct_only=False)[source]

Build one or more structure masks and do something with them

Parameters:

structure_ids : list of int

Specify structures to be masked

output_cb : function, optional

Must have the following signature: output_cb(structure_id, fn). On each requested id, fn will be curried to make a mask for that id. Defaults to returning the structure id and mask.

direct_only : bool, optional

If True, only include voxels directly assigned to a structure in the mask. Otherwise include voxels assigned to descendants.

Yields:

Return values of output_cb called on each structure_id, structure_mask

pair.

Notes

output_cb is called on every yield, so any side-effects (such as writing to a file) will be carried out regardless of what you do with the return values. You do actually have to iterate through the output, though.

remove_unassigned(update_self=True)[source]

Obtains a structure tree consisting only of structures that have at least one voxel in the annotation.

Parameters:

update_self : bool, optional

If True, the contained structure tree will be replaced,

Returns:

list of dict :

elements are filtered structures

static return_mask_cb(structure_id, fn)[source]

A basic callback for many_structure_masks

total_voxel_counts()[source]

Determines the number of voxels assigned to a structure or its descendants

Returns:

dict :

Keys are structure ids, values are the number of voxels assigned to structures’ descendants.

total_voxel_map
validate_structures(structure_ids, domain_mask)[source]

Determines whether a set of structures produces an exact and nonoverlapping tiling of a spatial domain

Parameters:

structure_ids : list of int

Specifies the set of structures to check.

domain_mask : numpy ndarray

Same shape as annotation. 1 inside the mask, 0 out. Specifies spatial domain.

Returns:

set :

Ids of structures that are the ancestors of other structures in the supplied set.

numpy ndarray :

Indicator for missing voxels.

allensdk.core.simple_tree module

class allensdk.core.simple_tree.SimpleTree(nodes, node_id_cb, parent_id_cb)[source]

Bases: object

ancestor_ids(node_ids)[source]

Obtain the ids of one or more nodes’ ancestors

Parameters:

node_ids : list of hashable

Items are ids of nodes whose ancestors you wish to find.

Returns:

list of list of hashable :

Items are lists of input nodes’ ancestors’ ids.

Notes

Given the tree: A -> B -> C

`-> D

The ancestors of C are [C, B, A]. The ancestors of A are [A]. The ancestors of D are [D, A]

ancestors(node_ids)[source]

Get one or mode nodes’ ancestor nodes

Parameters:

node_ids : list of hashable

Items are ids of nodes whose ancestors will be found.

Returns:

list of list of dict :

Items are lists of ancestor nodes corresponding to argued ids.

child_ids(node_ids)[source]

Obtain the ids of one or more nodes’ children

Parameters:

node_ids : list of hashable

Items are ids of nodes whose children you wish to find.

Returns:

list of list of hashable :

Items are lists of input nodes’ children’s ids.

children(node_ids)[source]

Get one or mode nodes’ child nodes

Parameters:

node_ids : list of hashable

Items are ids of nodes whose children will be found.

Returns:

list of list of dict :

Items are lists of child nodes corresponding to argued ids.

descendant_ids(node_ids)[source]

Obtain the ids of one or more nodes’ descendants

Parameters:

node_ids : list of hashable

Items are ids of nodes whose descendants you wish to find.

Returns:

list of list of hashable :

Items are lists of input nodes’ descendants’ ids.

Notes

Given the tree: A -> B -> C

`-> D

The descendants of A are [B, C, D]. The descendants of C are [].

descendants(node_ids)[source]

Get one or mode nodes’ descendant nodes

Parameters:

node_ids : list of hashable

Items are ids of nodes whose descendants will be found.

Returns:

list of list of dict :

Items are lists of descendant nodes corresponding to argued ids.

filter_nodes(criterion)[source]

Obtain a list of nodes filtered by some criterion

Parameters:

criterion : function | node dict => bool

Only nodes for which criterion returns true will be returned.

Returns:

list of dict :

Items are node dictionaries that passed the filter.

node(node_ids=None)[source]

Get one or more nodes’ full dictionaries from their ids.

Parameters:

node_ids : list of hashable

Items are ids of nodes to be returned. Default is all.

Returns:

list of dict :

Items are nodes corresponding to argued ids.

node_ids()[source]

Obtain the node ids of each node in the tree

Returns:

list :

elements are node ids

parent(node_ids)[source]

Get one or mode nodes’ parent nodes

Parameters:

node_ids : list of hashable

Items are ids of nodes whose parents will be found.

Returns:

list of dict :

Items are parents of nodes corresponding to argued ids.

parent_id(node_ids)[source]

Obtain the ids of one or more nodes’ parents

Parameters:

node_ids : list of hashable

Items are ids of nodes whose parents you wish to find.

Returns:

list of hashable :

Items are ids of input nodes’ parents in order.

value_map(from_fn, to_fn)[source]

Obtain a look-up table relating a pair of node properties across nodes

Parameters:

from_fn : function | node dict => hashable value

The keys of the output dictionary will be obtained by calling from_fn on each node.

to_fn : function | node_dict => value

The values of the output function will be obtained by calling to_fn on each node.

Returns:

dict :

Maps the node property defined by from_fn to the node property defined by to_fn across nodes.

Notes

The resulting map is not necessarily 1-to-1!

allensdk.core.structure_tree module

class allensdk.core.structure_tree.StructureTree(nodes)[source]

Bases: allensdk.core.simple_tree.SimpleTree

FIELDS = ['acronym', 'color_hex_triplet', 'graph_id', 'graph_order', 'id', 'name', 'structure_id_path', 'structure_set_ids']
static clean_structures(structures, field_whitelist=None)[source]

Convert structures_with_sets query results into a form that can be used to construct a StructureTree

Parameters:

structures : list of dict

Each element describes a structure. Should have a structure id path field (str values) and a structure_sets field (list of dict).

field_whitelist : list of str, optional

Each record should keep only fields in this list

Returns:

list of dict :

structures, after conversion of structure_id_path and structure_sets

static filter_dict(dictionary, *pass_keys)[source]
get_ancestor_id_map()[source]

Get a dictionary mapping structure ids to ancestor ids across all nodes.

Returns:

dict :

Keys are structure ids. Values are lists of ancestor ids.

get_colormap()[source]

Get a dictionary mapping structure ids to colors across all nodes.

Returns:

dict :

Keys are structure ids. Values are RGB lists of integers.

get_id_acronym_map()[source]

Get a dictionary mapping structure acronyms to ids across all nodes.

Returns:

dict :

Keys are structure acronyms. Values are structure ids.

get_name_map()[source]

Get a dictionary mapping structure ids to names across all nodes.

Returns:

dict :

Keys are structure ids. Values are structure name strings.

get_structure_sets()[source]

Lists all unique structure sets that are assigned to at least one structure in the tree.

Returns:

list of int :

Elements are ids of structure sets.

get_structures_by_acronym(acronyms)[source]

Obtain a list of brain structures from their acronyms

Parameters:

names : list of str

Get structures corresponding to these acronyms.

Returns:

list of dict :

Each item describes a structure.

get_structures_by_id(structure_ids)[source]

Obtain a list of brain structures from their structure ids

Parameters:

structure_ids : list of int

Get structures corresponding to these ids.

Returns:

list of dict :

Each item describes a structure.

get_structures_by_name(names)[source]

Obtain a list of brain structures from their names,

Parameters:

names : list of str

Get structures corresponding to these names.

Returns:

list of dict :

Each item describes a structure.

get_structures_by_set_id(structure_set_ids)[source]

Obtain a list of brain structures from by the sets that contain them.

Parameters:

structure_set_ids : list of int

Get structures belonging to these structure sets.

Returns:

list of dict :

Each item describes a structure.

has_overlaps(structure_ids)[source]

Determine if a list of structures contains structures along with their ancestors

Parameters:

structure_ids : list of int

Check this set of structures for overlaps

Returns:

set :

Ids of structures that are the ancestors of other structures in the supplied set.

static hex_to_rgb(hex_color)[source]

Convert a hexadecimal color string to a uint8 triplet

Parameters:

hex_color : string

Must be 6 characters long, unless it is 7 long and the first character is #.

Returns:

list of int :

3 characters long - 1 per two characters in the input string.

structure_descends_from(child_id, parent_id)[source]

Tests whether one structure descends from another.

Parameters:

child_id : int

Id of the putative child structure.

parent_id : int

Id of the putative parent structure.

Returns:

bool :

True if the structure specified by child_id is a descendant of the one specified by parent_id. Otherwise False.

allensdk.core.swc module

class allensdk.core.swc.Compartment(*args, **kwargs)[source]

Bases: dict

A dictionary class storing information about a single morphology node

print_node()[source]

print out compartment information with field names

class allensdk.core.swc.Marker(*args, **kwargs)[source]

Bases: dict

Simple dictionary class for handling reconstruction marker objects.

CUT_DENDRITE = 10
NO_RECONSTRUCTION = 20
SPACING = [0.1144, 0.1144, 0.28]
class allensdk.core.swc.Morphology(compartment_list=None, compartment_index=None)[source]

Bases: object

Keep track of the list of compartments in a morphology and provide a few helper methods (soma, tree information, pruning, etc).

APICAL_DENDRITE = 4
AXON = 2
BASAL_DENDRITE = 3
DENDRITE = 3
NODE_TYPES = [1, 2, 3, 3, 4]
SOMA = 1
append(node_list)[source]

Add additional nodes to this Morphology. Those nodes must originate from another morphology object.

Parameters:node_list: list of Morphology nodes
apply_affine(aff, scale=None)[source]

Apply an affine transform to all compartments in this morphology. Node radius is adjusted as well.

Format of the affine matrix is:

[x0 y0 z0] [tx] [x1 y1 z1] [ty] [x2 y2 z2] [tz]

where the left 3x3 the matrix defines the affine rotation and scaling, and the right column is the translation vector.

The matrix must be collapsed and stored in a list as follows:

[x0 y0, z0, x1, y1, z1, x2, y2, z2, tx, ty, tz]

Parameters:

aff: 3x4 array of floats (python 2D list, or numpy 2D array)

the transformation matrix

change_parent(child, parent)[source]

Change the parent of a node. The child node is adjusted to point to the new parent, the child is taken off of the previous parent’s child list, and it is added to the new parent’s child list.

Parameters:

child: integer or Morphology Object

The ID of the child node, or the child node itself

parent: integer or Morphology Object

The ID of the parent node, or the parent node itself

Returns:

Nothing

children_of(seg)[source]

Returns a list of the children of the specified node

Parameters:

seg: integer or Morphology Object

The ID of the parent node, or the parent node itself

Returns:

A list of the child morphology objects. If the ID of the parent

node is invalid, None is returned.

compartment_index

Return the compartment index. This is a property to ensure that the compartment list and compartment index are in sync.

compartment_index_by_type(compartment_type)[source]

Return an dictionary of compartments indexed by id that all have a particular compartment type.

Parameters:

compartment_type: int

Desired compartment type

Returns:

A dictionary of Morphology Objects, indexed by ID

compartment_list

Return the compartment list. This is a property to ensure that the compartment list and compartment index are in sync.

compartment_list_by_type(compartment_type)[source]

Return an list of all compartments having the specified compartment type.

Parameters:

compartment_type: int

Desired compartment type

Returns:

A list of of Morphology Objects

convert_type(old_type, new_type)[source]

Converts all compartments from one type to another. Nodes of the original type are not affected so this procedure can also be used as a merge procedure.

Parameters:

old_type: enum

The compartment type to be changed. Use one of the following constants: SOMA, AXON, DENDRITE, BASAL_DENDRITE, or APICAL_DENDRITE

new_type: enum

The target compartment type. Use one of the following constants: SOMA, AXON, DENDRITE, BASAL_DENDRITE, or APICAL_DENDRITE

delete_tree(n)[source]

Delete tree, and all of its compartments, from the morphology.

Parameters:

n: Integer

The tree number to delete

find(x, y, z, dist, node_type=None)[source]

Returns a list of Morphology Objects located within ‘dist’ of coordinate (x,y,z). If node_type is specified, the search will be constrained to return only nodes of that type.

Parameters:

x, y, z: float

The x,y,z coordinates from which to search around

dist: float

The search radius

node_type: enum (optional)

One of the following constants: SOMA, AXON, DENDRITE, BASAL_DENDRITE or APICAL_DENDRITE

Returns:

A list of all Morphology Objects matching the search criteria

node(n)[source]

Returns the morphology node having the specified ID.

Parameters:

n: integer

ID of desired node

Returns:

A morphology object having the specified ID, or None if such a

node doesn’t exist

num_nodes

Return the number of compartments in the morphology.

num_trees

Return the number of trees in the morphology. A tree is defined as everything following from a single root compartment.

parent_of(seg)[source]

Returns parent of the specified node.

Parameters:

seg: integer or Morphology Object

The ID of the child node, or the child node itself

Returns:

A morphology object, or None if no parent exists or if the

specified node ID doesn’t exist

root

[deprecated] Returns root node of soma, if present. Use ‘soma’ instead of ‘root’

save(file_name)[source]

Write this morphology out to an SWC file

Parameters:

file_name: string

desired name of your SWC file

soma

Returns root node of soma, if present

sparsify(modulo, compress_ids=False)[source]

Return a new Morphology object that has a given number of non-leaf, non-root nodes removed. IDs can be reassigned so as to be continuous.

Parameters:

modulo: int

keep 1 out of every modulo nodes.

compress_ids: boolean

Reassign ids so that ids are continuous (no missing id numbers).

Returns:

Morphology

A new morphology instance

strip_all_other_types(node_type, keep_soma=True)[source]

Strips everything from the morphology except for the specified type. Parent and child relationships are updated accordingly, creating new roots when necessary.

Parameters:

node_type: enum

The compartment type to keep in the morphology. Use one of the following constants: SOMA, AXON, DENDRITE, BASAL_DENDRITE, or APICAL_DENDRITE

keep_soma: Boolean (optional)

True (default) if soma nodes should remain in the morpyhology, and False if the soma should also be stripped

strip_type(node_type)[source]

Strips all compartments of the specified type from the morphology. Parent and child relationships are updated accordingly, creating new roots when necessary.

Parameters:

node_type: enum

The compartment type to strip from the morphology. Use one of the following constants: SOMA, AXON, DENDRITE, BASAL_DENDRITE, or APICAL_DENDRITE

stumpify_axon(count=10)[source]

Remove all axon compartments except the first ‘count’ nodes, as counted from the connected axon root.

Parameters:

count: Integer

The length of the axon ‘stump’, in number of compartments

tree(n)[source]

Returns a list of all Morphology Nodes within the specified tree. A tree is defined as a fully connected graph of nodes. Each tree has exactly one root.

Parameters:

n: integer

ID of desired tree

Returns:

A list of all morphology objects in the specified tree, or None

if the tree doesn’t exist

write(file_name)[source]
allensdk.core.swc.read_marker_file(file_name)[source]

read in a marker file and return a list of dictionaries

allensdk.core.swc.read_swc(file_name, columns='NOT_USED', numeric_columns='NOT_USED')[source]

Read in an SWC file and return a Morphology object.

Parameters:

file_name: string

SWC file name.

Returns:

Morphology

A Morphology instance.

Module contents