roiextractors package#

Subpackages#

Submodules#

roiextractors.extraction_tools module#

Various tools for extraction of ROIs from imaging data.

Classes#

VideoStructure

A data class for specifying the structure of a video.

raise_multi_channel_or_depth_not_implemented(extractor_name: str)[source]#

Raise a NotImplementedError for an extractor that does not support multiple channels or depth (z-axis).

class VideoStructure(num_rows: int, num_columns: int, num_channels: int, rows_axis: int, columns_axis: int, channels_axis: int, frame_axis: int)[source]#

Bases: object

A data class for specifying the structure of a video.

The role of the data class is to ensure consistency in naming and provide some initial consistency checks to ensure the validity of the sturcture.

Variables:
  • num_rows (int) – The number of rows of each frame as a matrix.

  • num_columns (int) – The number of columns of each frame as a matrix.

  • num_channels (int) – The number of channels (1 for grayscale, 3 for color).

  • rows_axis (int) – The axis or dimension corresponding to the rows.

  • columns_axis (int) – The axis or dimension corresponding to the columns.

  • channels_axis (int) – The axis or dimension corresponding to the channels.

  • frame_axis (int) – The axis or dimension corresponding to the frames in the video.

  • 5 (>>> num_columns =)

  • you (where the video is to have the following shape (num_frames, num_rows, num_columns, num_channels))

  • way (could define the class this)

  • VideoStructure (>>> from roiextractors.extraction_tools import)

  • 10 (>>> num_rows =)

  • 5

  • 1 (>>> rows_axis =)

  • 0 (>>> frame_axis =)

  • 1

  • 2 (>>> columns_axis =)

  • 3 (>>> channels_axis =)

  • VideoStructure( (>>> video_structure =) – num_rows=num_rows, num_columns=num_columns, num_channels=num_channels, rows_axis=rows_axis, columns_axis=columns_axis, channels_axis=channels_axis, frame_axis=frame_axis,

  • )

num_rows: int#
num_columns: int#
num_channels: int#
rows_axis: int#
columns_axis: int#
channels_axis: int#
frame_axis: int#
__post_init__() None[source]#

Validate the structure of the video and initialize the shape of the frame.

_initialize_frame_shape() None[source]#

Initialize the shape of the frame.

_validate_video_structure() None[source]#

Validate the structure of the video.

build_video_shape(n_frames: int) Tuple[int, int, int, int][source]#

Build the shape of the video from class attributes.

Parameters:

n_frames (int) – The number of frames in the video.

Returns:

The shape of the video.

Return type:

Tuple[int, int, int, int]

Notes

The class attributes frame_axis, rows_axis, columns_axis and channels_axis are used to determine the order of the dimensions in the returned tuple.

transform_video_to_canonical_form(video: ndarray) ndarray[source]#

Transform a video to the canonical internal format of roiextractors (num_frames, num_rows, num_columns, num_channels).

Parameters:

video (numpy.ndarray) – The video to be transformed

Returns:

The reshaped video

Return type:

numpy.ndarray

Raises:

KeyError – If the video is not in a format that can be transformed.

read_numpy_memmap_video(file_path: str | Path, video_structure: VideoStructure, dtype: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any], offset: int = 0) array[source]#

Auxiliary function to read videos from binary files.

Parameters:
  • file_path (PathType) – the file_path where the data resides.

  • video_structure (VideoStructure) – A VideoStructure instance describing the structure of the video to read. This includes parameters such as the number of rows, columns and channels plus which axis (i.e. dimension) of the image corresponds to each of them.

    As an example you create one of these structures in the following way:

    from roiextractors.extraction_tools import VideoStructure

    num_rows = 10 num_columns = 5 num_channels = 3 frame_axis = 0 rows_axis = 1 columns_axis = 2 channels_axis = 3

    video_structure = VideoStructure(

    num_rows=num_rows, num_columns=num_columns, num_channels=num_channels, rows_axis=rows_axis, columns_axis=columns_axis, channels_axis=channels_axis, frame_axis=frame_axis,

    )

  • dtype (DtypeType) – The type of the data to be loaded (int, float, etc.)

  • offset (int, optional) – The offset in bytes. Usually corresponds to the number of bytes occupied by the header. 0 by default.

Returns:

video_memap – A numpy memmap pointing to the video.

Return type:

np.array

_pixel_mask_extractor(image_mask_, _roi_ids) list[source]#

Convert image mask to pixel mask.

Pixel masks are an alternative data format for storage of image masks which relies on the sparsity of the images. The location and weight of each non-zero pixel is stored for each mask.

Parameters:
  • image_mask_ (numpy.ndarray) – Dense representation of the ROIs with shape (number_of_rows, number_of_columns, number_of_rois).

  • _roi_ids (list) – List of roi ids with length number_of_rois.

Returns:

pixel_masks – List of length number of rois, each element is a 2-D array with shape (number_of_non_zero_pixels, 3). Columns 1 and 2 are the x and y coordinates of the pixel, while the third column represents the weight of the pixel.

