celltraj.spatial

celltraj.spatial.get_border_dict(labels, states=None, radius=10, state_ids=None, vdist=None, return_nnindex=True, return_nnvector=True, return_curvature=True, nn_states=None, scale=None, verbose=False, **border_args)

Computes the border properties of labeled regions in a segmented image.

This function identifies the borders of labeled regions in a given image and calculates various properties such as nearest neighbor indices, vectors, and curvature. It can also return the scaled distances if specified.

Parameters:
  • labels (ndarray) – A 2D or 3D array where each element represents a label, identifying different regions in the image.

  • states (ndarray, optional) – An array indicating the state of each labeled region. If provided, states are used to differentiate regions. If None, all regions are assumed to have the same state.

  • radius (float, optional) – The radius for finding nearest neighbors around each border point (default is 10).

  • vdist (ndarray, optional) – An array representing a scalar value in the image, such as estimated ligand concentration, to store in the border point dictionary.

  • return_nnindex (bool, optional) – If True, returns the nearest neighbor index for each border point (default is True).

  • return_nnvector (bool, optional) – If True, returns the vector pointing to the nearest neighbor for each border point (default is True).

  • return_curvature (bool, optional) – If True, calculates and returns the curvature at each border point (default is True).

  • scale (list or ndarray, optional) – Scaling factors for each dimension of the labels array. If provided, scales the labels accordingly.

  • **border_args (dict, optional) – Additional arguments to control border property calculations, such as ‘knn’ for the number of nearest neighbors when computing curvature.

Returns:

border_dict – A dictionary containing the computed border properties: - ‘pts’: ndarray of float, coordinates of the border points. - ‘index’: ndarray of int, indices of the regions to which each border point belongs. - ‘states’: ndarray of int, states of the regions to which each border point belongs. - ‘nn_index’: ndarray of int, nearest neighbor indices for each border point (if return_nnindex is True). - ‘nn_states’: ndarray of int, states of the nearest neighbors (if return_nnindex is True). - ‘nn_pts’: ndarray of float, coordinates of the nearest neighbors (if return_nnvector is True). - ‘nn_inds’: ndarray of int, indices of the nearest neighbors (if return_nnvector is True). - ‘n’: ndarray of float, normals at each border point (if return_curvature is True). - ‘c’: ndarray of float, curvature at each border point (if return_curvature is True). - ‘vdist’: ndarray of float, scaled distances at each border point (if vdist is provided).

Return type:

dict

Notes

  • This function is useful for analyzing cell shapes and their interactions in spatially resolved images.

  • The nearest neighbor indices and vectors can help understand cell-cell interactions and local neighborhood structures.

  • The curvature values can provide insights into the geometrical properties of cell boundaries.

Examples

>>> labels = np.array([[0, 1, 1, 0], [0, 1, 1, 0], [2, 2, 0, 0], [0, 0, 0, 0]])
>>> scale = [1.0, 1.0]
>>> border_dict = get_border_dict(labels, scale=scale, return_nnindex=True, return_nnvector=True)
>>> print(border_dict['pts'])
[[0., 1.], [0., 2.], [1., 1.], [2., 0.], [2., 1.]]
>>> print(border_dict['nn_index'])
[2, 2, 2, 1, 1]
celltraj.spatial.get_surface_points(msk, return_normals=False, return_curvature=False, knn=20, rscale=0.1, verbose=False)

Computes the surface points of a labeled mask and optionally calculates normals and curvature.

This function identifies the surface (border) points of a given labeled mask using segmentation techniques. It can also compute normals (perpendicular vectors to the surface) and curvature values at these points if requested.

Parameters:
  • msk (ndarray) – A 3D binary or labeled array representing the mask of regions of interest. Non-zero values represent the regions.

  • return_normals (bool, optional) – If True, computes and returns the normals at each surface point (default is False).

  • return_curvature (bool, optional) – If True, computes and returns the curvature at each surface point (default is False).

  • knn (int, optional) – The number of nearest neighbors to consider when calculating normals and curvature (default is 20).

Returns:

  • border_pts (ndarray) – A 2D array of shape (N, 3) containing the coordinates of the border points, where N is the number of border points found.

  • n (ndarray, optional) – A 2D array of shape (N, 3) containing the normal vectors at each border point. Only returned if return_normals is True.

  • c (ndarray, optional) – A 1D array of length N containing the curvature values at each border point. Only returned if return_curvature is True.

Notes

  • The function uses eigen decomposition on the neighborhood of each surface point to compute normals and curvature.

  • The normals are adjusted to face outward from the surface. If normals face inward, they are flipped.

  • Curvature is calculated as the ratio of the smallest eigenvalue to the sum of all eigenvalues, giving an estimate of local surface bending.

Examples

>>> msk = np.zeros((100, 100, 100), dtype=int)
>>> msk[40:60, 40:60, 40:60] = 1  # A cube in the center
>>> border_pts = get_surface_points(msk)
>>> border_pts.shape
(960, 3)
>>> border_pts, normals = get_surface_points(msk, return_normals=True)
>>> border_pts.shape, normals.shape
((960, 3), (960, 3))
>>> border_pts, normals, curvature = get_surface_points(msk, return_normals=True, return_curvature=True)
>>> border_pts.shape, normals.shape, curvature.shape
((960, 3), (960, 3), (960,))
celltraj.spatial.get_adhesive_displacement(border_dict, surf_force_function, eps, alpha=1.0, maxd=None, rmin=None, rmax=None, active_neighbor_states=numpy.array, active_displacement_states=numpy.array, symmetrize=True, **force_args)

