celltraj.trajectory

class celltraj.trajectory.Trajectory(h5filename=None, data_list=None)

Bases: object

A toolset for single-cell trajectory modeling. See:

References

Copperman, Jeremy, Sean M. Gross, Young Hwan Chang, Laura M. Heiser, and Daniel M. Zuckerman. “Morphodynamical cell state description via live-cell imaging trajectory embedding.” Communications Biology 6, no. 1 (2023): 484.

Copperman, Jeremy, Ian C. Mclean, Sean M. Gross, Young Hwan Chang, Daniel M. Zuckerman, and Laura M. Heiser. “Single-cell morphodynamical trajectories enable prediction of gene expression accompanying cell state change.” bioRxiv (2024): 2024-01.

__init__(h5filename=None, data_list=None)

Initializes a Trajectory object, optionally loading metadata and additional data from an HDF5 file.

This constructor sets the HDF5 filename and attempts to load metadata associated with the file. If the file is present, it reads the metadata from a predefined group. If data_list is provided, it will also attempt to load additional data specified in the list from the HDF5 file. Errors during metadata or data loading are caught and logged. Future updates should include better commenting and organizational improvements of class attributes.

Parameters:
  • h5filename (str, optional) – The path to the HDF5 file from which to load the metadata. If not provided, the instance will be initialized without loading metadata.

  • data_list (list of str, optional) – A list of data group paths within the HDF5 file to be loaded along with the metadata. Each entry in the list should specify a path to a dataset or group within the HDF5 file that contains data relevant to the trajectory analysis.

Notes

TODO: - Improve documentation of class attributes. - Reorganize attributes into a more meaningful structure.

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
loading path/to/your/hdf5file.h5

If an HDF5 file and data list are provided: >>> data_groups = [‘/group1/data’, ‘/group2/data’] >>> traj = Trajectory(‘path/to/your/hdf5file.h5’, data_list=data_groups) loading path/to/your/hdf5file.h5

load_from_h5(path)

Load data from a specified path within an HDF5 file. This method attempts to read records recursively from the given path in the HDF5 file specified by the h5filename attribute of the instance.

Parameters:

path (str) – The base path in the HDF5 file from which to load data.

Returns:

Returns True if the data was successfully loaded, False otherwise.

Return type:

bool

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> traj.load_from_h5('/data/group1')
loading path/to/your/hdf5file.h5
True
save_to_h5(path, attribute_list, overwrite=False)

Save specified attributes to an HDF5 file at the given path. This method saves attributes from the current instance to a specified location within the HDF5 file, creating or overwriting data as necessary based on the overwrite parameter.

Parameters:
  • path (str) – The base path in the HDF5 file where attributes will be saved.

  • attribute_list (list of str) – A list containing the names of attributes to save to the HDF5 file.

  • overwrite (bool, optional) – If True, existing data at the specified path will be overwritten. Default is False.

Returns:

Returns True if the attributes were successfully saved, False otherwise, such as when the HDF5 file does not exist or attributes cannot be written.

Return type:

bool

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> traj.some_attribute = np.array([1, 2, 3])
>>> traj.save_to_h5('/data/', ['some_attribute'])
saving attributes ['some_attribute'] to /data/ in path/to/your/hdf5file.h5
saved some_attribute to path/to/your/hdf5file.h5/data/
True
get_frames()

Scans an HDF5 file for image and mask datasets to determine the total number of frames, images per frame, and the total number of cells across all frames. This method updates the instance with attributes for the number of images, the maximum frame index, and the total cell count. It handles multiple mask channels by requiring the mskchannel attribute to be set if more than one mask channel exists.

Returns:

Returns True if the frames were successfully scanned and the relevant attributes set. Returns False if the HDF5 file is not set, no image data is found, or if there are multiple mask channels but mskchannel is not specified.

Return type:

bool

Raises:

AttributeError – If mskchannel needs to be specified but is not set when nmaskchannel is greater than zero.

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> success = traj.get_frames()
True
get_image_shape(n_frame=0)

Determine the dimensions of the image and mask data from the HDF5 file at a specified frame index and store these as attributes. This method retrieves the dimensions of both the image and mask datasets, discerning whether the data includes channels or z-stacks, and updates the object’s attributes accordingly. Attributes updated include the number of dimensions (ndim), image axes layout (axes), image dimensions (nx, ny, [nz]), number of channels in the image and mask (nchannels, nmaskchannels), and the full image shape (image_shape).

Parameters:

n_frame (int, optional) – The frame index from which to retrieve the image and mask dimensions. Default is 0.

Returns:

Returns True if the dimensions were successfully retrieved and stored as attributes, False otherwise, such as when the file is not found or an error occurs in reading data.

Return type:

bool

axes

The layout of axes in the image data, e.g., ‘xy’, ‘xyc’, ‘zxy’, ‘zxyc’.

Type:

str

nx

Width of the image in pixels.

Type:

int

ny

Height of the image in pixels.

Type:

int

nz

Number of z-stacks in the image, if applicable.

Type:

int, optional

image_shape

Array representing the dimensions of the image.

Type:

ndarray

nchannels

Number of channels in the image data.

Type:

int

nmaskchannels

Number of channels in the mask data.

Type:

int

ndim

Number of spatial dimensions in the image data.

Type:

int

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> success = traj.get_image_shape(1)
True
get_image_data(n_frame)

Retrieve the image data for a specified frame from the HDF5 file associated with this instance. This method accesses the HDF5 file, navigates to the specific dataset for the given frame, and extracts the image data.

Parameters:

n_frame (int) – The frame number from which to retrieve image data.

Returns:

img – The image data as a NumPy array. The shape and type of the array depend on the structure of the image data in the HDF5 file (e.g., may include dimensions for channels or z-stacks).

Return type:

ndarray

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> image_data = traj.get_image_data(5)
>>> image_data.shape
(1024, 1024, 3)  # Example shape, actual may vary.
get_mask_data(n_frame)

Retrieve the mask data for a specified frame from the HDF5 file associated with this instance. This method accesses the HDF5 file, navigates to the specific dataset for the given frame, and extracts the mask data.

Parameters:

n_frame (int) – The frame number from which to retrieve mask data.

Returns:

msk – The mask data as a NumPy array. The structure of the array will depend on the mask setup in the HDF5 file, such as whether it includes dimensions for multiple channels or z-stacks.

Return type:

ndarray

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> mask_data = traj.get_mask_data(5)
>>> mask_data.shape
(1024, 1024, 2)  # Example shape, actual may vary.
get_fmask_data(n_frame, channel=None)

Retrieve the foreground mask data for a specific frame using different methods depending on the set attributes. This method determines the foreground mask either by selecting a specific mask channel (fmskchannel), by applying a threshold to an image channel (fmsk_threshold and fmsk_imgchannel), or directly from specified channels in the HDF5 file (fmask_channels).

Parameters:
  • n_frame (int) – The frame number from which to retrieve the foreground mask data.

  • channel (int, optional) – The specific channel to use when fmask_channels attribute is set. If not provided, the default ‘foreground’ channel is used if available.

Returns:

  • fmsk (ndarray, bool) – The foreground (cells) / background mask array, indicating cell locations as True and background as False.

  • Methods for Determining `fmsk`

  • ------------------------------

  • 1. If `fmskchannel is set`

  • - The method uses the specified channel from the mask data (not fmask data).

  • 2. If `fmsk_threshold` and fmsk_imgchannel are set

  • - The method thresholds the image data at the specified channel using the given threshold.

  • 3. If `fmask_channels is set` and the channel parameter is provided or a default is available

  • - The method retrieves the mask from the specified or default channel in the `fmsk dataset.`

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> fmask_data = traj.get_fmask_data(5)
>>> fmask_data.shape
(1024, 1024)  # Example shape, actual may vary.
get_cell_blocks(label, return_label_ids=False)