Return type:

list

_image_mask_extractor(pixel_mask, _roi_ids, image_shape) ndarray[source]#

Convert a pixel mask to image mask.

Parameters:
  • pixel_mask (list) – list of pixel masks (no pixels X 3)

  • _roi_ids (list) – list of roi ids with length number_of_rois

  • image_shape (array_like) – shape of the image (number_of_rows, number_of_columns)

Returns:

image_mask – Dense representation of the ROIs with shape (number_of_rows, number_of_columns, number_of_rois).

Return type:

np.ndarray

check_get_frames_args(func)[source]#

Check the arguments of the get_frames function.

This decorator allows the get_frames function to be queried with either an integer, slice or an array and handles a common return. [I think that np.take can be used instead of this]

Parameters:

func (function) – The get_frames function.

Returns:

corrected_args – The get_frames function with corrected arguments.

Return type:

function

Raises:

AssertionError – If ‘frame_idxs’ exceed the number of frames.

_cast_start_end_frame(start_frame, end_frame)[source]#

Cast start and end frame to int or None.

Parameters:
  • start_frame (int, float, None) – The start frame.

  • end_frame (int, float, None) – The end frame.

Returns:

  • start_frame (int, None) – The start frame.

  • end_frame (int, None) – The end frame.

Raises:
  • ValueError – If start_frame is not an int, float or None.

  • ValueError – If end_frame is not an int, float or None.

check_get_videos_args(func)[source]#

Check the arguments of the get_videos function.

This decorator allows the get_videos function to be queried with either an integer or slice and handles a common return.

Parameters:

func (function) – The get_videos function.

Returns:

corrected_args – The get_videos function with corrected arguments.

Return type:

function

Raises:
  • AssertionError – If ‘start_frame’ exceeds the number of frames.

  • AssertionError – If ‘end_frame’ exceeds the number of frames.

  • AssertionError – If ‘start_frame’ is greater than ‘end_frame’.

write_to_h5_dataset_format(imaging, dataset_path, save_path=None, file_handle=None, dtype=None, chunk_size=None, chunk_mb=1000, verbose=False)[source]#

Save the video of an imaging extractor in an h5 dataset.

Parameters:
  • imaging (ImagingExtractor) – The imaging extractor object to be saved in the .h5 file

  • dataset_path (str) – Path to dataset in h5 file (e.g. ‘/dataset’)

  • save_path (str) – The path to the file.

  • file_handle (file handle) – The file handle to dump data. This can be used to append data to an header. In case file_handle is given, the file is NOT closed after writing the binary data.

  • dtype (dtype) – Type of the saved data. Default float32.

  • chunk_size (None or int) – Number of chunks to save the file in. This avoid to much memory consumption for big files. If None and ‘chunk_mb’ is given, the file is saved in chunks of ‘chunk_mb’ Mb (default 500Mb)

  • chunk_mb (None or int) – Chunk size in Mb (default 1000Mb)

  • verbose (bool) – If True, output is verbose (when chunks are used)

Returns:

save_path – The path to the file.

Return type:

str

Raises:
  • AssertionError – If h5py is not installed.

  • AssertionError – If neither ‘save_path’ nor ‘file_handle’ are given.

show_video(imaging, ax=None)[source]#

Show video as animation.

Parameters:
  • imaging (ImagingExtractor) – The imaging extractor object to be saved in the .h5 file

  • ax (matplotlib axis) – Axis to plot the video. If None, a new axis is created.

Returns:

anim – Animation of the video.

Return type:

matplotlib.animation.FuncAnimation

check_keys(dict)[source]#

Check keys of dictionary for mat-objects.

Checks if entries in dictionary are mat-objects. If yes todict is called to change them to nested dictionaries.

Parameters:

dict (dict) – Dictionary to check.

Returns:

dict – Dictionary with mat-objects converted to nested dictionaries.

Return type:

dict

Raises:

AssertionError – If scipy is not installed.

todict(matobj)[source]#

Recursively construct nested dictionaries from matobjects.

Parameters:

matobj (mat_struct) – Matlab object to convert to nested dictionary.

Returns:

dict – Dictionary with mat-objects converted to nested dictionaries.

Return type:

dict

get_package(package_name: str, installation_instructions: str | None = None, excluded_platforms_and_python_versions: Dict[str, List[str]] | None = None) ModuleType[source]#

Check if package is installed and return module if so.

Otherwise, raise informative error describing how to perform the installation. Inspired by https://docs.python.org/3/library/importlib.html#checking-if-a-module-can-be-imported.

Parameters:
  • package_name (str) – Name of the package to be imported.

  • installation_instructions (str, optional) – String describing the source, options, and alias of package name (if needed) for installation. For example,

    >>> installation_source = "conda install -c conda-forge my-package-name"
    

    Defaults to f”pip install {package_name}”.

  • excluded_platforms_and_python_versions (dict mapping string platform names to a list of string versions, optional) – In case some combinations of platforms or Python versions are not allowed for the given package, specify this dictionary to raise a more specific error to that issue. For example, excluded_platforms_and_python_versions = dict(darwin=[“3.7”]) will raise an informative error when running on MacOS with Python version 3.7. Allows all platforms and Python versions used by default.