Computes the adhesive displacement between cell surfaces using a specified surface force function.

This function calculates the displacement of cell surfaces based on adhesive forces. It uses the states and positions of neighboring cells to determine active interfaces and apply force-based displacements. Optionally, the displacements can be symmetrized to ensure consistency across cell borders.

Parameters:
  • border_dict (dict) – A dictionary containing border information, including: - ‘pts’: ndarray of shape (N, 3), coordinates of border points. - ‘nn_pts’: ndarray of shape (N, 3), coordinates of nearest neighbor points. - ‘states’: ndarray of shape (N,), states of the border points. - ‘nn_states’: ndarray of shape (N,), states of the nearest neighbor points. - ‘nn_inds’: ndarray of shape (N,), indices of the nearest neighbor points.

  • surf_force_function (callable) – A function that computes the surface force based on distance and other parameters. Should take distance, epsilon, and additional arguments as inputs.

  • eps (ndarray) – A 2D array where eps[i, j] represents the interaction strength between state i and state j.

  • alpha (float, optional) – A scaling factor for the displacement magnitude (default is 1.0).

  • maxd (float, optional) – The maximum allowed displacement. Displacements will be scaled if any calculated displacements exceed this value.

  • rmin (float, optional) – The minimum interaction distance. Displacements calculated from distances smaller than rmin will be set to rmin.

  • rmax (float, optional) – The maximum interaction distance. Displacements calculated from distances larger than rmax will be set to rmax.

  • active_neighbor_states (ndarray, optional) – An array specifying the states of neighbors that are active for interaction (default is np.array([1])).

  • active_displacement_states (ndarray, optional) – An array specifying the states of cells that are active for displacement (default is an empty array, which means all states are active).

  • symmetrize (bool, optional) – If True, the displacements are symmetrized to ensure consistency across borders (default is True).

  • **force_args (dict, optional) – Additional arguments to be passed to the surf_force_function.

Returns:

dr – A 2D array of shape (N, 3) representing the displacements of the border points.

Return type:

ndarray

Notes

  • The function filters out inactive or excluded states before computing the displacement.

  • Displacement is scaled using the surface force and optionally capped by maxd.

  • Symmetrization ensures that the displacement is consistent from both interacting cells’ perspectives.

Examples

>>> border_dict = {
...     'pts': np.random.rand(100, 3),
...     'nn_pts': np.random.rand(100, 3),
...     'states': np.random.randint(0, 2, 100),
...     'nn_states': np.random.randint(0, 2, 100),
...     'nn_inds': np.random.randint(0, 100, 100)
... }
>>> surf_force_function = lambda r, eps: -eps * (r - 1)
>>> eps = np.array([[0.1, 0.2], [0.2, 0.3]])
>>> dr = get_adhesive_displacement(border_dict, surf_force_function, eps, alpha=0.5)
>>> dr.shape
(100, 3)
celltraj.spatial.get_surface_displacement(border_dict, sts=None, c=None, n=None, alpha=1.0, maxd=None)

Computes the surface displacement of cells based on their curvature and normal vectors.

This function calculates the displacement of cell surfaces using the curvature values and normal vectors. The displacement can be scaled by a factor alpha, and optionally constrained by a maximum displacement value.

Parameters:
  • border_dict (dict) – A dictionary containing information about the cell borders, including: - ‘n’: ndarray of shape (N, 3), normal vectors at the border points. - ‘c’: ndarray of shape (N,), curvature values at the border points. - ‘states’: ndarray of shape (N,), states of the border points.

  • sts (ndarray, optional) – An array of scaling factors for each state, used to modify the curvature. If provided, sts is multiplied with the curvature values based on the state of each border point (default is None, meaning no scaling is applied).

  • c (ndarray, optional) – Curvature values at the border points. If None, it uses the curvature from border_dict (default is None).

  • n (ndarray, optional) – Normal vectors at the border points. If None, it uses the normal vectors from border_dict (default is None).

  • alpha (float, optional) – A scaling factor for the displacement magnitude (default is 1.0).

  • maxd (float, optional) – The maximum allowed displacement. If specified, the displacement is scaled to ensure it does not exceed this value.

Returns:

dx – A 2D array of shape (N, 3) representing the displacements of the border points.

Return type:

ndarray

Notes

  • The displacement is calculated as a product of curvature, normal vectors, and the scaling factor alpha.

  • If sts is provided, curvature values are scaled according to the states of the border points.

  • Displacement magnitude is capped by maxd if specified, ensuring that no displacement exceeds this value.

Examples

>>> border_dict = {
...     'n': np.random.rand(100, 3),
...     'c': np.random.rand(100),
...     'states': np.random.randint(0, 2, 100)
... }
>>> sts = np.array([1.0, 0.5])
>>> dx = get_surface_displacement(border_dict, sts=sts, alpha=0.2, maxd=0.1)
>>> dx.shape
(100, 3)
celltraj.spatial.get_surface_gradvariance(border_pts, dx_ot, knn=12, use_eigs=False, use_nonspatial=False)

