API Reference

laptrack

pydantic model laptrack.LapTrack

Tracking class for LAP tracker with parameters.

Fields:
  • track_dist_metric (str | Callable)

  • track_cost_cutoff (float)

  • gap_closing_dist_metric (str | Callable)

  • gap_closing_cost_cutoff (Literal[False] | float)

  • gap_closing_max_frame_count (int)

  • splitting_dist_metric (str | Callable)

  • splitting_cost_cutoff (Literal[False] | float)

  • merging_dist_metric (str | Callable)

  • merging_cost_cutoff (Literal[False] | float)

  • track_start_cost (float | None)

  • track_end_cost (float | None)

  • segment_start_cost (float | None)

  • segment_end_cost (float | None)

  • no_splitting_cost (float | None)

  • no_merging_cost (float | None)

  • alternative_cost_factor (float)

  • alternative_cost_percentile (float)

  • alternative_cost_percentile_interpolation (str)

  • parallel_backend (laptrack._tracking.ParallelBackend)

field track_dist_metric: str | Callable = 'sqeuclidean'

The metric for calculating track linking cost. See documentation for scipy.spatial.distance.cdist for accepted values.

field track_cost_cutoff: float = 225

The cost cutoff for the connected points in the track. For default cases with dist_metric=’sqeuclidean’, this value should be squared maximum distance.

field gap_closing_dist_metric: str | Callable = 'sqeuclidean'

The metric for calculating gap closing cost. See documentation for scipy.spatial.distance.cdist for accepted values.

field gap_closing_cost_cutoff: Literal[False] | float = 225

The cost cutoff for gap closing. For default cases with dist_metric=’sqeuclidean’, this value should be squared maximum distance. If False, no gap closing is allowed.

field gap_closing_max_frame_count: int = 2

The maximum frame gaps, by default 2.

field splitting_dist_metric: str | Callable = 'sqeuclidean'

The metric for calculating splitting cost. See track_dist_metric.

field splitting_cost_cutoff: Literal[False] | float = False

The cost cutoff for splitting. See gap_closing_cost_cutoff. If False, no splitting is allowed.

field merging_dist_metric: str | Callable = 'sqeuclidean'

The metric for calculating merging cost. See track_dist_metric

field merging_cost_cutoff: Literal[False] | float = False

The cost cutoff for merging. See gap_closing_cost_cutoff. If False, no merging is allowed.

field track_start_cost: float | None = None

The cost for starting the track (b in Jaqaman et al 2008 NMeth) If None, automatically estimated.

field track_end_cost: float | None = None

The cost for ending the track (d in Jaqaman et al 2008 NMeth). If None, automatically estimated.

field segment_start_cost: float | None = None

The cost for starting the segment (b in Jaqaman et al 2008 NMeth). If None, automatically estimated.

field segment_end_cost: float | None = None

The cost for ending the segment (d in Jaqaman et al 2008 NMeth). If None, automatically estimated.

field no_splitting_cost: float | None = None

The cost to reject splitting, if None, automatically estimated.

field no_merging_cost: float | None = None

The cost to reject merging, if None, automatically estimated.

field alternative_cost_factor: float = 1.05

The factor to calculate the alternative costs (b,d,b’,d’ in Jaqaman et al 2008 NMeth).

field alternative_cost_percentile: float = 90

The percentile to calculate the alternative costs.

field alternative_cost_percentile_interpolation: str = 'lower'

The percentile interpolation to calculate the alternative costs. See numpy.percentile for accepted values.

field parallel_backend: ParallelBackend = ParallelBackend.serial

The parallelization strategy. Must be one of serial, ray.

predict(coords, connected_edges=None, split_merge_validation=True)

Predict the tracking graph from coordinates.

Parameters:
  • coords (Sequence[NumArray]) – The list of coordinates of point for each frame. The array index means (sample, dimension).

  • connected_edges (Optional[EdgeType]) – The edges that is known to be connected. If None, no edges are assumed to be connected.

  • split_merge_validation (bool) – If true, check if the split/merge edges are two-fold.

Raises:

ValueError – Raised for invalid coordinate formats.:

Returns:

track_tree – The graph for the tracks, whose nodes are (frame, index). The edge direction represents the time order.

Return type:

nx.DiGraph

predict_dataframe(df, coordinate_cols, frame_col='frame', validate_frame=True, only_coordinate_cols=True, connected_edges=None, index_offset=0)

Shorthand for the tracking with the dataframe input / output.

Parameters:
  • df (pd.DataFrame) – The input dataframe.

  • coordinate_cols (List[str]) – The list of the columns to use for coordinates.

  • frame_col (str, optional) – The column name to use for the frame index. Defaults to “frame”.

  • validate_frame (bool, optional) – Whether to validate the frame. Defaults to True.

  • only_coordinate_cols (bool, optional) – Whether to use only the coordinate columns. Defaults to True.

  • connected_edges (Optional[List[Tuple[Int,Int]]]) – The edges that is known to be connected. Must be a list of the tuples of the row numbers (not index, but iloc). If None, no edges are assumed to be connected.

  • index_offset (Int) – The offset to add to the track and tree index.