Raises:

ModuleNotFoundError – If the package is not installed.

roiextractors.extractorlist module#

Listing of available formats for extraction.

roiextractors.imagingextractor module#

Base class definitions for all ImagingExtractors.

Classes#

ImagingExtractor

Abstract class that contains all the meta-data and input data from the imaging data.

FrameSliceImagingExtractor

Class to get a lazy frame slice.

class ImagingExtractor(*args, **kwargs)[source]#

Bases: ABC

Abstract class that contains all the meta-data and input data from the imaging data.

Initialize the ImagingExtractor object.

abstract get_image_size() Tuple[int, int][source]#

Get the size of the video (num_rows, num_columns).

Returns:

image_size – Size of the video (num_rows, num_columns).

Return type:

tuple

abstract get_num_frames() int[source]#

Get the number of frames in the video.

Returns:

num_frames – Number of frames in the video.

Return type:

int

abstract get_sampling_frequency() float[source]#

Get the sampling frequency in Hz.

Returns:

sampling_frequency – Sampling frequency in Hz.

Return type:

float

abstract get_channel_names() list[source]#

Get the channel names in the recoding.

Returns:

channel_names – List of strings of channel names

Return type:

list

abstract get_num_channels() int[source]#

Get the total number of active channels in the recording.

Returns:

num_channels – Integer count of number of channels.

Return type:

int

get_dtype() dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any][source]#

Get the data type of the video.

Returns:

dtype – Data type of the video.

Return type:

dtype

abstract get_video(start_frame: int | None = None, end_frame: int | None = None, channel: int = 0) ndarray[source]#

Get the video frames.

Parameters:
  • start_frame (int, optional) – Start frame index (inclusive).

  • end_frame (int, optional) – End frame index (exclusive).

  • channel (int, optional) – Channel index.

Returns:

video – The video frames.

Return type:

numpy.ndarray

Notes

Importantly, we follow the convention that the dimensions of the array are returned in their matrix order, More specifically: (time, height, width)

Which is equivalent to: (samples, rows, columns)

Note that this does not match the cartesian convention: (t, x, y)

Where x is the columns width or and y is the rows or height.

get_frames(frame_idxs: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], channel: int | None = 0) ndarray[source]#

Get specific video frames from indices (not necessarily continuous).

Parameters:
  • frame_idxs (array-like) – Indices of frames to return.

  • channel (int, optional) – Channel index.

Returns:

frames – The video frames.

Return type:

numpy.ndarray

frame_to_time(frames: float | ndarray) float | ndarray[source]#

Convert user-inputted frame indices to times with units of seconds.

Parameters:

frames (int or array-like) – The frame or frames to be converted to times.

Returns:

times – The corresponding times in seconds.

Return type:

float or array-like

time_to_frame(times: float | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) float | ndarray[source]#

Convert a user-inputted times (in seconds) to a frame indices.

Parameters:

times (float or array-like) – The times (in seconds) to be converted to frame indices.

Returns:

frames – The corresponding frame indices.

Return type:

float or array-like

set_times(times: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) None[source]#

Set the recording times (in seconds) for each frame.

Parameters:

times (array-like) – The times in seconds for each frame

has_time_vector() bool[source]#

Detect if the ImagingExtractor has a time vector set or not.

Returns:

has_times – True if the ImagingExtractor has a time vector set, otherwise False.

Return type:

bool

copy_times(extractor) None[source]#

Copy times from another extractor.

Parameters:

extractor – The extractor from which the times will be copied.

frame_slice(start_frame: int | None = None, end_frame: int | None = None)[source]#

Return a new ImagingExtractor ranging from the start_frame to the end_frame.

Parameters:
  • start_frame (int, optional) – Start frame index (inclusive).

  • end_frame (int, optional) – End frame index (exclusive).

Returns:

imaging – The sliced ImagingExtractor object.

Return type:

FrameSliceImagingExtractor

static write_imaging(imaging, save_path: str | Path, overwrite: bool = False)[source]#

Write an imaging extractor to its native file structure.

Parameters:
  • imaging (ImagingExtractor) – The imaging extractor object to be saved.

  • save_path (str or Path) – Path to save the file.

  • overwrite (bool, optional) – If True, overwrite the file/folder if it already exists. The default is False.

_abc_impl = <_abc._abc_data object>#
class FrameSliceImagingExtractor(parent_imaging: ImagingExtractor, start_frame: int | None = None, end_frame: int | None = None)[source]#

Bases: ImagingExtractor

Class to get a lazy frame slice.

Do not use this class directly but use .frame_slice(…) on an ImagingExtractor object.

Initialize an ImagingExtractor whose frames subset the parent.