Estimate local variation (squared gradient / roughness) of a boundary displacement field.

This function takes a set of boundary points and their displacements (e.g., from optimal transport between two surfaces) and computes a per-point measure of how rapidly the displacement magnitude varies along the surface.

Three related estimators are supported, selected via use_eigs and use_nonspatial:

  1. Eigen-based local variation (`use_eigs=True`): Uses the PyntCloud eigen-decomposition of the local displacement field within a k-nearest-neighbor (kNN) neighborhood to compute a scalar measure of variation based on the eigenvalues.

  2. Neighbor variance of displacement magnitude (`use_nonspatial=True`): Computes the variance of the displacement magnitudes within each point’s kNN neighborhood, ignoring surface geometry (purely neighborhood-based).

  3. Graph-based gradient magnitude (default): Builds a kNN graph on the boundary points, estimates a local tangent-frame basis, constructs gradient/divergence operators, and computes the squared gradient magnitude of the displacement magnitude field at each point.

Parameters:
  • border_pts (ndarray of shape (N, 3)) – Coordinates of N boundary points (typically 3D) on a cell or tissue surface.

  • dx_ot (ndarray of shape (N, 3)) – Displacement vectors associated with each boundary point, e.g. from an optimal transport (OT) match between two consecutive surfaces.

  • knn (int, optional) – Number of nearest neighbors to use when constructing local neighborhoods on the surface. Used in all modes (eigen-based, nonspatial, and graph-based). Default is 12.

  • use_eigs (bool, optional) – If True, use the eigen-decomposition–based estimator via PyntCloud: the displacement field is projected onto the local eigenvectors, and a scalar variation measure is computed from the eigenvalues. When True, this branch takes precedence over the graph-based default but can be overridden by use_nonspatial (see Notes).

  • use_nonspatial (bool, optional) – If True, compute the variance of the displacement magnitudes within each point’s kNN neighborhood, ignoring the explicit surface geometry and gradient operators. When True, this branch takes precedence over the graph-based default.

Returns:

dh – Scalar variation/roughness measure for each boundary point.

  • If use_eigs=True: dh[i] is proportional to the sum of local eigenvalues of the displacement field around point i (units depend on displacement scale).

  • If use_nonspatial=True: dh[i] is the variance of the displacement magnitude ||dx_ot|| in the kNN neighborhood of point i.

  • Otherwise: dh[i] is the squared gradient magnitude of ||dx_ot|| estimated in a local tangent frame via graph-based operators.

Return type:

ndarray of shape (N,)

Notes

  • This function assumes boundary points are sampled densely enough to make kNN-based local approximations meaningful.

  • The default branch (when both use_eigs and use_nonspatial are False) relies on helper functions:

    • knn_graph(pts, knn) to construct a sparse kNN adjacency.

    • estimate_basis(pts, edge_index) to estimate local tangent bases.

    • build_grad_div(border_pts, *basis, edge_index) to construct gradient and divergence operators.

  • Non-finite displacement magnitudes (||dx_ot||) are masked and do not contribute to the final estimates in the graph-based branch.

celltraj.spatial.get_surface_displacement_deviation(border_dict, border_pts_prev, exclude_states=None, n=None, knn=12, use_eigs=False, alpha=1.0, maxd=None)

Calculates the surface displacement deviation using optimal transport between current and previous border points.

This function computes the displacement of cell surface points based on deviations from previous positions. The displacement can be modified by normal vectors, filtered by specific states, and controlled by curvature or variance in displacement.

Parameters:
  • border_dict (dict) – A dictionary containing information about the current cell borders, including: - ‘pts’: ndarray of shape (N, 3), current border points. - ‘states’: ndarray of shape (N,), states of the border points.

  • border_pts_prev (ndarray) – A 2D array of shape (N, 3) containing the positions of border points from the previous time step.

  • exclude_states (array-like, optional) – A list or array of states to exclude from displacement calculations (default is None, meaning no states are excluded).

  • n (ndarray, optional) – Normal vectors at the border points. If None, normal vectors are calculated based on the optimal transport displacement (default is None).

  • knn (int, optional) – The number of nearest neighbors to consider when computing variance or eigen decomposition for curvature calculations (default is 12).

  • use_eigs (bool, optional) – If True, use eigen decomposition to calculate the displacement deviation; otherwise, use variance (default is False).

  • alpha (float, optional) – A scaling factor for the displacement magnitude (default is 1.0).

  • maxd (float, optional) – The maximum allowed displacement. If specified, the displacement is scaled to ensure it does not exceed this value (default is None).

Returns:

dx – A 2D array of shape (N, 3) representing the displacements of the border points.

Return type:

ndarray

Notes

  • The function uses optimal transport to calculate deviations between current and previous border points.

  • The surface displacement deviation is inspired by the “mother of all non-linearities”– the Kardar-Parisi-Zhang non-linear surface growth universality class.

  • Displacement deviations are scaled by the normal vectors and can be controlled by alpha and capped by maxd.

  • If use_eigs is True, eigen decomposition of the displacement field is used to calculate deviations, otherwise variance is used.

  • Excludes displacements for specified states, if exclude_states is provided.