Returns:

  • track_df (pd.DataFrame) – The track dataframe, with the following columns:

    • ”frame” : The frame index.

    • ”index” : The coordinate index.

    • ”track_id” : The track id.

    • ”tree_id” : The tree id.

    • the other columns : The coordinate values.

  • split_df (pd.DataFrame) – The splitting dataframe, with the following columns:

    • ”parent_track_id” : The track id of the parent.

    • ”child_track_id” : The track id of the child.

  • merge_df (pd.DataFrame) – The merging dataframe, with the following columns:

    • ”parent_track_id” : The track id of the parent.

    • ”child_track_id” : The track id of the child.

Return type:

Tuple[DataFrame, DataFrame, DataFrame]

laptrack.laptrack(coords, **kwargs)

Shorthand for calling LapTrack.fit(coords).

Parameters:
  • coords (Sequence[NumArray]) – The list of coordinates of point for each frame. The array index means (sample, dimension).

  • **kwargs (dict) – Parameters for the LapTrack initalization

Returns:

tracks – The graph for the tracks, whose nodes are (frame, index).

Return type:

networkx.Graph

data conversion utilities

Data conversion utilities for tracking.

laptrack.data_conversion.convert_dataframe_to_coords(df, coordinate_cols, frame_col='frame', validate_frame=True)

Convert a track dataframe to a list of coordinates for input.

Parameters:
  • df (pd.DataFrame) – The input dataframe.

  • coordinate_cols (List[str]) – The list of columns to use for coordinates.

  • frame_col (str, default "frame") – The column name to use for the frame index.

  • validate_frame (bool, default True) – Whether to validate the frame.

Returns:

coords – The list of the coordinates.

Return type:

List[np.ndarray]

laptrack.data_conversion.convert_dataframe_to_coords_frame_index(df, coordinate_cols, frame_col='frame', validate_frame=True)

Convert a track dataframe to a list of coordinates for input with (frame,index) list.

Parameters:
  • df (pd.DataFrame) – The input dataframe.

  • coordinate_cols (List[str]) – The list of columns to use for coordinates.

  • frame_col (str, default "frame") – The column name to use for the frame index.

  • validate_frame (bool, default True) – Whether to validate the frame.

Returns:

  • coords (List[np.ndarray]) – The list of coordinates.

  • frame_index (List[Tuple[int, int]]) – The (frame, index) list for the original iloc of the dataframe.

Return type:

Tuple[List[ndarray[Any, dtype[float64 | int64]]], List[Tuple[int, int]]]

laptrack.data_conversion.convert_split_merge_df_to_napari_graph(split_df, merge_df)

Convert the split and merge dataframes to a dictionary of parent to children for napari visualization.

Parameters:
  • split_df (pd.DataFrame) – The splitting dataframe.

  • merge_df (pd.DataFrame) – The merging dataframe.

Returns:

split_merge_graph – Dictionary defines the mapping between a track ID and the parents of the track.

Return type:

Dict[int,List[int]]

laptrack.data_conversion.convert_tree_to_dataframe(tree, coords=None, dataframe=None, frame_index=None)

Convert the track tree to dataframes.

Parameters:
  • tree (nx.Graph) – The track tree, resulted from the traking.

  • coords (Optional[Sequence[NumArray]], default None) – The coordinate values. If None, no coordinate values are appended to the dataframe.

  • dataframe (Optional[pd.DataFrame], default None) – The dataframe. If not None, frame_index should also exist. Ignored if the parameter coords is not None.

  • frame_index (Optional[List[Tuple[int, int]]], default None) – the inverse map to map (frame, index) to the original iloc of the dataframe.

Returns:

  • track_df (pd.DataFrame) – The track dataframe, with the following columns:

    • ”frame” : The frame index.

    • ”index” : The coordinate index.

    • ”track_id” : The track id.

    • ”tree_id” : The tree id.

    • ”coord-0”, “coord-1”, … : The coordinate values. Exists if coords is not None.

  • split_df (pd.DataFrame) – The splitting dataframe, with the following columns:

    • ”parent_track_id” : The track id of the parent.

    • ”child_track_id” : The track id of the parent.

  • merge_df (pd.DataFrame) – The merging dataframe, with the following columns:

    • ”parent_track_id” : The track id of the parent.

    • ”child_track_id” : The track id of the parent.

Return type:

Tuple[DataFrame, DataFrame, DataFrame]

score calculation utilities

Tracking score calculation utilities.

laptrack.scores.calc_scores(true_edges, predicted_edges, exclude_true_edges=[], include_frames=None, track_scores=True)

Calculate track prediction scores.

Parameters:
  • true_edges (EdgeType) – The list of true edges. Assumes ((frame1,index1), (frame2,index2)) for each edge.

  • predicted_edges (EdgeType) – The list of predicted edges. See true_edges for the format.

  • exclude_true_edges (EdgeType, default []) – The list of true edges to be excluded from “*_ratio”. See true_edges for the format.

  • include_frames (Optional[List[Int]], default None) – The list of frames to include in the score calculation. If None, all the frames are included.

  • track_scores (bool, default True) – If True, the function calculates track_purity, target_effectiveness and mitotic_branching_correctness.