Subset is exclusive on the right bound, that is, the indexes of this ImagingExtractor range over [0, …, end_frame-start_frame-1], which is used to resolve the index mapping in get_frames(frame_idxs=[…]).

Parameters:
  • parent_imaging (ImagingExtractor) – The ImagingExtractor object to sebset the frames of.

  • start_frame (int, optional) – The left bound of the frames to subset. The default is the start frame of the parent.

  • end_frame (int, optional) – The right bound of the frames, exlcusively, to subset. The default is end frame of the parent.

extractor_name = 'FrameSliceImagingExtractor'#
installed = True#
is_writable = True#
installation_mesg = ''#
get_frames(frame_idxs: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes], channel: int | None = 0) ndarray[source]#

Get specific video frames from indices (not necessarily continuous).

Parameters:
  • frame_idxs (array-like) – Indices of frames to return.

  • channel (int, optional) – Channel index.

Returns:

frames – The video frames.

Return type:

numpy.ndarray

get_video(start_frame: int | None = None, end_frame: int | None = None, channel: int | None = 0) ndarray[source]#

Get the video frames.

Parameters:
  • start_frame (int, optional) – Start frame index (inclusive).

  • end_frame (int, optional) – End frame index (exclusive).

  • channel (int, optional) – Channel index.

Returns:

video – The video frames.

Return type:

numpy.ndarray

Notes

Importantly, we follow the convention that the dimensions of the array are returned in their matrix order, More specifically: (time, height, width)

Which is equivalent to: (samples, rows, columns)

Note that this does not match the cartesian convention: (t, x, y)

Where x is the columns width or and y is the rows or height.

get_image_size() Tuple[int, int][source]#

Get the size of the video (num_rows, num_columns).

Returns:

image_size – Size of the video (num_rows, num_columns).

Return type:

tuple

get_num_frames() int[source]#

Get the number of frames in the video.

Returns:

num_frames – Number of frames in the video.

Return type:

int

get_sampling_frequency() float[source]#

Get the sampling frequency in Hz.

Returns:

sampling_frequency – Sampling frequency in Hz.

Return type:

float

get_channel_names() list[source]#

Get the channel names in the recoding.

Returns:

channel_names – List of strings of channel names

Return type:

list

get_num_channels() int[source]#

Get the total number of active channels in the recording.

Returns:

num_channels – Integer count of number of channels.

Return type:

int

_abc_impl = <_abc._abc_data object>#

roiextractors.memmapextractors module#

roiextractors.multisegmentationextractor module#

Defines the MultiSegmentationExtractor class.

Classes#

MultiSegmentationExtractor

This class is used to combine multiple SegmentationExtractor objects by frames.

concatenate_output(func)[source]#

Concatenate output of single SegmentationExtractor methods.

Parameters:

func (function) – function to be decorated

Returns:

_get_from_roi_map – decorated function

Return type:

function

class MultiSegmentationExtractor(segmentatation_extractors_list, plane_names=None)[source]#

Bases: SegmentationExtractor

Class is used to concatenate multi-plane recordings from the same device and session of experiment.

Initialize a MultiSegmentationExtractor object from a list of SegmentationExtractors.

Parameters:
  • segmentatation_extractors_list (list of SegmentationExtractor) – list of segmentation extractor objects (one for each plane)

  • plane_names (list) – list of strings of names for the plane. Defaults to ‘Plane0’, ‘Plane1’ …

extractor_name = 'MultiSegmentationExtractor'#
installed = True#
is_writable = False#
mode = 'file'#
installation_mesg = ''#
property no_planes#

Number of planes in the recording.

Returns:

no_planes – number of planes in the recording

Return type:

int

property segmentations#

List of segmentation extractors (one for each plane).

Returns:

segmentations – list of segmentation extractors (one for each plane)

Return type:

list

get_num_channels()[source]#

Get number of channels in the pipeline.

Returns:

num_of_channels – number of channels

Return type:

int

get_num_rois()[source]#

Get total number of Regions of Interest (ROIs) in the acquired images.

Returns:

num_rois – The number of ROIs extracted.

Return type:

int

get_images(name='correlation_plane0')[source]#

Get images from the imaging extractors.

Parameters:

name (str) – name of the image to get

Returns:

images – Array of images.

Return type:

numpy.ndarray

get_images_dict()[source]#

Get images as a dictionary with key as the name of the ROIResponseSeries.

Returns:

_roi_image_dict

dictionary with key, values representing different types of Images used in segmentation:

Mean, Correlation image

Return type:

dict

get_traces_dict()[source]#

Get traces as a dictionary with key as the name of the ROiResponseSeries.

Returns:

_roi_response_dict

dictionary with key, values representing different types of RoiResponseSeries:

Raw Fluorescence, DeltaFOverF, Denoised, Neuropil, Deconvolved, Background, etc.

Return type:

dict

get_image_size()[source]#

Get frame size of movie (height, width).

Returns:

no_rois – 2-D array: image height x image width

Return type:

array_like

get_traces(roi_ids=None, **kwargs)[source]#