Examples

>>> border_dict = {
...     'pts': np.random.rand(100, 3),
...     'states': np.random.randint(0, 2, 100)
... }
>>> border_pts_prev = np.random.rand(100, 3)
>>> dx = get_surface_displacement_deviation(border_dict, border_pts_prev, exclude_states=[0], alpha=0.5, maxd=0.1)
>>> dx.shape
(100, 3)
celltraj.spatial.get_flux_displacement(border_dict, border_features=None, flux_function=None, exclude_states=None, n=None, fmeans=0.0, fsigmas=0.0, random_seed=None, alpha=1.0, maxd=None, **flux_function_args)

Calculates the displacement of border points using flux information.

This function computes the displacement of border points by applying a flux function or random sampling based on mean and standard deviation values. The displacements can be controlled by normal vectors, excluded for certain states, and scaled to a maximum displacement.

Parameters:
  • border_dict (dict) – A dictionary containing information about the current cell borders, including: - ‘n’: ndarray of shape (N, 3), normal vectors at the border points. - ‘states’: ndarray of shape (N,), states of the border points.

  • border_features (ndarray, optional) – Features at the border points used as input to the flux function (default is None).

  • flux_function (callable, optional) – A function that takes border_features and additional arguments to compute mean (fmeans) and standard deviation (fsigmas) of the flux at each border point (default is None, meaning random sampling is used).

  • exclude_states (array-like, optional) – A list or array of states to exclude from displacement calculations (default is None, meaning no states are excluded).

  • n (ndarray, optional) – Normal vectors at the border points. If None, normal vectors are taken from border_dict[‘n’] (default is None).

  • fmeans (float or array-like, optional) – Mean flux value(s) for random sampling (default is 0.). If flux_function is provided, this value is ignored.

  • fsigmas (float or array-like, optional) – Standard deviation of flux value(s) for random sampling (default is 0.). If flux_function is provided, this value is ignored.

  • random_seed (int, optional) – Seed for the random number generator to ensure reproducibility (default is None).

  • alpha (float, optional) – A scaling factor for the displacement magnitude (default is 1.0).

  • maxd (float, optional) – The maximum allowed displacement. If specified, the displacement is scaled to ensure it does not exceed this value (default is None).

  • **flux_function_args (dict, optional) – Additional arguments to pass to the flux_function.

Returns:

dx – A 2D array of shape (N, 3) representing the displacements of the border points.

Return type:

ndarray

Notes

  • The function can use a flux function to calculate displacements based on border features or perform random sampling with specified mean and standard deviation values.

  • Displacement deviations are scaled by normal vectors and can be controlled by alpha and capped by maxd.

  • Excludes displacements for specified states, if exclude_states is provided.

  • The random number generator can be seeded for reproducibility using random_seed.

Examples

>>> border_dict = {
...     'n': np.random.rand(100, 3),
...     'states': np.random.randint(0, 2, 100)
... }
>>> dx = get_flux_displacement(border_dict, fmeans=0.5, fsigmas=0.1, random_seed=42, alpha=0.8, maxd=0.2)
>>> dx.shape
(100, 3)
celltraj.spatial.get_ot_dx(pts0, pts1, return_dx=True, return_cost=False)

Computes the optimal transport (OT) displacement and cost between two sets of points.

This function calculates the optimal transport map between two sets of points pts0 and pts1 using the Earth Mover’s Distance (EMD). It returns the indices of the optimal transport matches and the displacement vectors, as well as the transport cost if specified.

Parameters:
  • pts0 (ndarray) – A 2D array of shape (N, D), representing the first set of points, where N is the number of points and D is the dimensionality.

  • pts1 (ndarray) – A 2D array of shape (M, D), representing the second set of points, where M is the number of points and D is the dimensionality.

  • return_dx (bool, optional) – If True, returns the displacement vectors between matched points (default is True).

  • return_cost (bool, optional) – If True, returns the total transport cost (default is False).

Returns:

  • inds_ot (ndarray) – A 1D array of shape (N,), representing the indices of the points in pts1 that are matched to the points in pts0 according to the optimal transport map.

  • dx (ndarray, optional) – A 2D array of shape (N, D), representing the displacement vectors from the points in pts0 to the matched points in pts1. Returned only if return_dx is True.

  • cost (float, optional) – The total optimal transport cost, calculated as the sum of the transport cost between matched points. Returned only if return_cost is True.

Notes

  • The function uses the Earth Mover’s Distance (EMD) for computing the optimal transport map, which minimizes the cost of moving mass from pts0 to pts1.

  • The cost is computed as the sum of the pairwise distances weighted by the transport plan.

  • Displacement vectors are computed as the difference between points in pts0 and their matched points in pts1.

Examples

>>> pts0 = np.array([[0, 0], [1, 1], [2, 2]])
>>> pts1 = np.array([[0, 1], [1, 0], [2, 1]])
>>> inds_ot, dx, cost = get_ot_dx(pts0, pts1, return_dx=True, return_cost=True)
>>> inds_ot
array([0, 1, 2])
>>> dx
array([[ 0, -1],
       [ 0,  1],
       [ 0,  1]])