Returns:

score_dict – The scores in the dict form. The keys are:

  • ”Jaccard_index”: (number of TP edges) / (number of TP edges + number of FP edges + number of FN edges)

  • ”true_positive_rate”: (number of TP edges) / (number of TP edges + number of FN edges)

  • ”precision”: (number of TP edges) / (number of TP edges + number of FP edges)

  • ”track_purity” : the track purity.

  • ”target_effectiveness” : the target effectiveness.

  • ”mitotic_branching_correctness” : the number of divisions that were correctly predicted.

Return type:

Dict[str,float]

metric utilities

Utilities for metric calculation.

class laptrack.metric_utils.LabelOverlap(label_images)

Utility object to calculate overlap of segmentation labels between frames.

Parameters:

label_images (ndarray[Any, dtype[int64]] | List[ndarray[Any, dtype[int64]]]) –

__init__(label_images)

Summarise the segmentation properties and initialize the object.

Parameters:

label_images (Union[IntArray,List[IntArray]]) – The labeled images. The first dimension is interpreted as the frame dimension.

calc_overlap(frame1, label1, frame2, label2)

Calculate the overlap properties of the labeled regions.

Parameters:
  • frame1 (Int) – the frame of the first object

  • label1 (Int) – the label of the first object

  • frame2 (Int) – the frame of the second object

  • label2 (Int) – the label of the second object

Returns:

  • overlap (float) – overlap (intersection) of the labeled regions

  • iou (float) – overlap over the union of the labeled regions

  • ratio_1 (float) – overlap over the area of the first object of the labeled regions

  • ratio_2 (float) – overlap over the area of the second object of the labeled regions

Return type:

Tuple[int | int64 | uint8 | uint16 | uint32 | uint64, float | float64, float | float64, float | float64]

class laptrack.metric_utils.LabelOverlapOld(label_images)

Utility object to calculate overlap of segmentation labels between frames (Old implementation using regionoprops).

Parameters:

label_images (ndarray[Any, dtype[int64]] | List[ndarray[Any, dtype[int64]]]) –

__init__(label_images)

Summarise the segmentation properties and initialize the object.

Parameters:

label_images (Union[IntArray,List[IntArray]]) – The labeled images. The first dimension is interpreted as the frame dimension.

calc_overlap(frame1, label1, frame2, label2)

Calculate the overlap properties of the labeled regions.

Parameters:
  • frame1 (Int) – the frame of the first object

  • label1 (Int) – the label of the first object

  • frame2 (Int) – the frame of the second object

  • label2 (Int) – the label of the second object

Returns:

  • overlap (float) – overlap of the labeled regions

  • iou (float) – overlap over intersection of the labeled regions

  • ratio_1 (float) – overlap over the area of the first object of the labeled regions

  • ratio_2 (float) – overlap over the area of the second object of the labeled regions

Return type:

Tuple[int | int64 | uint8 | uint16 | uint32 | uint64, float | float64, float | float64, float | float64]

sample datasets

Datasets used for testing.

laptrack.datasets.HL60_3D_synthesized()

Return the “HL60 3D synthesized” dataset.

Data source: rescaling dataset 1 in https://bbbc.broadinstitute.org/BBBC050 Image set BBBC050 [Tokuoka, Yuta, et al. npj Syst Biol Appl 6, 32 (2020)], downloaded from the Broad Bioimage Benchmark Collection [Ljosa et al., Nature Methods, 2012]. The images and ground truth are licensed under a Creative Commons Attribution 3.0 Unported License (Commercial use allowed) by Akira Funahashi.

Returns:

data – The images and labels.

Return type:

Tuple[FloatArray, IntArray]

laptrack.datasets.bright_brownian_particles()

Return the “bright Brownian particles” dataset.

Returns:

data – The images.

Return type:

FloatArray

laptrack.datasets.cell_segmentation()

Return the “cell segmentation” dataset.

Data source: https://osf.io/ysaq2/ CC-By Attribution 4.0 International

Returns:

data – The images and labels.

Return type:

Tuple[FloatArray, IntArray]

laptrack.datasets.fetch(data_name)

Fetch a sample dataset from GitHub.

Parameters:

data_name (str) – The name of the dataset. Must be one of [“simple_tracks”, “bright_brownian_particles”, “cell_segmentation”, “mouse_epidermis”].

Returns:

data – The result data.

Return type:

Union[ndarray,pd.DataFrame]

Raises:

ValueError – If the dataset name is not one of the allowed values.:

laptrack.datasets.mouse_epidermis()

Return the “mouse epidermis” dataset.

Data source: cropping segmentation.npy in https://github.com/NoneqPhysLivingMatterLab/cell_interaction_gnn.

Returns:

data – The labels.

Return type:

IntArray

laptrack.datasets.simple_tracks()

Return the “simple tracks” dataset.

Returns:

data – The dataset.

Return type:

pd.DataFrame