Call member function of each SegmentationExtractor specified by func and concatenate the output.

Parameters:
  • roi_ids (list) – list of roi ids to be used

  • kwargs (dict) – keyword arguments to be passed to func

Returns:

out – list of outputs from each SegmentationExtractor

Return type:

list

get_roi_pixel_masks(roi_ids=None, **kwargs)[source]#

Call member function of each SegmentationExtractor specified by func and concatenate the output.

Parameters:
  • roi_ids (list) – list of roi ids to be used

  • kwargs (dict) – keyword arguments to be passed to func

Returns:

out – list of outputs from each SegmentationExtractor

Return type:

list

get_roi_image_masks(roi_ids=None, **kwargs)[source]#

Call member function of each SegmentationExtractor specified by func and concatenate the output.

Parameters:
  • roi_ids (list) – list of roi ids to be used

  • kwargs (dict) – keyword arguments to be passed to func

Returns:

out – list of outputs from each SegmentationExtractor

Return type:

list

get_roi_locations(roi_ids=None, **kwargs)[source]#

Call member function of each SegmentationExtractor specified by func and concatenate the output.

Parameters:
  • roi_ids (list) – list of roi ids to be used

  • kwargs (dict) – keyword arguments to be passed to func

Returns:

out – list of outputs from each SegmentationExtractor

Return type:

list

get_num_frames()[source]#

Get the number of frames in the recording (duration of recording).

Returns:

num_frames – Number of frames in the recording.

Return type:

int

get_accepted_list()[source]#

Get a list of accepted ROI ids.

Returns:

accepted_list – List of accepted ROI ids.

Return type:

list

get_rejected_list()[source]#

Get a list of rejected ROI ids.

Returns:

rejected_list – List of rejected ROI ids.

Return type:

list

_abc_impl = <_abc._abc_data object>#

roiextractors.segmentationextractor module#

Base segmentation extractors.

Classes#

SegmentationExtractor

Abstract class that contains all the meta-data and output data from the ROI segmentation operation when applied to the pre-processed data. It also contains methods to read from and write to various data formats output from the processing pipelines like SIMA, CaImAn, Suite2p, CNMF-E.

FrameSliceSegmentationExtractor

Class to get a lazy frame slice.

class SegmentationExtractor[source]#

Bases: ABC

Abstract segmentation extractor class.

An abstract class that contains all the meta-data and output data from the ROI segmentation operation when applied to the pre-processed data. It also contains methods to read from and write to various data formats output from the processing pipelines like SIMA, CaImAn, Suite2p, CNMF-E. All the methods with @abstract decorator have to be defined by the format specific classes that inherit from this.

Create a new SegmentationExtractor from specified data type (unique to each child SegmentationExtractor).

abstract get_accepted_list() list[source]#

Get a list of accepted ROI ids.

Returns:

accepted_list – List of accepted ROI ids.

Return type:

list

abstract get_rejected_list() list[source]#

Get a list of rejected ROI ids.

Returns:

rejected_list – List of rejected ROI ids.

Return type:

list

get_num_frames() int[source]#

Get the number of frames in the recording (duration of recording).

Returns:

num_frames – Number of frames in the recording.

Return type:

int

get_roi_locations(roi_ids=None) ndarray[source]#

Get the locations of the Regions of Interest (ROIs).

Parameters:

roi_ids (array_like) – A list or 1D array of ids of the ROIs. Length is the number of ROIs requested.

Returns:

roi_locs – 2-D array: 2 X no_ROIs. The pixel ids (x,y) where the centroid of the ROI is.

Return type:

numpy.ndarray

get_roi_ids() list[source]#

Get the list of ROI ids.

Returns:

roi_ids – List of roi ids.

Return type:

list

get_roi_image_masks(roi_ids=None) ndarray[source]#

Get the image masks extracted from segmentation algorithm.

Parameters:

roi_ids (array_like) – A list or 1D array of ids of the ROIs. Length is the number of ROIs requested.

Returns:

image_masks – 3-D array(val 0 or 1): image_height X image_width X length(roi_ids)

Return type:

numpy.ndarray

get_roi_pixel_masks(roi_ids=None) array[source]#

Get the weights applied to each of the pixels of the mask.

Parameters:

roi_ids (array_like) – A list or 1D array of ids of the ROIs. Length is the number of ROIs requested.

Returns:

pixel_masks – List of length number of rois, each element is a 2-D array with shape (number_of_non_zero_pixels, 3). Columns 1 and 2 are the x and y coordinates of the pixel, while the third column represents the weight of the pixel.

Return type:

list

get_background_ids() list[source]#

Get the list of background components ids.

Returns:

background_components_ids – List of background components ids.

Return type:

list

get_background_image_masks(background_ids=None) ndarray[source]#

Get the background image masks extracted from segmentation algorithm.

Parameters:

background_ids (array_like) – A list or 1D array of ids of the background components. Length is the number of background components requested.

Returns:

background_image_masks – 3-D array(val 0 or 1): image_height X image_width X length(background_ids)