>>> cost
1.0
celltraj.spatial.get_ot_displacement(border_dict, border_dict_prev, parent_index=None)

Computes the optimal transport (OT) displacement between two sets of boundary points.

This function calculates the optimal transport displacements between the points in the current boundary (border_dict) and the points in the previous boundary (border_dict_prev). It finds the optimal matches and computes the displacement vectors for each point.

Parameters:
  • border_dict (dict) – A dictionary containing the current boundary points and related information. Expected keys include: - ‘index’: ndarray of shape (N,), unique labels of current boundary points. - ‘pts’: ndarray of shape (N, D), coordinates of the current boundary points.

  • border_dict_prev (dict) – A dictionary containing the previous boundary points and related information. Expected keys include: - ‘index’: ndarray of shape (M,), unique labels of previous boundary points. - ‘pts’: ndarray of shape (M, D), coordinates of the previous boundary points.

  • parent_index (ndarray, optional) – An array of unique labels (indices) to use for matching previous boundary points. If not provided, index1 from border_dict will be used to match with border_dict_prev.

Returns:

  • inds_ot (ndarray) – A 1D array containing the indices of the optimal transport matches for the current boundary points from the previous boundary points.

  • dxs_ot (ndarray) – A 2D array of shape (N, D), representing the displacement vectors from the current boundary points to the matched previous boundary points.

Notes

  • The function uses the get_ot_dx function to compute the optimal transport match and displacement between boundary points.

  • If parent_index is not provided, it defaults to using the indices of the current boundary points (index1).

Examples

>>> border_dict = {
...     'index': np.array([1, 2, 3]),
...     'pts': np.array([[0, 0], [1, 1], [2, 2]])
... }
>>> border_dict_prev = {
...     'index': np.array([1, 2, 3]),
...     'pts': np.array([[0, 1], [1, 0], [2, 1]])
... }
>>> inds_ot, dxs_ot = get_ot_displacement(border_dict, border_dict_prev)
>>> inds_ot
array([0, 0, 0])
>>> dxs_ot
array([[ 0, -1],
       [ 0,  1],
       [ 0,  1]])
celltraj.spatial.get_labels_fromborderdict(border_dict, labels_shape, active_states=None, surface_labels=None, connected=True, random_seed=None)

Generates a label mask from a dictionary of border points and associated states.

This function creates a 3D label array by identifying regions enclosed by the boundary points in border_dict. It assigns unique labels to each region based on the indices of the border points.

Parameters:
  • border_dict (dict) – A dictionary containing the border points and associated information. Expected keys include: - ‘pts’: ndarray of shape (N, D), coordinates of the border points. - ‘index’: ndarray of shape (N,), labels for each border point. - ‘states’: ndarray of shape (N,), states associated with each border point.

  • labels_shape (tuple of ints) – The shape of the output labels array.

  • active_states (array-like, optional) – A list or array of states to include in the labeling. If None, all unique states in border_dict[‘states’] are used.

  • surface_labels (ndarray, optional) – A pre-existing label array to use as a base. Regions with non-zero values in this array will retain their labels.

  • connected (bool, optional) – If True, ensures that labeled regions are connected. Uses the largest connected component labeling method.

  • random_seed (int, optional) – A seed for the random number generator to ensure reproducibility.

Returns:

labels – An array of the same shape as labels_shape with labeled regions. Each unique region enclosed by border points is assigned a unique label.

Return type:

ndarray

Notes

  • This function utilizes convex hull and Delaunay triangulation to determine the regions enclosed by the border points.

  • It can be used to generate labels for 3D volumes, based on the locations and states of border points.

  • The function includes options for randomization and enforcing connectivity of labeled regions.

Examples

>>> border_dict = {
...     'pts': np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]),
...     'index': np.array([1, 1, 2]),
...     'states': np.array([1, 1, 2])
... }
>>> labels_shape = (3, 3, 3)
>>> labels = get_labels_fromborderdict(border_dict, labels_shape)
>>> print(labels)
array([[[1, 1, 0],
        [1, 1, 0],
        [0, 0, 0]],
       [[1, 1, 0],
        [1, 1, 0],
        [0, 0, 0]],
       [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]]])
celltraj.spatial.get_volconstraint_com(border_pts, target_volume, max_iter=1000, converror=0.05, dc=1.0)

Adjusts the positions of boundary points to achieve a target volume using a centroid-based method.

This function iteratively adjusts the positions of boundary points to match a specified target volume. The adjustment is done by moving points along the direction from the centroid to the points, scaled by the difference between the current and target volumes.

Parameters:
  • border_pts (ndarray) – An array of shape (N, 3) representing the coordinates of the boundary points.

  • target_volume (float) – The desired volume to be achieved.

  • max_iter (int, optional) – Maximum number of iterations to perform. Default is 1000.

  • converror (float, optional) – Convergence error threshold. Iterations stop when the relative volume error is below this value. Default is 0.05.

  • dc (float, optional) – A scaling factor for the displacement calculated in each iteration. Default is 1.0.

Returns:

border_pts – An array of shape (N, 3) representing the adjusted coordinates of the boundary points that approximate the target volume.

Return type:

ndarray

Notes

  • The method assumes a 3D convex hull can be formed by the points, which is adjusted iteratively.

  • The convergence is based on the relative difference between the current volume and the target volume.

  • If the boundary points are collinear in any dimension, the method adjusts them to ensure a valid convex hull.

Examples

>>> border_pts = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]])
>>> target_volume = 10.0
>>> adjusted_pts = get_volconstraint_com(border_pts, target_volume)
>>> print(adjusted_pts)
array([[ ... ]])  # Adjusted coordinates to approximate the target volume
celltraj.spatial.constrain_volume(border_dict, target_vols, exclude_states=None, **volconstraint_args)

Adjusts the positions of boundary points to achieve target volumes for different regions.

This function iterates through different regions identified by their indices and adjusts the boundary points to match specified target volumes. The adjustments are performed using the get_volconstraint_com function, which modifies the boundary points to achieve the desired volume.

Parameters:
  • border_dict (dict) – A dictionary containing boundary information, typically with keys: - ‘pts’: ndarray of shape (N, 3), coordinates of the boundary points. - ‘index’: ndarray of shape (N,), indices identifying the region each point belongs to. - ‘n’: ndarray of shape (N, 3), normals at the boundary points.

  • target_vols (dict or ndarray) – A dictionary or array where each key or index corresponds to a region index, and the value is the target volume for that region.

  • exclude_states (array-like, optional) – States to be excluded from volume adjustment. If not provided, all states will be adjusted. Default is None.

  • **volconstraint_args (dict, optional) – Additional arguments to pass to the get_volconstraint_com function, such as maximum iterations or convergence criteria.

Returns:

border_pts_c – An array of shape (N, 3) representing the adjusted coordinates of the boundary points.

Return type:

ndarray

Notes

  • This function uses volume constraints to adjust the morphology of different regions based on specified target volumes.

  • The regions are identified by the ‘index’ values in border_dict.

  • Points belonging to excluded states are not adjusted.

Examples

>>> border_dict = {'pts': np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]),
                   'index': np.array([1, 1, 2]),
                   'n': np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]])}
>>> target_vols = {1: 10.0, 2: 5.0}
>>> adjusted_pts = constrain_volume(border_dict, target_vols)
>>> print(adjusted_pts)
array([[ ... ]])  # Adjusted coordinates for regions with target volumes
celltraj.spatial.get_yukawa_force(r, eps, R=1.0)

Computes the Yukawa force for a given set of distances.

The Yukawa force is a screened Coulomb force often used to describe interactions in plasmas and other systems with screened potentials. This function calculates the Yukawa force based on the provided distances, interaction strength, and screening length.

Parameters:
  • r (array-like or float) – The distance(s) at which to calculate the Yukawa force. Can be a single float or an array of distances.

  • eps (float) – The interaction strength (or potential strength) parameter, determining the amplitude of the force.

  • R (float, optional) – The screening length parameter, which determines how quickly the force decays with distance. Default is 1.

Returns:

force – The computed Yukawa force at each distance provided in r. The shape of the output matches the shape of r.

Return type:

array-like or float

Examples

>>> distances = np.array([0.5, 1.0, 1.5])
>>> interaction_strength = 2.0
>>> screening_length = 1.0
>>> forces = get_yukawa_force(distances, interaction_strength, R=screening_length)
>>> print(forces)
[4. e+00 1.47151776e+00 4.48168907e-01]

Notes

  • The Yukawa force is computed using the formula: force = eps * exp(-r / R) * (r + R) / (R * r^2), where eps is the interaction strength and R is the screening length.

  • The function handles both scalar and array inputs for r.

celltraj.spatial.get_LJ_force(r, eps, R=1.0, max_repulsion=True)

Computes the Lennard-Jones (LJ) force for a given set of distances.

The Lennard-Jones potential models interactions between a pair of neutral atoms or molecules, capturing both the attractive and repulsive forces. This function calculates the LJ force based on the provided distances, interaction strength, and characteristic distance.

Parameters:
  • r (array-like or float) – The distance(s) at which to calculate the Lennard-Jones force. Can be a single float or an array of distances.

  • eps (float) – The depth of the potential well, representing the strength of the interaction.

  • R (float, optional) – The characteristic distance parameter, which influences the distance at which the potential well occurs. Default is 1.

  • max_repulsion (bool, optional) – If True, the force is limited to a maximum repulsion by setting distances below the sigma value to sigma, where sigma is the distance at which the potential crosses zero (point of maximum repulsion). Default is True.

Returns:

force – The computed Lennard-Jones force at each distance provided in r. The shape of the output matches the shape of r.

Return type:

array-like or float

Examples

>>> distances = np.array([0.5, 1.0, 1.5])
>>> interaction_strength = 1.0
>>> characteristic_distance = 1.0
>>> forces = get_LJ_force(distances, interaction_strength, R=characteristic_distance)
>>> print(forces)
[ 0.  -24.         0.7410312]

