baby.tracker.core.CellTracker¶
- class baby.tracker.core.CellTracker(feats2use=None, trapfeats=None, extrafeats=None, model=None, bak_model=None, thresh=None, low_thresh=None, high_thresh=None, nstepsback=None, aweights=None, red_fun=None, max_distance=None, **kwargs)¶
Bases:
FeatureCalculator
Class used to manage cell tracking. You can call it using an existing model or use the inherited CellTrainer to get a new one.
Initialization parameters:
- Model
sklearn.ensemble.RandomForestClassifier object
- Trapfeats
Features to manually calculate within a trap
- Extrafeats
Additional features to calculate
- Model
Model to use, if provided ignores all other args but threshs
- Bak_model
Backup mode to use when prediction is unsure
- Nstepsback
int Number of timepoints to go back
- Thresh
float Cut-off value to assume a cell is not new
- Low_thresh
Lower thresh for model switching
- High_thresh
Higher thresh for model switching. Probabilities between these two thresholds summon the backup model.
- Aweights
area weight for barycentre calculations
# Feature order in array features 1. basic features 2. trap features (within a trap) 3. extra features (process between imgs)
- Attributes
- a_ind
- ma_ind
- x_ind
- y_ind
Methods
assign_lbls
(prob_backtrace, prev_lbls[, red_fun])Assign labels using a prediction matrix of nxmxl where n is the number of cells in the previous image, m the number of steps back considered and l in the new image.
calc_dtfeats
(n3darray)Calculates features obtained between timepoints, such as distance for every pair of cells from t1 to t2.
calc_feat_ndarray
(prev_feats, new_feats)Calculate feature ndarray using two ndarrays of features.
calc_feats_from_mask
(masks[, feats2use, ...])Calculate feature ndarray from ndarray of cell masks
calc_trapfeats
(basefeats)Calculate trap-based features using basic ones. :basefeats: (n basic outfeats) 1-D array with features outputed by skimage.measure.regionprops_table.
Return feats to be used from a loaded random forest model model
get_new_lbls
(new_img, prev_lbls, prev_feats, ...)Core function to calculate the new cell labels.
predict_proba_from_ndarray
(array_3d[, ...])input
probabilities_from_impair
(image_t1, image_t2)Convenience function to test tracking between two time-points
run_tp
(masks[, state])Assign labels to new masks using a state dictionary.
scale_feats
(feats, pixel_size)input
get_outfeats
load_model
set_named_ids
- __init__(feats2use=None, trapfeats=None, extrafeats=None, model=None, bak_model=None, thresh=None, low_thresh=None, high_thresh=None, nstepsback=None, aweights=None, red_fun=None, max_distance=None, **kwargs)¶
Methods
__init__
([feats2use, trapfeats, extrafeats, ...])assign_lbls
(prob_backtrace, prev_lbls[, red_fun])Assign labels using a prediction matrix of nxmxl where n is the number of cells in the previous image, m the number of steps back considered and l in the new image.
calc_dtfeats
(n3darray)Calculates features obtained between timepoints, such as distance for every pair of cells from t1 to t2.
calc_feat_ndarray
(prev_feats, new_feats)Calculate feature ndarray using two ndarrays of features.
calc_feats_from_mask
(masks[, feats2use, ...])Calculate feature ndarray from ndarray of cell masks
calc_trapfeats
(basefeats)Calculate trap-based features using basic ones. :basefeats: (n basic outfeats) 1-D array with features outputed by skimage.measure.regionprops_table.
Return feats to be used from a loaded random forest model model
get_new_lbls
(new_img, prev_lbls, prev_feats, ...)Core function to calculate the new cell labels.
get_outfeats
([feats2use])load_model
(path, fname)predict_proba_from_ndarray
(array_3d[, ...])input
probabilities_from_impair
(image_t1, image_t2)Convenience function to test tracking between two time-points
run_tp
(masks[, state])Assign labels to new masks using a state dictionary.
scale_feats
(feats, pixel_size)input
set_named_ids
()Attributes
a_ind
ma_ind
x_ind
y_ind
- assign_lbls(prob_backtrace: ndarray, prev_lbls: List[List[int]], red_fun=None)¶
Assign labels using a prediction matrix of nxmxl where n is the number of cells in the previous image, m the number of steps back considered and l in the new image. It assigns the number zero if it doesn’t find the cell. — input
- Prob_backtrace
Probability n x m x l array obtained as an output of rforest
- Prev_labels
List of cell labels for previous timepoint to be compared.
- Red_fun
Function used to collapse the previous timepoints into one. If none provided it uses maximum and ignores np.nans.
returns
- New_lbls
ndarray of newly assigned labels obtained, new cells as
zero.
- calc_dtfeats(n3darray)¶
Calculates features obtained between timepoints, such as distance for every pair of cells from t1 to t2. —
input
- N3darray
ndarray (ncells_prev, ncells_new, ntfeats) containing a cell-wise substraction of the features in the input ndarrays.
returns
- Newarray
3d array taking the features specified in self.outfeats and self.trapfeats
and adding dtfeats
- calc_feat_ndarray(prev_feats, new_feats)¶
Calculate feature ndarray using two ndarrays of features. —
input
- Prev_feats
ndarray (ncells, nfeats) of timepoint 1
- New_feats
ndarray (ncells, nfeats) of timepoint 2
returns
- N3darray
ndarray (ncells_prev, ncells_new, nfeats) containing a cell-wise substraction of the features in the input ndarrays.
- calc_feats_from_mask(masks: ndarray, feats2use: Optional[Tuple[str]] = None, trapfeats: Optional[Tuple[str]] = None, scale: Optional[bool] = True, pixel_size: Optional[float] = None)¶
Calculate feature ndarray from ndarray of cell masks — input
- Masks
ndarray (ncells, x_size, y_size), typically dtype bool
- Feats2use
list of strings with the feature properties to extract. If it is None it uses the ones set in self.feats2use.
- Trapfeats
List of str with additional features to use calculated immediately after basic features.
- Scale
bool, if True scales mask to a defined pixel_size.
- Pixel_size
float, used to rescale the object features.
returns
(ncells, nfeats) ndarray of features for input masks
- calc_trapfeats(basefeats)¶
Calculate trap-based features using basic ones. :basefeats: (n basic outfeats) 1-D array with features outputed by
skimage.measure.regionprops_table
- requires
self.aind self.aweights self.xind self.yind self.trapfeats
returns (ntrapfeats) 1-D array with
- get_feats2use()¶
Return feats to be used from a loaded random forest model model
- get_new_lbls(new_img, prev_lbls, prev_feats, max_lbl, new_feats=None, pixel_size=None, **kwargs)¶
Core function to calculate the new cell labels.
input
- New_img
ndarray (len, width, ncells) containing the cell outlines
- Max_lbl
int indicating the last assigned cell label
- Prev_feats
list of ndarrays of size (ncells x nfeatures)
containing the features of previous timepoints :prev_lbls: list of list of ints corresponding to the cell labels in
the previous timepoints
- New_feats
(optional) Directly give a feature ndarray. It ignores new_img if given.
- Kwargs
Additional keyword values passed to self.predict_proba_from_ndarray
returns
- New_lbls
list of labels assigned to new timepoint
- New_feats
list of ndarrays containing the updated features
- New_max
updated max cell label assigned
- predict_proba_from_ndarray(array_3d: ndarray, model: Optional[str] = None, boolean: bool = False, max_distance: Optional[float] = None)¶
input
- Array_3d
(ncells_tp1, ncells_tp2, out_feats) ndarray
- Model
str, {‘model’, ‘bak_model’} can force a unique model instead of an ensemble
- Boolean
bool, if False returns probability, if True returns prediction
- Max_distance
float Maximum distance (in um) to be considered. If None it uses the instance’s value,
if zero it skips checking distances.
requires :self.model: :self.mainof_ids: list of indices corresponding to the main model’s features :self.bakof_ids: list of indices corresponding to the backup model’s features
returns
- (ncells_tp1, ncells_tp2) ndarray with probabilities or prediction
of cell identities depending on “boolean” arg.
- probabilities_from_impair(image_t1: ndarray, image_t2: ndarray, kwargs_feat_calc: dict = {}, **kwargs)¶
Convenience function to test tracking between two time-points
- Image_t1
np.ndarray containing mask of first time-point
- Image_t2
np.ndarray containing mask of second time-point
- Kwargs_feat_calc
are passed to self.calc_feats_from_mask calls
- Kwargs
are passed to self.predict_proba_from_ndarray
- run_tp(masks: ndarray, state: Optional[Dict[str, Union[int, list]]] = None, **kwargs) Dict[str, Union[List[int], Dict[str, Union[int, list]]]] ¶
Assign labels to new masks using a state dictionary.
- Parameters
- masksnp.ndarray
Cell masks to label.
- statet.Dict[str, t.Union[int, list]]
Dictionary containing maximum cell label, and previous cell labels and features for those cells.
- kwargskeyword arguments
Keyword arguments passed to self.get_new_lbls
- Returns
- t.Dict[str, t.Union[t.List[int], t.Dict[str, t.Union[int, list]]]]
New labels and new state dictionary.
Examples
FIXME: Add example beyond the trivial one.
import numpy as np from baby.tracker.core import celltracker from tqdm import tqdm
# overlapping outlines are of shape (t,z,x,y) masks = np.zeros((5, 3, 20, 20), dtype=bool) masks[0, 0, 2:6, 2:6] = true masks[1:, 0, 13:14, 13:14] = true masks[:, 1, 8:12, 8:12] = true masks[:, 2, 14:18, 14:18] = true
# 13um pixel size ct = celltracker(pixel_size=0.185) labels = []
state = none for masks_tp in tqdm(masks):
new_labels, state = ct.run_tp(masks_tp, state=state) labels.append(new_labels)
# should result in state[‘cell_lbls’] # [[1, 2, 3], [4, 2, 3], [4, 2, 3], [4, 2, 3], [4, 2, 3]]
- scale_feats(feats: ndarray, pixel_size: float)¶
input
- Feats
np.ndarray (ncells * nfeatures)
- Pixel_size
float Value used to normalise the images.
returns Rescaled list of feature values