Return type:

numpy.ndarray

get_background_pixel_masks(background_ids=None) array[source]#

Get the weights applied to each of the pixels of the mask.

Parameters:

roi_ids (array_like) – A list or 1D array of ids of the ROIs. Length is the number of ROIs requested.

Returns:

pixel_masks – List of length number of rois, each element is a 2-D array with shape (number_of_non_zero_pixels, 3). Columns 1 and 2 are the x and y coordinates of the pixel, while the third column represents the weight of the pixel.

Return type:

list

abstract get_image_size() _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes][source]#

Get frame size of movie (height, width).

Returns:

no_rois – 2-D array: image height x image width

Return type:

array_like

frame_slice(start_frame: int | None = None, end_frame: int | None = None)[source]#

Return a new SegmentationExtractor ranging from the start_frame to the end_frame.

Parameters:
  • start_frame (int) – The starting frame of the new SegmentationExtractor.

  • end_frame (int) – The ending frame of the new SegmentationExtractor.

Returns:

frame_slice_segmentation_extractor – The frame slice segmentation extractor object.

Return type:

FrameSliceSegmentationExtractor

get_traces(roi_ids: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None, start_frame: int | None = None, end_frame: int | None = None, name: str = 'raw')[source]#

Get the traces of each ROI specified by roi_ids.

Parameters:
  • roi_ids (array_like) – A list or 1D array of ids of the ROIs. Length is the number of ROIs requested.

  • start_frame (int) – The starting frame of the trace.

  • end_frame (int) – The ending frame of the trace.

  • name (str) – The name of the trace to retrieve ex. ‘raw’, ‘dff’, ‘neuropil’, ‘deconvolved’

Returns:

traces – 2-D array (ROI x timepoints)

Return type:

array_like

get_traces_dict()[source]#

Get traces as a dictionary with key as the name of the ROiResponseSeries.

Returns:

_roi_response_dict

dictionary with key, values representing different types of RoiResponseSeries:

Raw Fluorescence, DeltaFOverF, Denoised, Neuropil, Deconvolved, Background, etc.

Return type:

dict

get_images_dict()[source]#

Get images as a dictionary with key as the name of the ROIResponseSeries.

Returns:

_roi_image_dict

dictionary with key, values representing different types of Images used in segmentation:

Mean, Correlation image

Return type:

dict

get_image(name: str = 'correlation') _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes][source]#

Get specific images: mean or correlation.

Parameters:

name (str) – name of the type of image to retrieve

Returns:

images

Return type:

numpy.ndarray

get_sampling_frequency() float[source]#

Get the sampling frequency in Hz.

Returns:

sampling_frequency – Sampling frequency of the recording in Hz.

Return type:

float

get_num_rois() int[source]#

Get total number of Regions of Interest (ROIs) in the acquired images.

Returns:

num_rois – The number of ROIs extracted.

Return type:

int

get_num_background_components() int[source]#

Get total number of background components in the acquired images.

Returns:

num_background_components – The number of background components extracted.

Return type:

int

get_channel_names() List[str][source]#

Get names of channels in the pipeline.

Returns:

_channel_names – names of channels (str)

Return type:

list

get_num_channels() int[source]#

Get number of channels in the pipeline.

Returns:

num_of_channels – number of channels

Return type:

int

get_num_planes()[source]#

Get the default number of planes of imaging for the segmentation extractor.

Notes

Defaults to 1 for all but the MultiSegmentationExtractor.

Returns:

self._num_planes – number of planes

Return type:

int

set_times(times: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes])[source]#

Set the recording times in seconds for each frame.

Parameters:

times (array-like) – The times in seconds for each frame

Notes

Operates on _times attribute of the SegmentationExtractor object.

has_time_vector() bool[source]#

Detect if the SegmentationExtractor has a time vector set or not.

Returns:

has_time_vector – True if the SegmentationExtractor has a time vector set, otherwise False.

Return type:

bool

frame_to_time(frames: int | integer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes]) float | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes][source]#

Get the timing of frames in unit of seconds.

Parameters:

frames (int or array-like) – The frame or frames to be converted to times

Returns:

times – The corresponding times in seconds

Return type:

float or array-like

static write_segmentation(segmentation_extractor, save_path, overwrite=False)[source]#

Write recording back to the native format.

Parameters:
  • segmentation_extractor ([SegmentationExtractor, MultiSegmentationExtractor]) – The EXTRACT segmentation object from which an EXTRACT native format file has to be generated.

  • save_path (str) – path to save the native format.

  • overwrite (bool) – If True, the file is overwritten if existing (default False)

_abc_impl = <_abc._abc_data object>#
class FrameSliceSegmentationExtractor(parent_segmentation: SegmentationExtractor, start_frame: int | None = None, end_frame: int | None = None)[source]#

Bases: SegmentationExtractor

Class to get a lazy frame slice.

Do not use this class directly but use .frame_slice(…)

Create a new FrameSliceSegmentationExtractor from parent SegmentationExtractor.