Extracts bounding box information for each cell from a labeled mask image. This function returns the minimum and maximum indices for each labeled cell, useful for operations such as cropping around a cell or analyzing specific cell regions. The function supports both 2D and 3D labeled images.

Parameters:

label (ndarray) – A labeled image array where each unique non-zero integer represents a unique cell.

Returns:

cellblocks – An array containing the bounding boxes for each cell. The array has shape (number_of_labels, number_of_dimensions, 2), where each cell’s bounding box is represented by [min_dim1, min_dim2, …, max_dim1, max_dim2, …].

Return type:

ndarray

Examples

>>> label_image = np.array([[0, 0, 1, 1], [0, 2, 2, 1], [2, 2, 2, 0]])
>>> blocks = traj.get_cell_blocks(label_image)
>>> blocks.shape
(2, 2, 2)  # Example output shape for a 2D label image with two labels.
get_cell_index(verbose=False, save_h5=False, overwrite=False)

Computes indices and corresponding frame information for each cell in an image stack, capturing this data in several attributes. This method gathers extensive cell data across all frames, including frame indices, image file indices, individual image indices, and bounding boxes for each cell. This information is stored in corresponding attributes, facilitating further analysis or reference.

Parameters:
  • verbose (bool, optional) – If True, prints detailed logging of the processing for each frame. Default is False.

  • save_h5 (bool, optional) – If True, saves the computed data to an HDF5 file using the specified mskchannel. Default is False.

  • overwrite (bool, optional) – If True and save_h5 is True, existing data in the HDF5 file will be overwritten. Default is False.

Returns:

True if the computation and any specified data saving are successful, False if there is an error due to missing prerequisites or during saving.

Return type:

bool

cells_frameSet

Array storing the frame index for each cell, shape (ncells_total,).

Type:

ndarray

cells_imgfileSet

Array storing the image file index for each cell, shape (ncells_total,).

Type:

ndarray

cells_indSet

Array storing a unique index for each cell in the trajectory, shape (ncells_total,).

Type:

ndarray

cells_indimgSet

Array storing the image-specific index for each cell, shape (ncells_total,).

Type:

ndarray

cellblocks

Array of bounding boxes for each cell, shape (ncells_total, ndim, 2).

Type:

ndarray

Raises:

AttributeError – If necessary attributes (like nmaskchannels, ncells_total, mskchannel, maxFrame) are not set prior to invoking this method.

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> success = traj.get_cell_index(verbose=True, save_h5=True, overwrite=True)
True
get_cell_data(ic, frametype='boundingbox', boundary_expansion=None, return_masks=True, relabel_masks=True, relabel_mskchannels=None, delete_background=False)

Retrieves image and mask data for specific cells based on various configuration options. This method can extract data for single cells, their neighborhoods, or connected cell groups, and offers options to expand the extraction region, relabel masks, and more.

Parameters:
  • ic (int or list of int) – Cell ID(s) for which to retrieve data. Can specify a single cell or a list of cells.

  • frametype (str, optional) – Type of frame data to retrieve; options include ‘boundingbox’, ‘neighborhood’, or ‘connected’. Default is ‘boundingbox’.

  • boundary_expansion (ndarray or int, optional) – Array specifying how much to expand the bounding box around the cell in each dimension.

  • return_masks (bool, optional) – Whether to return the mask data along with the image data. Default is True.

  • relabel_masks (bool, optional) – Whether to relabel mask data with movie cell indices. Default is True.

  • relabel_mskchannels (array or list, optional) – Specifies the mask channels to relabel. If not set, uses the default mask channel.

  • delete_background (bool, optional) – If set to True, sets label and image pixels outside the specified cell set to zero. Default is False.

Returns:

  • imgc (ndarray) – The image data for the specified cell(s) as a NumPy array.

  • mskc (ndarray, optional) – The mask data for the specified cell(s) as a NumPy array, returned if return_masks is True.

Raises:

ValueError – If cells from multiple frames are requested or necessary attributes are not set.

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> img_data, mask_data = traj.get_cell_data(5, frametype='boundingbox', boundary_expansion=5, return_masks=True)
get_cell_features(function_tuple, indcells=None, imgchannel=0, mskchannel=0, use_fmask_for_intensity_image=False, fmskchannel=None, use_mask_for_intensity_image=False, bordersize=10, apply_contact_transform=False, preprocess_functions=None, return_feature_list=False, save_h5=False, overwrite=False, concatenate_features=False)

Extracts complex cell features based on the specified custom functions and imaging data. This method allows customization of the feature extraction process using region properties from segmented cell data, with optional transformations like border erosion or contact transformations. Features can be based on intensity images, mask data, or specific transformations of these data.

Parameters:
  • function_tuple (callable or tuple of callables) – Function(s) that take a mask and an intensity image as input and return a scalar or array of features. These functions must be compatible with skimage’s regionprops.

  • indcells (ndarray of int, optional) – Array of cell indices for which to calculate features. If None, calculates for all cells.

  • imgchannel (int, optional) – Index of the image channel used for intensity image feature calculation.

  • mskchannel (int, optional) – Index of the mask channel used for single-cell label feature calculation.

  • use_fmask_for_intensity_image (bool, optional) – If True, uses foreground mask data for intensity images.

  • fmskchannel (int, optional) – Channel index for foreground mask data if used for intensity image.

  • use_mask_for_intensity_image (bool, optional) – If True, uses mask data instead of image data for intensity measurements.

  • bordersize (int, optional) – Pixel size for erosion of the foreground mask or growth radius for contact boundaries.

  • apply_contact_transform (bool, optional) – If True, applies a contact transform to generate segmentation contacts from the mask data.

  • return_feature_list (bool, optional) – If True, returns a list of strings describing the calculated features.

  • save_h5 (bool, optional) – If True, saves the features and their descriptions to an HDF5 file.

  • overwrite (bool, optional) – If True and save_h5 is also True, overwrites existing data in the HDF5 file.

  • concatenate_features (bool, optional) – If True, adds the newly calculated features to existing features in the dataset.

Returns:

  • Xf (ndarray) – Array of features indexed by cells. The shape is (number of cells, number of features).

  • feature_list (ndarray of str, optional) – Array of strings describing each feature, returned if return_feature_list is True.

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> features, feature_descriptions = traj.get_cell_features(my_feature_funcs, return_feature_list=True)
get_cell_compartment_ratio(indcells=None, imgchannel=None, mskchannel1=None, mskchannel2=None, fmask_channel=None, make_disjoint=True, remove_background_perframe=False, fmask_channel_background=0, background_percentile=1, erosion_footprint1=None, erosion_footprint2=None, combined_and_disjoint=False, intensity_sum=False, intensity_ztransform=False, noratio=False, inverse_ratio=False, save_h5=False, overwrite=False)

Calculates the ratio of features between two cellular compartments, optionally adjusted for image intensity and morphology transformations. This method allows for complex comparisons between different mask channels or modified versions of these channels to derive cellular compartment ratios.