Notes

  • The Lennard-Jones force is computed using the formula: force = 48 * eps * [(sigma^12 / r^13) - 0.5 * (sigma^6 / r^7)], where eps is the interaction strength and sigma is the effective particle diameter, calculated as sigma = R / 2^(1/6).

  • The max_repulsion option ensures that no distances smaller than sigma are considered, effectively limiting the maximum repulsive force.

  • This function can handle both scalar and array inputs for r.

celltraj.spatial.get_morse_force(r, eps, R=1.0, L=4.0)

Computes the Morse force for a given set of distances.

The Morse potential is used to model the interaction between a pair of atoms or molecules, capturing both the attractive and repulsive forces more realistically than the Lennard-Jones potential. This function calculates the Morse force based on the provided distances, interaction strength, characteristic distance, and interaction range.

Parameters:
  • r (array-like or float) – The distance(s) at which to calculate the Morse force. Can be a single float or an array of distances.

  • eps (float) – The depth of the potential well, representing the strength of the interaction.

  • R (float, optional) – The equilibrium distance where the potential reaches its minimum. Default is 1.

  • L (float, optional) – The width of the potential well, determining the range of the interaction. A larger value of L indicates a narrower well, meaning the potential changes more rapidly with distance. Default is 4.

Returns:

force – The computed Morse force at each distance provided in r. The shape of the output matches the shape of r.

Return type:

array-like or float

Examples

>>> distances = np.array([0.8, 1.0, 1.2])
>>> interaction_strength = 2.0
>>> equilibrium_distance = 1.0
>>> interaction_range = 4.0
>>> forces = get_morse_force(distances, interaction_strength, R=equilibrium_distance, L=interaction_range)
>>> print(forces)
[ 1.17328042  0.         -0.63212056]

Notes

  • The Morse force is derived from the Morse potential and is calculated using the formula: force = eps * [exp(-2 * (r - R) / L) - exp(-(r - R) / L)], where eps is the interaction strength, R is the equilibrium distance, and L is the interaction range.

  • This function can handle both scalar and array inputs for r.

celltraj.spatial.get_secreted_ligand_density(msk, scale=2.0, zscale=1.0, npad=None, indz_bm=0, secretion_rate=1.0, D=None, micron_per_pixel=1.0, visual=False)

Calculate the spatial distribution of secreted ligand density in a 3D tissue model.

This function simulates the diffusion and absorption of secreted ligands in a 3D volume defined by a binary mask. It uses finite element methods to solve the diffusion equation for ligand concentration, taking into account secretion from cell surfaces and absorption at boundaries.

Parameters:
  • msk (ndarray) – A 3D binary mask representing the tissue, where non-zero values indicate the presence of cells.

  • scale (float, optional) – The scaling factor for spatial resolution in the x and y dimensions. Default is 2.

  • zscale (float, optional) – The scaling factor for spatial resolution in the z dimension. Default is 1.

  • npad (array-like of int, optional) – Number of pixels to pad the mask in each dimension. Default is None, implying no padding.

  • indz_bm (int, optional) – The index for the basal membrane in the z-dimension, where diffusion starts. Default is 0.

  • secretion_rate (float or array-like, optional) – The rate of ligand secretion from the cell surfaces. Can be a scalar or array for different cell types. Default is 1.0.

  • D (float, optional) – The diffusion coefficient for the ligand. If None, it is set to a default value based on the pixel size. Default is None.

  • micron_per_pixel (float, optional) – The conversion factor from pixels to microns. Default is 1.

  • visual (bool, optional) – If True, generates visualizations of the cell borders and diffusion process. Default is False.

Returns:

vdist – A 3D array representing the steady-state concentration of the secreted ligand in the tissue volume.

Return type:

ndarray

Examples

>>> tissue_mask = np.random.randint(0, 2, size=(100, 100, 50))
>>> ligand_density = get_secreted_ligand_density(tissue_mask, scale=2.5, zscale=1.2, secretion_rate=0.8)
>>> print(ligand_density.shape)
(100, 100, 50)

Notes

  • This function uses fipy for solving the diffusion equation and skimage.segmentation.find_boundaries for identifying cell borders.

  • The function includes various options for handling different boundary conditions, cell shapes, and secretion rates.

celltraj.spatial.get_flux_ligdist(vdist, cmean=1.0, csigma=0.5, center=True)

Calculate the mean and standard deviation of flux values based on ligand distribution.

This function computes the flux mean and standard deviation for a given ligand distribution, using specified parameters for the mean and scaling factor for the standard deviation. Optionally, it can center the mean flux to ensure the overall flux is balanced.

Parameters:
  • vdist (ndarray) – A 3D array representing the ligand concentration distribution in a tissue volume.

  • cmean (float, optional) – A scaling factor for the mean flux. Default is 1.0.

  • csigma (float, optional) – A scaling factor for the standard deviation of the flux. Default is 0.5.

  • center (bool, optional) – If True, centers the mean flux distribution around zero by subtracting the overall mean. Default is True.

Returns:

  • fmeans (ndarray) – A 3D array representing the mean flux values based on the ligand distribution.

  • fsigmas (ndarray) – A 3D array representing the standard deviation of flux values based on the ligand distribution.

Examples