Parameters:
  • parent_segmentation (SegmentationExtractor) – The parent SegmentationExtractor object.

  • start_frame (int) – The starting frame of the new SegmentationExtractor.

  • end_frame (int) – The ending frame of the new SegmentationExtractor.

extractor_name = 'FrameSliceSegmentationExtractor'#
is_writable = True#
get_accepted_list() list[source]#

Get a list of accepted ROI ids.

Returns:

accepted_list – List of accepted ROI ids.

Return type:

list

get_rejected_list() list[source]#

Get a list of rejected ROI ids.

Returns:

rejected_list – List of rejected ROI ids.

Return type:

list

get_traces(roi_ids: Iterable[int] | None = None, start_frame: int | None = None, end_frame: int | None = None, name: str = 'raw') ndarray[source]#

Get the traces of each ROI specified by roi_ids.

Parameters:
  • roi_ids (array_like) – A list or 1D array of ids of the ROIs. Length is the number of ROIs requested.

  • start_frame (int) – The starting frame of the trace.

  • end_frame (int) – The ending frame of the trace.

  • name (str) – The name of the trace to retrieve ex. ‘raw’, ‘dff’, ‘neuropil’, ‘deconvolved’

Returns:

traces – 2-D array (ROI x timepoints)

Return type:

array_like

get_traces_dict()[source]#

Get traces as a dictionary with key as the name of the ROiResponseSeries.

Returns:

_roi_response_dict

dictionary with key, values representing different types of RoiResponseSeries:

Raw Fluorescence, DeltaFOverF, Denoised, Neuropil, Deconvolved, Background, etc.

Return type:

dict

get_image_size() Tuple[int, int][source]#

Get frame size of movie (height, width).

Returns:

no_rois – 2-D array: image height x image width

Return type:

array_like

get_num_frames() int[source]#

Get the number of frames in the recording (duration of recording).

Returns:

num_frames – Number of frames in the recording.

Return type:

int

get_num_rois()[source]#

Get total number of Regions of Interest (ROIs) in the acquired images.

Returns:

num_rois – The number of ROIs extracted.

Return type:

int

get_images_dict() dict[source]#

Get images as a dictionary with key as the name of the ROIResponseSeries.

Returns:

_roi_image_dict

dictionary with key, values representing different types of Images used in segmentation:

Mean, Correlation image

Return type:

dict

get_image(name='correlation')[source]#

Get specific images: mean or correlation.

Parameters:

name (str) – name of the type of image to retrieve

Returns:

images

Return type:

numpy.ndarray

get_sampling_frequency() float[source]#

Get the sampling frequency in Hz.

Returns:

sampling_frequency – Sampling frequency of the recording in Hz.

Return type:

float

get_channel_names() list[source]#

Get names of channels in the pipeline.

Returns:

_channel_names – names of channels (str)

Return type:

list

get_num_channels() int[source]#

Get number of channels in the pipeline.

Returns:

num_of_channels – number of channels

Return type:

int

get_num_planes()[source]#

Get the default number of planes of imaging for the segmentation extractor.

Notes

Defaults to 1 for all but the MultiSegmentationExtractor.

Returns:

self._num_planes – number of planes

Return type:

int

get_roi_pixel_masks(roi_ids: _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | bool | int | float | complex | str | bytes | _NestedSequence[bool | int | float | complex | str | bytes] | None = None) List[ndarray][source]#

Get the weights applied to each of the pixels of the mask.

Parameters:

roi_ids (array_like) – A list or 1D array of ids of the ROIs. Length is the number of ROIs requested.

Returns:

pixel_masks – List of length number of rois, each element is a 2-D array with shape (number_of_non_zero_pixels, 3). Columns 1 and 2 are the x and y coordinates of the pixel, while the third column represents the weight of the pixel.

Return type:

list

_abc_impl = <_abc._abc_data object>#

roiextractors.testing module#

Testing utilities for the roiextractors package.

generate_dummy_video(size: Tuple[int], dtype: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any] = 'uint16')[source]#

Generate a dummy video of a given size and dtype.

Parameters:
  • size (Tuple[int]) – Size of the video to generate.

  • dtype (DtypeType, optional) – Dtype of the video to generate, by default “uint16”.

Returns:

video – A dummy video of the given size and dtype.

Return type:

np.ndarray

generate_dummy_imaging_extractor(num_frames: int = 30, num_rows: int = 10, num_columns: int = 10, num_channels: int = 1, sampling_frequency: float = 30, dtype: dtype[Any] | None | type[Any] | _SupportsDType[dtype[Any]] | str | tuple[Any, int] | tuple[Any, SupportsIndex | Sequence[SupportsIndex]] | list[Any] | _DTypeDict | tuple[Any, Any] = 'uint16', channel_names: list | None = None)[source]#

Generate a dummy imaging extractor for testing.

The imaging extractor is built by feeding random data into the NumpyImagingExtractor.