Parameters:
  • indcells (ndarray of int, optional) – Indices of cells for which to calculate the feature ratios.

  • imgchannel (int, optional) – Index of the image channel used for intensity measurements.

  • mskchannel1 (int, optional) – Mask channel index for the numerator in the ratio calculation.

  • mskchannel2 (int, optional) – Mask channel index for the denominator in the ratio calculation. Overlaps with mskchannel1 are removed.

  • fmask_channel (int, optional) – Mask channel index used to adjust mskchannel2 if no separate mskchannel2 is provided.

  • make_disjoint (bool, optional) – If True, ensures that masks from mskchannel1 and mskchannel2 do not overlap by adjusting mskchannel1.

  • erosion_footprint1 (ndarray, optional) – Erosion footprint for the first mask, modifies the mask by eroding it before calculations.

  • erosion_footprint2 (ndarray, optional) – Erosion footprint for the second mask, modifies the mask by eroding it before calculations.

  • combined_and_disjoint (bool, optional) – If True, combines and then separates the masks to only include disjoint areas in calculations.

  • intensity_sum (bool, optional) – If True, sums the intensity over the area rather than averaging it, before ratio calculation.

  • intensity_ztransform (bool, optional) – If True, applies a z-transformation based on standard deviations and means stored in the object.

  • noratio (bool, optional) – If True, returns only the numerator intensity mean without forming a ratio.

  • inverse_ratio (bool, optional) – If True, calculates the inverse of the normal ratio.

  • save_h5 (bool, optional) – If True, saves the calculated ratios to an HDF5 file.

  • overwrite (bool, optional) – If True and save_h5 is also True, overwrites existing data in the HDF5 file.

Returns:

  • cratio (ndarray) – Array of calculated compartment ratios for each specified cell.

  • feature_list (ndarray of str, optional) – Descriptions of the cell features, returned if return_feature_list is set to True.

Examples

>>> cratio = traj.get_cell_compartment_ratio(indcells=[1,2,3], imgchannel=0, mskchannel1=1, mskchannel2=2)
get_cell_channel_crosscorr(indcells=None, mskchannel=None, imgchannel1=None, imgchannel2=None, save_h5=False, overwrite=False)

Computes the cross-correlation between two image channels within labeled cells, using masks defined by a specific mask channel. This method is particularly useful for analyzing the relationship between different signal channels at a cellular level.

Parameters:
  • indcells (ndarray of int, optional) – Indices of cells for which to calculate cross-correlations. If None, calculations are performed for all indexed cells.

  • mskchannel (int) – Mask channel used to define cellular regions.

  • imgchannel1 (int) – First image channel for correlation analysis.

  • imgchannel2 (int) – Second image channel for correlation analysis.

  • save_h5 (bool, optional) – If True, saves the calculated cross-correlations to an HDF5 file under the specified directory and file names.

  • overwrite (bool, optional) – If True and save_h5 is True, existing data in the HDF5 file will be overwritten.

Returns:

corrc – Array of cross-correlation coefficients for each cell. The length of the array corresponds to the number of cells specified by indcells.

Return type:

ndarray

Raises:

ValueError – If required parameters are not set or if no cell index is available, prompting the user to set necessary parameters or perform required prior steps.

Examples

>>> corrc = traj.get_cell_channel_crosscorr(indcells=[1,2,3], mskchannel=0, imgchannel1=1, imgchannel2=2)
get_motility_features(indcells=None, mskchannel=None, radius=None, save_h5=False, overwrite=False)

Extracts motility features for individual cells and their neighbors. This method calculates both single-cell and neighbor-averaged motility characteristics, such as displacement and interaction with neighboring cells, based on tracking data and cell label information.

Parameters:
  • indcells (ndarray of int, optional) – Indices of cells for which to calculate motility features. If None, features are calculated for all cells in the dataset.

  • mskchannel (int) – Mask channel used to define cell labels.

  • radius (int, optional) – Size of morphological expansion in pixels to find neighboring cells.

  • save_h5 (bool, optional) – If True, saves the calculated motility features to an HDF5 file specified in the trajectory object.

  • overwrite (bool, optional) – If True and save_h5 is True, overwrites existing data in the HDF5 file.

Returns:

  • Xf_com (ndarray) – An array of computed motility features for each specified cell. The array dimensions are (number of cells, number of features).

  • feature_list (ndarray of str, optional) – Descriptions of each motility feature computed. This is returned if return_feature_list is set to True in the method call.

Raises:

ValueError – If required data such as mask channels or cell indices are not set, or if cell tracking has not been performed prior to feature extraction.

Examples

>>> motility_features = traj.get_motility_features(indcells=[1, 2, 3], mskchannel=0)
get_stack_trans(mskchannel=0, ntrans=20, maxt=10, dist_function=<function get_pairwise_distance_sum>, zscale=None, save_h5=False, overwrite=False, do_global=False, **dist_function_keys)

Computes translations across an image stack using a brute force optimization method to align cell centers from frame to frame. This method can apply both local and global alignment strategies based on the distribution of cell centers.

Parameters:
  • mskchannel (int) – Mask channel to use for extracting cell centers from labels.

  • ntrans (int or ndarray) – Number of translations to try in each dimension during optimization.

  • maxt (float or ndarray) – Maximum translation distance to consider in each dimension.

  • dist_function (function) – Optimization function that takes cell centers from two frames and a translation vector, returning a score where lower values indicate better alignment.

  • zscale (float, optional) – Scaling factor for the z-dimension to normalize it with x and y dimensions.

  • save_h5 (bool, optional) – If True, saves the computed transformation matrices to an HDF5 file.

  • overwrite (bool, optional) – If True and save_h5 is True, overwrites existing data in the HDF5 file.

  • do_global (bool, optional) – If True, performs a global alignment using the center of mass of all masks prior to brute force optimization.

  • dist_function_keys (dict) – Additional keyword arguments to pass to the dist_function.

Returns:

tf_matrix_set – An array of shape (nframes, ndim+1, ndim+1) containing the transformation matrices for aligning each frame to the first frame based on the computed translations.

Return type:

ndarray

Examples

>>> transformations = traj.get_stack_trans(mskchannel=1, ntrans=10, maxt=5, do_global=False)
get_cell_positions(mskchannel=0, save_h5=False, overwrite=False)

Calculate the center of mass for cells in each frame of the mask channel and optionally save these positions to an HDF5 file. This method processes mask data to find cell positions across frames and can store these positions back into the HDF5 file associated with the Trajectory instance.

Parameters:
  • mskchannel (int, optional) – The index of the mask channel from which to calculate cell positions. Default is 0.

  • save_h5 (bool, optional) – If True, the calculated cell positions will be saved to the HDF5 file specified by h5filename. Default is False.

  • overwrite (bool, optional) – If True and save_h5 is also True, existing data in the HDF5 file will be overwritten. Default is False.

Returns:

An array of cell positions calculated from the mask channel. The shape of the array is (number of cells, number of dimensions).

Return type:

ndarray

Raises:

RuntimeError – If the stack has not been transformed, indicated by tf_matrix_set not being set.

Examples

>>> traj = Trajectory('path/to/your/hdf5file.h5')
>>> traj.get_stack_trans()  # Ensure transformation matrix is set
>>> positions = traj.get_cell_positions(mskchannel=1, save_h5=True, overwrite=True)
getting positions from mask channel 1, default mskchannel is 0
loading cells from frame 0
loading cells from frame 1
...
get_lineage_min_otcost(distcut=5.0, ot_cost_cut=numpy.inf, border_scale=None, border_resolution=None, return_cost=False, visual=False, save_h5=False, overwrite=False)

Tracks cell lineages over multiple time points using optimal transport cost minimization.

This method uses centroid distances and optimal transport costs to identify the best matches for cell trajectories between consecutive time points, ensuring accurate tracking even in dense or complex environments.

Parameters:
  • distcut (float, optional) – Maximum distance between cell centroids to consider a match (default is 5.0).

  • ot_cost_cut (float, optional) – Maximum optimal transport cost allowed for a match (default is np.inf).

  • border_scale (list of float, optional) – Scaling factors for the cell border in the [z, y, x] dimensions. If not provided, the scaling is determined from self.micron_per_pixel and border_resolution.

  • border_resolution (float, optional) – Resolution for the cell border, used to determine border_scale if it is not provided. If not set, uses self.border_resolution.

  • visual (bool, optional) – If True, plots the cells and their matches at each time point for visualization (default is False).

  • save_h5 (bool, optional) – If True, saves the lineage data to the HDF5 file (default is False).

  • overwrite (bool, optional) – If True, overwrites existing data in the HDF5 file when saving (default is False).