>>> ligand_distribution = np.random.random((100, 100, 50))
>>> mean_flux, sigma_flux = get_flux_ligdist(ligand_distribution, cmean=1.2, csigma=0.8)
>>> print(mean_flux.shape, sigma_flux.shape)
(100, 100, 50) (100, 100, 50)

Notes

  • The function uses the absolute value of vdist to calculate the standard deviation of the flux.

  • Centering the mean flux helps in ensuring there is no net flux imbalance across the tissue volume.

celltraj.spatial.get_border_properties(cell_labels, surfaces=None, cell_states=None, state_ids=None, surface_states=None, cell_labels_next=None, cell_labels_prev=None, lin_next=None, lin_prev=None, vdist=None, border_scale=1.0, radius=2.0, order=1, return_border_properties_list=False, verbose=False)

Calculate geometric and physical properties of cell borders, with optional tracking between frames and surface contact details.

This function computes properties of cell borders based on cell_labels, surface contacts, and multipole moments up to a specified order. It supports tracking cell border displacement across frames using optional next and previous frame labels (cell_labels_next, cell_labels_prev). Outputs include multipole moments and border displacements useful in characterizing cell interactions and tracking cell behaviors.

Parameters:
  • cell_labels (ndarray) – Array of labels identifying distinct cells within the domain.

  • surfaces (list of ndarrays, optional) – List of binary masks indicating surface layers adjacent to cells (e.g., membranes or other boundaries). Each is assigned a unique identifier.

  • cell_states (ndarray of int, optional) – Array specifying a state for each cell in cell_labels. Defaults to 1 if not provided.

  • surface_states (ndarray of int, optional) – Array of states corresponding to each surface in surfaces. These states must not overlap with cell_states.

  • cell_labels_next (ndarray, optional) – Label array for the next frame to track cell borders over time.

  • cell_labels_prev (ndarray, optional) – Label array for the previous frame, used for backward tracking of cells.

  • lin_next (list of lists, optional) – Mapping of cells in cell_labels to corresponding cells in cell_labels_next. Each entry contains IDs of linked cells in the next frame.

  • lin_prev (list of lists, optional) – Mapping of cells in cell_labels to corresponding cells in cell_labels_prev, used for backward tracking.

  • border_scale (float, optional) – Resolution in microns applied to border point extraction (default is 1.0).

  • radius (float, optional) – Radius in pixels for calculating border properties such as contact neighbors (default is 2.0).

  • order (int, optional) – Order of multipole moments to calculate for each border contact (default is 1).

  • return_border_properties_list (bool, optional) – If True, returns a list of property names for multipole moments alongside the border dictionary.

Returns:

  • border_dict (dict) – Dictionary containing calculated properties of each cell’s border, including:

    • pts : Array of border points.

    • index : Label of each cell at the border.

    • nn_states : Neighboring cell states at each border point.

    • contact_properties : Array of multipole moment properties calculated up to order.

    • border_dx_next, border_dx_prev : Displacements of each border in the next and previous frames, if applicable.

    • dx_next_properties, dx_prev_properties : Arrays of multipole moments based on border displacement for next and previous frames.

  • border_properties_list (list of str, optional) – List of property names for contact_properties array if return_border_properties_list is True.

Notes

  • Multipole Moment Calculation: Moments up to the specified order are computed based on border charges (representing contact fraction) for each border point.

  • Cell Tracking: When provided with cell_labels_next or cell_labels_prev, the function calculates optimal transport (OT) vectors to track border movement between frames.

Examples

Calculate properties of cell borders and multipole moments with next-frame tracking:

>>> border_dict, property_list = get_border_properties(
...     cell_labels=my_cell_labels, surfaces=my_surfaces, cell_states=my_states,
...     cell_labels_next=my_next_frame_labels, lin_next=my_next_frame_links,
...     border_scale=0.8, radius=1.5, order=2, return_border_properties_list=True
... )
celltraj.spatial.get_boundary_multipole_moments(border_pts, border_charge, order=1, return_moments=False)

Compute normalized radial magnitudes of spherical multipole moments for a discrete boundary charge distribution.

This function uses the multipoles package to perform a multipole expansion of the scalar charges located at the coordinates border_pts. It returns, for each multipole order ℓ from 0 up to order, the magnitude of the vector of raw (ℓ,m) moments, normalized by the number of charges and by (2ℓ+1).

Parameters:
  • border_pts (ndarray of shape (N, D)) – Coordinates of N boundary points in D dimensions (typically D=2 or 3).

  • border_charge (ndarray of shape (N,)) – Scalar “charge” values assigned to each boundary point.

  • order (int, optional) – Maximum multipole order ℓ to compute (default is 1, computing monopole and dipole).

  • return_moments (bool, optional) – If True, also return the full set of raw multipole moments for each ℓ and m.

Returns:

  • magnitudes (ndarray of shape (order+1,)) – For each ℓ = 0..order, the normalized radial magnitude of the multipole moments: [

    text{magnitude}_ell = frac{1}{(2ell+1),N} , bigllVert , M_{ell, m}bigrrVert_{m=-ell..ell}

    ]

  • moments (dict, optional) – Only returned if return_moments=True. A nested dictionary moments[ℓ][m] containing the raw complex multipole moment for each order ℓ and degree m.

Notes