Parameters:
  • num_frames (int, optional) – number of frames in the video, by default 30.

  • num_rows (int, optional) – number of rows in the video, by default 10.

  • num_columns (int, optional) – number of columns in the video, by default 10.

  • num_channels (int, optional) – number of channels in the video, by default 1.

  • sampling_frequency (float, optional) – sampling frequency of the video, by default 30.

  • dtype (DtypeType, optional) – dtype of the video, by default “uint16”.

  • channel_names (list, optional) – list of channel names.

Returns:

An imaging extractor with random data fed into NumpyImagingExtractor.

Return type:

ImagingExtractor

generate_dummy_segmentation_extractor(num_rois: int = 10, num_frames: int = 30, num_rows: int = 25, num_columns: int = 25, sampling_frequency: float = 30.0, has_summary_images: bool = True, has_raw_signal: bool = True, has_dff_signal: bool = True, has_deconvolved_signal: bool = True, has_neuropil_signal: bool = True, rejected_list: list | None = None) SegmentationExtractor[source]#

Generate a dummy segmentation extractor for testing.

The segmentation extractor is built by feeding random data into the NumpySegmentationExtractor.

Parameters:
  • num_rois (int, optional) – number of regions of interest, by default 10.

  • num_frames (int, optional) – _description_, by default 30

  • num_rows (number of frames used in the hypotethical video from which the data was extracted, optional) – number of rows in the hypotethical video from which the data was extracted, by default 25.

  • num_columns (int, optional) – numbe rof columns in the hypotethical video from which the data was extracted, by default 25.

  • sampling_frequency (float, optional) – sampling frequency of the hypotethical video form which the data was extracted, by default 30.0.

  • has_summary_images (bool, optional) – whether the dummy segmentation extractor has summary images or not (mean and correlation)

  • has_raw_signal (bool, optional) – whether a raw fluoresence signal is desired in the object, by default True.

  • has_dff_signal (bool, optional) – whether a relative (df/f) fluoresence signal is desired in the object, by default True.

  • has_deconvolved_signal (bool, optional) – whether a deconvolved signal is desired in the object, by default True.

  • has_neuropil_signal (bool, optional) – whether a neuropil signal is desiredi n the object, by default True.

  • rejected_list (list, optional) – A list of rejected rois, None by default.

Returns:

A segmentation extractor with random data fed into NumpySegmentationExtractor

Return type:

SegmentationExtractor

Notes

Note that this dummy example is meant to be a mock object with the right shape, structure and objects but does not contain meaningful content. That is, the image masks matrices are not plausible image mask for a roi, the raw signal is not a meaningful biological signal and is not related appropriately to the deconvolved signal , etc.

_assert_iterable_shape(iterable, shape)[source]#

Assert that the iterable has the given shape. If the iterable is a numpy array, the shape is checked directly.

_assert_iterable_shape_max(iterable, shape_max)[source]#

Assert that the iterable has a shape less than or equal to the given maximum shape.

_assert_iterable_element_dtypes(iterable, dtypes)[source]#

Assert that the iterable has elements of the given dtypes.

_assert_iterable_complete(iterable, dtypes=None, element_dtypes=None, shape=None, shape_max=None)[source]#

Assert that the iterable is complete, i.e. it is not None and has the given dtypes, element_dtypes, shape and shape_max.

check_segmentations_equal(segmentation_extractor1: SegmentationExtractor, segmentation_extractor2: SegmentationExtractor)[source]#

Check that two segmentation extractors have equal fields.

check_segmentations_images(segmentation_extractor1: SegmentationExtractor, segmentation_extractor2: SegmentationExtractor)[source]#

Check that the segmentation images are equal for the given segmentation extractors.

check_segmentation_return_types(seg: SegmentationExtractor)[source]#

Check that the return types of the segmentation extractor are correct.

check_imaging_equal(imaging_extractor1: ImagingExtractor, imaging_extractor2: ImagingExtractor, exclude_channel_comparison: bool = False)[source]#

Check that two imaging extractors have equal fields.

assert_get_frames_return_shape(imaging_extractor: ImagingExtractor)[source]#

Check whether an ImagingExtractor get_frames function behaves as expected.

We aim for the function to behave as numpy slicing and indexing as much as possible.

check_imaging_return_types(img_ex: ImagingExtractor)[source]#

Check that the return types of the imaging extractor are correct.

roiextractors.version module#

Get the version string for the named package.

param distribution_name:

The name of the distribution package to query.

return:

The version string for the package as defined in the package’s “Version” metadata key.

__dir__()#

Default dir() implementation.

__format__(format_spec, /)#

Default object formatter.

__init_subclass__()#

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__new__(*args, **kwargs)#

Create and return a new object. See help(type) for accurate signature.

__reduce__()#

Helper for pickle.

__reduce_ex__(protocol, /)#

Helper for pickle.

__sizeof__()#

Size of object in memory, in bytes.

__subclasshook__()#

Abstract classes can override this to customize issubclass().

This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).

Module contents#

Python-based module for extracting from, converting between, and handling recorded and optical imaging data from several file formats.