Returns:

The function updates the instance’s linSet attribute, which is a list of arrays containing lineage information for each time point. If save_h5 is True, the lineage data is saved to the HDF5 file.

Return type:

None

Notes

  • This function assumes that cell positions have already been extracted using the get_cell_positions method.

  • The function uses the spatial.get_border_dict method to compute cell borders and spatial.get_ot_dx

to compute optimal transport distances. - Visualization is available for 2D and 3D data, with different handling for each case.

Examples

>>> traj.get_lineage_min_otcost(distcut=10.0, ot_cost_cut=50.0, visual=True)
Frame 1 tracked 20 of 25 cells
Frame 2 tracked 22 of 30 cells
...
get_lineage_btrack(mskchannel=0, distcut=5.0, framewindow=6, visual_1cell=False, visual=False, max_search_radius=100, save_h5=False, overwrite=False)

Tracks cell lineages over an image stack using Bayesian tracking with visual confirmation options. This method registers transformed masks and applies Bayesian tracking to link cell identities across frames, storing the lineage information. Use of btrack software requires a cell_config.json file stored in the directory, see btrack documentation.

Parameters:
  • mskchannel (int) – Mask channel used to identify cell labels from which cell centers are extracted.

  • distcut (float) – Maximum distance between cell centers in consecutive frames for cells to be considered the same.

  • framewindow (int) – Number of frames over which to look for cell correspondences.

  • visual_1cell (bool) – If True, displays visual tracking information for single cell matches during processing.

  • visual (bool) – If True, displays visual tracking information for all cells during processing.

  • max_search_radius (int) – The maximum search radius in pixels for linking objects between frames.

  • save_h5 (bool) – If True, saves the lineage data (linSet) to an HDF5 file.

  • overwrite (bool) – If True and save_h5 is True, overwrites existing data in the HDF5 file.

Returns:

linSet – A list of arrays where each array corresponds to a frame and contains indices that map each cell to its predecessor in the previous frame. Cells with no predecessor are marked with -1. The data saved in linSet thus represents the lineage of each cell over the stack.

Return type:

list of ndarray

Raises:

AttributeError – If tf_matrix_set is not set, indicating that stack transformation matrices are required for tracking but have not been calculated.

Examples

>>> lineage_data = traj.get_lineage_btrack(mskchannel=1, visual=True)
get_lineage_mindist(distcut=5.0, visual=False, save_h5=False, overwrite=False)

Tracks cell lineage based on the minimum distance between cells across consecutive frames. This method assesses cell positions to establish lineage by identifying the nearest cell in the subsequent frame within a specified distance threshold.

Parameters:
  • distcut (float, optional) – The maximum distance a cell can move between frames to be considered the same cell. Cells moving a distance greater than this threshold will not be tracked from one frame to the next.

  • visual (bool, optional) – If True, displays a visual representation of the tracking process for each frame, showing the cells and their movements between frames.

  • save_h5 (bool, optional) – If True, saves the lineage data (linSet) to an HDF5 file.

  • overwrite (bool, optional) – If True and save_h5 is True, overwrites existing data in the HDF5 file.

Returns:

linSet – A list where each entry corresponds to a frame and contains cell indices that map each cell to its predecessor in the previous frame. Cells with no identifiable predecessor are marked with -1. This list provides a complete lineage map of cells across all analyzed frames.

Return type:

list of ndarray

Raises:

AttributeError – If the cell positions (x) are not calculated prior to running this method, indicating that get_cell_positions needs to be executed first.

Examples

>>> traj = Trajectory('path/to/your/data.h5')
>>> lineage_data = traj.get_lineage_mindist(distcut=10, visual=True)
get_cell_trajectory(cell_ind, n_hist=-1)

Retrieves the trajectory of a specified cell across previous frames, tracing back from the current frame to the point of its first appearance or until a specified number of history steps.

Parameters:
  • cell_ind (int) – The index of the cell for which to retrieve the trajectory.

  • n_hist (int, optional) – The number of historical steps to trace back. If set to -1 (default), the function traces back to the earliest frame in which the cell appears.

Returns:

cell_traj – An array of cell indices representing the trajectory of the specified cell across the tracked frames. The array is ordered from the earliest appearance to the current frame.

Return type:

ndarray

Raises:
  • IndexError – If the cell index provided is out of the bounds of the available data.

  • ValueError – If the provided cell index does not correspond to any tracked cell, possibly due to errors in lineage tracking.

Examples

>>> cell_trajectory = traj.get_cell_trajectory(10)
>>> print(cell_trajectory)
[23, 45, 67, 89]  # Example output, actual values depend on cell tracking results.

Notes

The trajectory is computed by accessing the lineage data (linSet), which must be computed beforehand via methods such as get_lineage_btrack. Each index in the resulting trajectory corresponds to a position in previous frames where the cell was identified, stepping backwards until the cell’s first detection or the limit of specified history steps.

get_unique_trajectories(cell_inds=None, verbose=False, extra_depth=None, save_h5=False, overwrite=False)

Computes unique trajectories for a set of cells over multiple frames, minimizing redundancy by ensuring that no two trajectories cover the same cell path beyond a specified overlap (extra_depth).

Parameters:
  • cell_inds (array of int, optional) – Array of cell indices for which to calculate trajectories. If None, calculates trajectories for all cells.

  • verbose (bool, optional) – If True, provides detailed logs during the trajectory calculation process.

  • extra_depth (int, optional) – Specifies how many frames of overlap to allow between different trajectories. If not set, uses the pre-set attribute ‘trajl’ minus one as the depth; if ‘trajl’ is not set, defaults to 0.

Notes

  • This method identifies unique trajectories by tracking each cell backward from its last appearance

to its first, recording the trajectory, and then ensuring subsequent trajectories do not retread the same path beyond the allowed overlap specified by ‘extra_depth’. - Each trajectory is tracked until it either reaches the start of the dataset or an earlier part of another trajectory within the allowed overlap. - This function updates the instance’s ‘trajectories’ attribute, storing each unique trajectory.

Examples

>>> traj.get_unique_trajectories(verbose=True)
get_traj_segments(seg_length)

Divides each trajectory into multiple overlapping segments of a specified length. This method is useful for analyzing sections of trajectories or for preparing data for machine learning models that require fixed-size input.

Parameters:

seg_length (int) – The length of each segment to be extracted from the trajectories. Segments are created by sliding a window of this length along each trajectory.

Returns:

traj_segSet – A 2D array where each row represents a segment of a trajectory. The number of columns in this array equals seg_length. Each segment includes consecutive cell indices from the original trajectories.

Return type:

ndarray

Notes

  • This method requires that the trajectories attribute has been populated, typically by

a method that computes full trajectories such as get_unique_trajectories. - Only trajectories that are at least as long as seg_length will contribute segments to the output. Shorter trajectories are ignored.

Examples

>>> traj = Trajectory('path/to/data.h5')
>>> traj.get_unique_trajectories()
>>> segments = traj.get_traj_segments(5)
>>> print(segments.shape)
(number of segments, 5)  # Example shape, actual values depend on trajectory lengths and seg_length.
Raises:

ValueError – If seg_length is larger than the length of any available trajectory, resulting in no valid segments being produced.

get_cell_children(icell)

Get the child cells for a given cell in the next frame.

This function identifies the child cells of a given parent cell icell by tracking the lineage data across consecutive frames. The lineage is determined from the parent cell’s index and the lineage set for the next frame.

Parameters:

icell (int) – The index of the cell for which to find the children.

Returns:

ind_children – An array of indices representing the child cells of the given cell icell in the next frame.

Return type:

ndarray

Notes

  • The function looks at the current frame of icell and identifies its child cells in the subsequent frame

using the lineage tracking set (linSet). - This method assumes that the lineage set (linSet) and cell indexing (cells_indimgSet, cells_indSet) are properly initialized and populated.

Examples

>>> cell_index = 10
>>> children = model.get_cell_children(cell_index)
>>> print(f'Children of cell {cell_index}: {children}')
get_cell_parents(icell)

Get the child cells for a given cell in the next frame.

This function identifies the parent cells of a given child cell icell by tracking the lineage data across consecutive frames. The lineage is determined from the parent cell’s index and the lineage set for the previous frame.

Parameters:

icell (int) – The index of the cell for which to find the children.

Returns:

ind_children – An array of indices representing the child cells of the given cell icell in the next frame.

Return type:

ndarray

Notes

  • The function looks at the current frame of icell and identifies its child cells in the subsequent frame

using the lineage tracking set (linSet). - This method assumes that the lineage set (linSet) and cell indexing (cells_indimgSet, cells_indSet) are properly initialized and populated.

Examples

>>> cell_index = 10
>>> children = model.get_cell_children(cell_index)
>>> print(f'Children of cell {cell_index}: {children}')
get_cells_nchildren()

Compute the number of children for each cell across all frames.

This function calculates the number of child cells each parent cell has across consecutive time frames. The result is an array where each element corresponds to the number of child cells for a given parent cell in the next frame. Cells with no children will have a count of 0.

Returns:

cells_nchildren – An array where each element represents the number of child cells for each cell in the dataset. The indices correspond to the cell indices in self.cells_indSet.

Return type:

ndarray

Notes

  • The function iterates through all time frames (nt) to determine the lineage of each cell

using the linSet attribute, which holds the lineage information between frames. - Cells that are not tracked between frames (i.e., not assigned a child in the next frame) will have a count of 0 children. - The method assumes that linSet, cells_indSet, and cells_indimgSet are properly initialized and populated.

Examples

>>> cell_children_counts = model.get_cells_nchildren()
>>> print(f'Number of children for each cell: {cell_children_counts}')
get_cell_sandwich(ic, msk_channel=0, boundary_expansion=None, trajl_past=1, trajl_future=1)

Extracts a sequence of image and mask “sandwiches” for a given cell, including past and future frames.

This function creates a set of 2D or 3D image and mask stacks for a specified cell, tracking the cell across multiple frames into the past and future. It includes boundary expansion around the cell if specified and gathers the images and masks for the cell trajectory. The function is useful for analyzing the temporal behavior of a cell within its local neighborhood.

Parameters:
  • ic (int) – Index of the target cell.

  • msk_channel (int, optional) – Channel of the mask image where the cell is identified (default is 0).

  • boundary_expansion (int or None, optional) – Number of pixels to expand the boundary around the cell block (default is None, no expansion).

  • trajl_past (int, optional) – Number of past frames to include in the sandwich (default is 1).

  • trajl_future (int, optional) – Number of future frames to include in the sandwich (default is 1).

Returns:

  • imgs (list of ndarray) – A list of image stacks (2D or 3D) for each frame in the trajectory sandwich.

  • msks (list of ndarray) – A list of binary masks corresponding to the same frames in imgs, where the cell and its descendants are highlighted.

Notes

  • The function retrieves the cell trajectory from the current frame, including both past and future cells,

as well as their children in future frames. - The images and masks are collected and returned in two separate lists, with the past, present, and future frames in sequential order. - The function supports both 2D and 3D image data based on the dimensions of the input data.

Examples

>>> imgs, msks = model.get_cell_sandwich(ic=42, boundary_expansion=10, trajl_past=2, trajl_future=2)
>>> print(f'Retrieved {len(imgs)} images and masks for cell 42 across past and future frames.')
get_Xtraj_celltrajectory(cell_traj, Xtraj=None, traj=None)

Retrieves trajectory segments for a specific cell trajectory from a larger set of trajectory data. This method matches segments of the cell trajectory with those in a pre-computed set of trajectories and extracts the corresponding features or data points.

Parameters:
  • cell_traj (ndarray) – An array containing indices of a cell’s trajectory over time.

  • Xtraj (ndarray, optional) – The trajectory feature matrix from which to extract data. If not provided, the method uses the instance’s attribute Xtraj.

  • traj (ndarray, optional) – A matrix of precomputed trajectories used for matching against cell_traj. If not provided, the method uses the instance’s attribute traj.

Returns:

  • xt (ndarray) – A subset of Xtraj corresponding to the segments of cell_traj that match segments in traj.

  • inds_traj (ndarray) – Indices within traj where matches were found, indicating which rows in Xtraj were selected.

Raises:

ValueError – If the length of cell_traj is less than the length used for trajectories in traj (trajl), making it impossible to match any trajectory segments.

Examples

>>> traj.get_unique_trajectories()
>>> cell_trajectory = traj.get_cell_trajectory(10)
>>> features, indices = traj.get_Xtraj_celltrajectory(cell_trajectory)

Notes

  • The method requires trajl, the length of the trajectory segments, to be set either as a class

attribute or passed explicitly. This length determines how the segments are compared for matching. - This function is particularly useful for analyzing time-series data or features extracted from trajectories, allowing for detailed analysis specific to a single cell’s path through time.

get_trajectory_steps(inds=None, traj=None, Xtraj=None, get_trajectories=True, nlag=1)

Extracts sequential steps from cell trajectories and retrieves corresponding features from a feature matrix. This method is useful for analyses that require step-wise comparison of trajectories, such as calculating changes or transitions over time.

Parameters:
  • inds (array of int, optional) – Indices of cells for which to get trajectory steps. If None, processes all cells.

  • traj (ndarray, optional) – The trajectory data matrix. If None, uses the instance’s traj attribute.

  • Xtraj (ndarray, optional) – The feature data matrix corresponding to trajectories. If None, uses the instance’s Xtraj attribute.

  • get_trajectories (bool, optional) – If True, computes unique trajectories for the specified indices before processing steps.

  • nlag (int, optional) – The lag between steps in a trajectory to consider. A value of 1 means consecutive steps.

Notes

  • The method assumes that the trajectory and feature data matrices (traj and Xtraj, respectively)

are indexed in the same way. - This function can optionally calculate unique trajectories before extracting steps, making it versatile for both freshly calculated and pre-computed trajectory datasets.

Examples

>>> traj = Trajectory('path/to/data.h5')
>>> traj.get_trajectory_steps(get_trajectories=True, nlag=2)
# This will compute unique trajectories for all cells and then extract every second step.
Raises:
  • IndexError – If any index in inds is out of bounds of the available data.

  • ValueError – If traj or Xtraj data matrices are not set and not provided as arguments.

get_trajAB_segments(xt, stateA=None, stateB=None, clusters=None, states=None, distcutA=None, distcutB=None)

Identifies segments within trajectories that transition between specified states, A and B. This method can be used to analyze transitions or dwell times in specific states within a trajectory dataset.

Parameters:
  • xt (ndarray) – An array representing trajectories, either as direct state assignments or continuous data.

  • stateA (int or array-like, optional) – The state or states considered as ‘A’. Transitions from this state are analyzed.

  • stateB (int or array-like, optional) – The state or states considered as ‘B’. If defined, transitions from state A to state B are analyzed.

  • clusters (object, optional) – A clustering object with an ‘assign’ method that can be used to discretize continuous trajectory data into states.

  • states (ndarray, optional) – An array defining all possible states. Used to map states in ‘xt’ if it contains direct state assignments.

  • distcutA (float, optional) – The distance cutoff for determining membership in state A if ‘xt’ is continuous.

  • distcutB (float, optional) – The distance cutoff for determining membership in state B if ‘xt’ is continuous and ‘stateB’ is defined.

Returns:

slices – A list of slice objects representing the indices of ‘xt’ where transitions between specified states occur. If only ‘stateA’ is specified, returns segments where the trajectory is in state A.

Return type:

list of slice

Raises:

ValueError – If required parameters for defining states or transitions are not provided or if the provided parameters are incompatible (e.g., ‘distcutA’ without a corresponding ‘stateA’).

Examples

>>> traj = Trajectory('path/to/data.h5')
>>> xt = np.random.rand(100, 2)  # Example continuous trajectory data
>>> clusters = KMeans(n_clusters=3).fit(xt)  # Example clustering model
>>> segments = traj.get_trajAB_segments(xt, stateA=0, stateB=1, clusters=clusters)
# Analyze transitions from state 0 to state 1 using cluster assignments

Notes

  • If ‘xt’ contains direct state assignments, ‘states’ must be provided to map these to actual state values.

  • For continuous data, ‘clusters’ or distance cutoffs (‘distcutA’, ‘distcutB’) must be used to define states.

  • This function is useful for analyzing kinetic data where transitions between states are of interest.

get_pair_rdf(cell_indsA=None, cell_indsB=None, rbins=None, nr=50, rmax=500)

Calculates the radial distribution function (RDF) between two sets of cells, identifying the frequency of cell-cell distances within specified radial bins. This method is commonly used in statistical physics and materials science to study the spatial distribution of particles.

Parameters:
  • cell_indsA (array of int, optional) – Indices of the first set of cells. If None, considers all cells.

  • cell_indsB (array of int, optional) – Indices of the second set of cells. If None, uses the same indices as cell_indsA.

  • rbins (ndarray, optional) – Array of radial bins for calculating RDF. If None, bins are generated linearly from nearly 0 to rmax.

  • nr (int, optional) – Number of radial bins if rbins is not specified. Default is 50.

  • rmax (float, optional) – Maximum radius for the radial bins if rbins is not specified. Default is 500 units.

Returns:

  • rbins (ndarray) – The radial bins used for the RDF calculation, adjusted to remove the zero point and ensure proper binning.

  • paircorrx (ndarray) – RDF values corresponding to each radial bin, normalized to the total number of pairs and the bin volumes.

Examples

>>> traj = Trajectory('path/to/data.h5')
>>> rbins, rdf = traj.get_pair_rdf(cell_indsA=[1, 2, 3], cell_indsB=[4, 5, 6], nr=100, rmax=200)
# This will calculate the RDF between two specified sets of cells with 100 radial bins up to a maximum radius of 200.

Notes

  • The RDF gives a normalized measure of how often pairs of points (cells) appear at certain distances from each other,

compared to what would be expected for a completely random distribution at the same density. - This function is useful for examining the spatial organization and clustering behavior of cells in tissues or cultures.

get_alpha(i1, i2)

Calculates the alignment measure, alpha, between two cells identified by their indices. This measure reflects how the movement direction of one cell relates to the direction of the vector connecting the two cells, essentially quantifying the relative motion along the axis of separation.

Parameters:
  • i1 (int) – Index of the first cell.

  • i2 (int) – Index of the second cell.

Returns:

alpha – The alignment measure between the two cells. This value ranges from -1 to 1, where 1 indicates that the cells are moving directly towards each other, -1 indicates they are moving directly away from each other, and 0 indicates orthogonal movement directions. Returns NaN if the calculation fails (e.g., due to division by zero when normalizing zero-length vectors).

Return type:

float

Raises:

Exception – If an error occurs during the trajectory retrieval or normalization process, likely due to missing data or incorrect indices.

Examples

>>> traj = Trajectory('path/to/data.h5')
>>> alignment = traj.get_alpha(10, 15)
# This computes the alignment measure between cells at index 10 and 15 based on their last movements.

Notes

  • The function computes the movement vectors of both cells from their previous positions in their

respective trajectories and uses these vectors to determine their alignment relative to the vector connecting the two cells at their current positions.

get_beta(i1, i2)

Calculates the cosine of the angle (beta) between the movement directions of two cells. This measure quantifies the directional similarity or alignment between two moving cells, with values ranging from -1 to 1.

Parameters:
  • i1 (int) – Index of the first cell.

  • i2 (int) – Index of the second cell.

Returns:

beta – The cosine of the angle between the movement vectors of the two cells, indicating their directional alignment. A value of 1 means the cells are moving in exactly the same direction, -1 means they are moving in exactly opposite directions, and 0 indicates orthogonal movement directions. Returns NaN if the calculation fails, typically due to a division by zero when attempting to normalize zero-length vectors.

Return type:

float

Raises:

Exception – If an error occurs during the trajectory retrieval or normalization process, likely due to missing data or incorrect indices.

Examples

>>> alignment = traj.get_beta(10, 15)
# This computes the directional alignment between cells at index 10 and 15 based on their last movements.

Notes

  • The function calculates movement vectors for both cells from their positions at the last two time points

in their trajectories. It then computes the cosine of the angle between these vectors as the beta value, providing an indication of how parallel their movements are.

get_dx(i1)

Calculates the displacement vector of a cell between its current position and its previous position in the trajectory. This vector represents the movement of the cell between two consecutive time points.

Parameters:

i1 (int) – Index of the cell for which to calculate the displacement.

Returns:

dx1 – A vector representing the displacement of the cell. The vector is given in the coordinate space of the cell positions. If the calculation fails (e.g., due to missing data), returns a vector of NaNs.

Return type:

ndarray

Raises:

Exception – If an error occurs during the trajectory retrieval or calculation, typically due to missing data or incorrect indices.

Examples

>>> displacement = traj.get_dx(10)
# This calculates the displacement vector for the cell at index 10 between its current and previous positions.

Notes

  • The method attempts to retrieve the last position from the cell’s trajectory using get_cell_trajectory.

If the cell’s trajectory does not have a previous position or the data is missing, the displacement vector will contain NaN values to indicate the failure of the calculation.

get_secreted_ligand_density(frame, mskchannel=0, scale=2.0, npad=None, indz_bm=0, secretion_rate=1.0, D=None, flipz=False, visual=False)

Simulates the diffusion of secreted ligands from cells, providing a spatial distribution of ligand density across a specified frame. The simulation considers specified boundary conditions and secretion rates to model the ligand concentration in the vicinity of cells.

Parameters:
  • frame (int) – The frame index from which image and mask data are extracted.

  • mskchannel (int, optional) – The channel of the mask that identifies the cells.

  • scale (float, optional) – The scaling factor for the resolution of the simulation. Default is 2.0.

  • npad (array-like, optional) – Padding to add around the simulation area to avoid edge effects. Defaults to [0, 0, 0] if None.

  • indz_bm (int, optional) – The index of the bottom-most slice to consider in the z-dimension.

  • secretion_rate (float or array-like, optional) – The rate at which ligands are secreted by the cells. Can be a single value or an array specifying different rates for different cells.

  • D (float, optional) – Diffusion coefficient. If not specified, it is calculated based on the pixel size and z-scaling.

  • flipz (bool, optional) – If True, flips the z-dimension of the image and mask data, useful for certain imaging orientations.

  • visual (bool, optional) – If True, displays visualizations of the simulation process and results.

Returns:

vdist – A 3D array representing the volumetric distribution of the ligand density around cells in the specified frame.

Return type:

ndarray

Examples

>>> traj = Trajectory('path/to/data.h5')
>>> ligand_density = traj.get_secreted_ligand_density(frame=10, mskchannel=1, scale=1.5, secretion_rate=0.5, D=15)
# This will simulate and return the ligand density around cells in frame 10 with specified parameters.
Raises:

ValueError – If any of the provided indices or parameters are out of the expected range or if there is a mismatch in array dimensions.

Notes

  • The method performs a complex series of image processing steps including scaling, padding, flipping, and 3D mesh generation.

  • It uses finite element methods to solve diffusion equations over the generated mesh, constrained by the cellular boundaries and secretion rates.

get_signal_contributions(S, time_lag=0, x_pos=None, rmax=5.0, R=None, zscale=None, rescale_z=False)

Computes the spatial contributions of signaling between cells over a specified time lag. This method averages signals from nearby cells, weighted inversely by their distances, to assess local signaling interactions.

Parameters:
  • S (ndarray) – A binary array indicating the signaling status of cells (1 for active, 0 for inactive).

  • time_lag (int, optional) – The time lag over which to assess signal contributions, defaulting to 0 for immediate interactions.

  • x_pos (ndarray, optional) – Positions of cells. If None, the positions are taken from the instance’s x attribute.

  • rmax (float, optional) – The maximum radius within which to consider signal contributions from neighboring cells, default is 5.

  • R (float, optional) – Normalization radius, typically set to the average cell diameter; defaults to the instance’s cellpose_diam.

  • zscale (float, optional) – The scaling factor for the z-dimension, used if rescale_z is True.

  • rescale_z (bool, optional) – If True, scales the z-coordinates of positions by zscale.

Returns:

S_r – An array where each element is the averaged spatial signal contribution received by each cell, normalized by distance and weighted by the signaling status of neighboring cells.

Return type:

ndarray

Examples

>>> traj = Trajectory('path/to/data.h5')
>>> S = np.random.randint(0, 2, size=traj.cells_indSet.size)
>>> signal_contributions = traj.get_signal_contributions(S, time_lag=1, rmax=10, R=15)
# This computes the signal contributions for each cell, considering interactions within a radius of 10 units.

Notes

  • This method is useful for understanding the influence of cell-cell interactions within a defined spatial range

and can be particularly insightful in dynamic cellular environments where signaling is a key factor. - The distances are normalized by the cell radius R to provide a relative measure of proximity, and the contributions are weighted by the inverse of these normalized distances.

Raises:

ValueError – If necessary parameters are missing or incorrectly formatted.

manual_fate_validation(indcells, fate_attr, trajl_future=2, trajl_past=2, stride=1, restart=False, val_tracks=False, rep_channel=2, bf_channel=0, nuc_channel=1, show_nuc=True, msk_channel=0, projection=False, nuclow=98, nuchigh=100, show_allcells=True, show_linked=True, pathto='./', save_pic=False, boundary_expansion=[1, 40, 40], save_attr=True, save_h5=False, overwrite=False)

Manually validates cell fate by reviewing images and tracking data for individual cells over time. Provides an interactive validation interface to assess whether cells follow a specific fate or not.

Parameters:
  • indcells (array-like of int) – Indices of cells to review for fate validation.

  • fate_attr (str) – The name of the fate attribute being reviewed and validated.

  • trajl_future (int, optional) – Number of future frames to include in the trajectory review (default is 2).

  • trajl_past (int, optional) – Number of past frames to include in the trajectory review (default is 2).

  • restart (bool, optional) – Whether to restart validation from the beginning (default is True). If False, previously reviewed cells are re-evaluated.

  • val_tracks (bool, optional) – If True, validates the cell tracking in addition to fate validation (default is True).

  • rep_channel (int, optional) – The channel used for representation images (default is 2).

  • bf_channel (int, optional) – The bright-field channel (default is 0).

  • nuc_channel (int, optional) – The nucleus channel (default is 1).

  • msk_channel (int, optional) – The mask channel used for cell identification (default is 0).

  • pathto (str, optional) – The path to save images if save_pic is True (default is ‘./’).

  • save_pic (bool, optional) – Whether to save the images for each validated cell (default is False).

  • boundary_expansion (list of int, optional) – The number of pixels to expand the boundary of the cell block in the image (default is [1, 40, 40]).

  • save_attr (bool, optional) – Whether to save the validated attributes during the process (default is True).

  • save_h5 (bool, optional) – Whether to save the updated attributes to an HDF5 file (default is False).

  • overwrite (bool, optional) – Whether to overwrite existing data when saving to HDF5 (default is False).

Returns:

  • vals_fate (ndarray of int) – Validated fate values for each cell. 1 indicates fate, 0 indicates not fate, and -1 indicates unclear or indeterminate fate.

  • inds_fate (ndarray of int) – Indices of the cells that were confirmed to follow the fate of interest.

Notes

  • This function provides an interactive review interface, where users can manually validate the fate and tracking of cells.

  • It allows users to interactively break cell lineage links if necessary and stores the results of each review session.

  • The images and masks for each cell across its past and future trajectory are visualized for validation.

Examples

>>> vals_fate, inds_fate = model.manual_fate_validation(indcells, 'apoptosis', trajl_future=3, trajl_past=3, save_pic=True, pathto='/output/images')
>>> print(f'Validated fates for {len(inds_fate)} cells.')
get_border_properties_dict(iS, cell_states=None, state_ids=None, secretion_rates=None, surfaces=None, surface_fmask_channels=None, surface_states_baseid=1000, add_label0_surf=True, make_cells_and_surfaces_disjoint=True, border_scale=None, border_resolution=None, vdist_scale=0.3, radius=2.0, order=1, visual=False, z_viz=None)

Calculate border properties for cells and surfaces at a given frame in a trajectory.

This function extracts data required to characterize the borders of cells within a specified frame (iS) in a 3D or 2D cell image sequence. The borders are characterized based on geometric and physical properties, with optional visualization and multipole moment expansion up to the specified order. Supports the inclusion of surface contacts, tracking cell borders over time, and calculating secreted ligand distributions.

Parameters:
  • iS (int) – Frame index within the trajectory for which to calculate border properties.

  • cell_states (ndarray, optional) – Array of states for each cell in the current frame. If not provided, all cells are assigned state 1 by default.

  • secretion_rates (ndarray, optional) – Array of secretion rates for each cell, used to calculate secreted ligand distribution along cell borders. If not provided, no secretion is considered.

  • surfaces (list of ndarrays, optional) – List of binary masks for surfaces adjacent to cells (e.g., membranes or other boundaries). Surfaces are optionally assigned states via surface_fmask_channels.

  • surface_fmask_channels (list of int, optional) – List of channels in the frame data specifying each surface’s mask. Used if surfaces is None. Each channel mask is assigned a state from surface_states_baseid onward.

  • surface_states_baseid (int, optional) – Base state ID for assigning states to surfaces. Defaults to 1000.

  • add_label0_surf (bool, optional) – If True, includes cells labeled as 0 (background) as a surface layer. Default is True.

  • make_cells_and_surfaces_disjoint (bool, optional) – If True, cells and surfaces are treated as mutually exclusive regions. Default is True.

  • border_scale (float or list of float, optional) – Scale for border calculations. If None, it defaults to the border_resolution attribute if available.

  • border_resolution (float, optional) – Resolution of the border calculations in units of pixels. If None, the value from the object’s border_resolution attribute is used if present.

  • vdist_scale (float, optional) – Scale factor for calculating the secreted ligand distribution. Default is 0.3.

  • radius (float, optional) – Radius for identifying contact neighbors when calculating border properties. Default is 2.0.

  • order (int, optional) – Order of multipole moments to compute for cell border properties. Default is 1.

  • visual (bool, optional) – If True, generates a visualization of the borders, including displacements from the previous and next frames.

  • z_viz (int, optional) – Specific z-plane to visualize in 3D data. If None, a central z-plane is chosen.

Returns:

border_dict – Dictionary containing computed properties for cell borders, including:

  • pts: Coordinates of each border point.

  • index: Cell IDs associated with each border point.

  • nn_states: States of neighboring cells at each border point.

  • c: Curvature at each border point.

  • global_index: Global indices for each border point in the dataset.

  • border_dx_prev, border_dx_next: Displacement vectors for borders to previous and

next frames, if applicable. - contact_properties: Multipole moment properties based on cell-state contacts. - vdist: Secreted ligand density distribution, if secretion_rates is provided.

Return type:

dict

Notes

  • Tracking: If previous (cell_labels_prev) or next frame (cell_labels_next) is provided,

the function calculates the optimal transport vector between consecutive frames for each cell. - Surface Assignment: When surface_fmask_channels is provided, each channel is used to define a distinct surface mask, and surface_states are assigned based on surface_states_baseid. - Multipole Moments: Higher-order moments are calculated based on border charges determined from neighboring cell states.

Examples

Compute border properties for frame 10 with secreted ligand distribution and visualize:

>>> border_properties = self.get_border_properties_dict(
...     iS=10, cell_states=my_cell_states, secretion_rates=my_secretion_rates,
...     surface_fmask_channels=[0, 1], border_resolution=1.0, vdist_scale=0.5, order=2,
...     visual=True, z_viz=15
... )
get_cellboundary_library(frames=None, indcells=None, secretion_rates=None, cell_states=None, state_ids=None, state_labels=None, surface_fmask_channels=[0], surface_states_baseid=None, border_resolution=1.0, vdist_scale=0.3, visual=False, save_h5=False, overwrite=False, **border_property_args)

Collect and create a library of boundary properties for cells across specified frames in a trajectory.

This function gathers cell and surface boundary properties across frames or specific cell indices. It collects properties such as position, displacement, neighboring point states, curvatures, and secreted ligand distributions, if applicable. This data is returned in a library format and optionally saved to an HDF5 file for later use.

Parameters:
  • frames (list of int, optional) – Frame indices to include in the boundary library. If None, includes all frames in cells_frameSet.

  • indcells (ndarray, optional) – Array of specific cell indices to include in the library. If None, all cells are included.

  • secretion_rates (ndarray, optional) – Array of secretion rates for each cell, used to calculate ligand distribution along borders.

  • cell_states (ndarray, optional) – Array of cell states for each cell. If not provided, cells are assigned state 1.

  • surface_fmask_channels (list of int, default [0]) – List of channels indicating each surface’s mask in the frame data.

  • surface_states_baseid (int, optional) – Starting ID for surface states. Defaults to one more than the maximum cell_states.

  • border_resolution (float, optional) – Resolution for border properties in units of pixels. Default is 1.0.

  • vdist_scale (float, optional) – Scale for secreted ligand distribution. Default is 0.3.

  • visual (bool, optional) – If True, displays a visualization of the boundaries. Default is False.

  • save_h5 (bool, optional) – If True, saves the resulting boundary library to an HDF5 file. Default is False.

  • overwrite (bool, optional) – If True, overwrites the HDF5 data file if it exists. Default is False.

  • **border_property_args – Additional arguments passed to the get_border_properties_dict function.

Returns:

boundary_library – Dictionary containing collected boundary properties for the specified cells and frames:

  • global_index: Global cell indices for each boundary point.

  • states: Cell or surface state at each boundary point.

  • pts: Coordinates of each boundary point.

  • dx_prevs, dx_nexts: Displacement vectors for boundaries to previous and next frames.

  • surface_normals: Surface normal vectors at each boundary point.

  • curvatures: Curvature at each boundary point.

  • nn_pts: Coordinates of neighboring points.

  • nn_states: States of neighboring points.

  • nn_pts_states: States of neighboring points with finer resolution.

  • surf_vars: Variance of surface displacement in the previous frame.

  • vdists: Secreted ligand density distribution, if secretion_rates is provided.

Return type:

dict

Notes

  • Frames and Cell Selection: If both frames and indcells are provided, only frames derived from

indcells are used. - Surfaces and States: surface_fmask_channels and surface_states_baseid define and initialize surfaces in each frame, using additional states based on surface_states_baseid. - Ligand Distribution: Secreted ligand density distribution (vdists) is included if secretion_rates is specified.

Examples

Generate a cell boundary library for frames 10, 15, and 20, with visualization enabled:

>>> boundary_library = self.get_cellboundary_library(
...     frames=[10, 15, 20], secretion_rates=my_secretion_rates, cell_states=my_cell_states,
...     surface_fmask_channels=[0, 1], visual=True, border_resolution=2.0
... )

Save the boundary library to HDF5 with overwrite enabled:

>>> boundary_library = self.get_cellboundary_library(
...     indcells=my_indcells, save_h5=True, overwrite=True
... )
get_multipole_boundarylibrary_properties(indcells=None, cell_states=None, cell_state_labels=None, nn_states=None, nn_state_labels=None, include_dx_prevs=True, include_dx_nexts=True, include_curvatures=True, include_vdists=False, include_shape=True, order=1, save_h5=False, overwrite=False)

Compute spherical multipole‐based features from the pre‐extracted boundary library for each cell.

This routine treats each cell’s boundary points as a discrete distribution of “charges” (scalar values defined by inverse neighbor distances, curvature, displacements, etc.), and computes the low‐order multipole moments of that distribution. Multipole moments compactly encode spatial patterns around each cell, capturing neighborhood geometry, motility, and shape features in a rotationally invariant basis.

Parameters:
  • self (Trajectory) – A Trajectory instance whose boundary_library (from get_cellboundary_library) contains per‐point data.

  • indcells (array-like of int, optional) – List of global cell indices to process. If None, processes all cells in the library.

  • cell_states (array-like of int, optional) – Subset of cell‐state IDs to include. Default is all states found in the library.

  • cell_state_labels (list of str, optional) – Text labels for each cell_states entry. Defaults to “cell state {state_id}”.

  • nn_states (array-like of int, optional) – Subset of neighbor‐state IDs to include. Defaults to all neighbor states in the library.

  • nn_state_labels (list of str, optional) – Text labels for each nn_states entry. Defaults to “nn state {state_id}”.

  • include_dx_prevs (bool, default True) – Whether to include multipole moments of the previous‐frame normal displacement.

  • include_dx_nexts (bool, default True) – Whether to include multipole moments of the next‐frame normal displacement.

  • include_curvatures (bool, default True) – Whether to include multipole moments of the boundary curvature.

  • include_vdists (bool, default False) – Whether to include multipole moments of secreted ligand density (vdist).

  • include_shape (bool, default True) – Whether to include shape features (e.g., sphere radius) via multipole moments.

  • order (int, default 1) – Maximum spherical harmonic order ℓ for the multipole expansion.

  • save_h5 (bool, default False) – If True, store results (mm_properties and mm_property_names) in this instance’s HDF5 data.

  • overwrite (bool, default False) – If True and save_h5 is True, overwrite existing datasets in the HDF5 file.

Returns:

  • mm_properties (ndarray, shape (max_cell_id+1, n_features)) – Rows indexed by cell ID, columns by the multipole‐derived features listed in property_names.

  • property_names (list of str) – Length‐n_features list describing each column in mm_properties.

Notes

  • Multipole moments are computed by expanding the scalar “charge” distribution q(r) on the boundary into

spherical harmonics up to order order, then assembling the radial moments. - The multipoles package (Maroba et al.) handles the core expansion: https://github.com/maroba/multipoles - Feature blocks include:

  • Inverse‐distance charges to each neighbor state

  • Frame‐to‐frame normal displacements (prev/next)

  • Local curvature

  • Ligand density (vdist), if requested

  • Shape deviations and equivalent sphere radius

References

  • Maroba, M. _multipoles_ Python package:

https://github.com/maroba/multipoles