synapse_net.distance_measurements

  1import os
  2import multiprocessing as mp
  3from typing import Dict, List, Optional, Tuple, Union
  4
  5import numpy as np
  6
  7from concurrent import futures
  8from scipy.ndimage import distance_transform_edt, binary_dilation
  9
 10from skimage.measure import regionprops
 11from skimage.draw import line_nd
 12from tqdm import tqdm
 13
 14try:
 15    import skfmm
 16except ImportError:
 17    skfmm = None
 18
 19
 20def compute_geodesic_distances(
 21    segmentation: np.ndarray,
 22    distance_to: np.ndarray,
 23    resolution: Optional[Union[int, float, Tuple[int, int, int]]] = None,
 24    unsigned: bool = True,
 25) -> np.ndarray:
 26    """Compute the geodesic distances between a segmentation and a distance target.
 27
 28    This function require scikit-fmm to be installed.
 29
 30    Args:
 31        segmentation: The binary segmentation.
 32        distance_to: The binary distance target.
 33        resolution: The voxel size of the data, used to scale the distances.
 34        unsigned: Whether to return the unsigned or signed distances.
 35
 36    Returns:
 37        Array with the geodesic distance values.
 38    """
 39    assert skfmm is not None, "Please install scikit-fmm to use compute_geodesic_distance."
 40
 41    invalid = segmentation == 0
 42    input_ = np.ma.array(segmentation.copy(), mask=invalid)
 43    input_[distance_to] = 0
 44
 45    if resolution is None:
 46        dx = 1.0
 47    elif isinstance(resolution, (int, float)):
 48        dx = float(resolution)
 49    else:
 50        assert len(resolution) == segmentation.ndim
 51        dx = resolution
 52
 53    distances = skfmm.distance(input_, dx=dx).data
 54    distances[distances == 0] = np.inf
 55    distances[distance_to] = 0
 56
 57    if unsigned:
 58        distances = np.abs(distances)
 59
 60    return distances
 61
 62
 63def _compute_boundary_distances(segmentation, resolution, n_threads):
 64
 65    seg_ids = np.unique(segmentation)[1:]
 66    n = len(seg_ids)
 67
 68    pairwise_distances = np.zeros((n, n))
 69    ndim = segmentation.ndim
 70    end_points1 = np.zeros((n, n, ndim), dtype="int")
 71    end_points2 = np.zeros((n, n, ndim), dtype="int")
 72
 73    properties = regionprops(segmentation)
 74    properties = {prop.label: prop for prop in properties}
 75
 76    def compute_distances_for_object(i):
 77
 78        seg_id = seg_ids[i]
 79        distances, indices = distance_transform_edt(segmentation != seg_id, return_indices=True, sampling=resolution)
 80
 81        for j in range(len(seg_ids)):
 82            if i >= j:
 83                continue
 84
 85            ngb_id = seg_ids[j]
 86            prop = properties[ngb_id]
 87
 88            bb = prop.bbox
 89            offset = np.array(bb[:ndim])
 90            if ndim == 2:
 91                bb = np.s_[bb[0]:bb[2], bb[1]:bb[3]]
 92            else:
 93                bb = np.s_[bb[0]:bb[3], bb[1]:bb[4], bb[2]:bb[5]]
 94
 95            mask = segmentation[bb] == ngb_id
 96            ngb_dist, ngb_index = distances[bb].copy(), indices[(slice(None),) + bb]
 97            ngb_dist[~mask] = np.inf
 98            min_point_ngb = np.unravel_index(np.argmin(ngb_dist), shape=mask.shape)
 99
100            min_dist = ngb_dist[min_point_ngb]
101
102            min_point = tuple(ind[min_point_ngb] for ind in ngb_index)
103            pairwise_distances[i, j] = min_dist
104
105            end_points1[i, j] = min_point
106            min_point_ngb = [off + minp for off, minp in zip(offset, min_point_ngb)]
107            end_points2[i, j] = min_point_ngb
108
109    n_threads = mp.cpu_count() if n_threads is None else n_threads
110    with futures.ThreadPoolExecutor(n_threads) as tp:
111        list(tqdm(
112            tp.map(compute_distances_for_object, range(n)), total=n, desc="Compute boundary distances"
113        ))
114
115    return pairwise_distances, end_points1, end_points2, seg_ids
116
117
118def measure_pairwise_object_distances(
119    segmentation: np.ndarray,
120    distance_type: str = "boundary",
121    resolution: Optional[Tuple[int, int, int]] = None,
122    n_threads: Optional[int] = None,
123    save_path: Optional[os.PathLike] = None,
124) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
125    """Compute the pairwise distances between all objects within a segmentation.
126
127    Args:
128        segmentation: The input segmentation.
129        distance_type: The type of distance to compute. Only 'boundary', the distance between
130            the boundary / surface of the objects, is supported.
131        resolution: The resolution / pixel size of the data.
132        n_threads: The number of threads for parallelizing the distance computation.
133        save_path: Path for saving the measurement results in numpy zipped format.
134
135    Returns:
136        The pairwise object distances.
137        The 'left' endpoint coordinates of the distances.
138        The 'right' endpoint coordinates of the distances.
139        The segmentation id pairs of the distances.
140    """
141    if distance_type != "boundary":
142        raise NotImplementedError(f"Distance type '{distance_type}' is not supported, only 'boundary'.")
143    distances, endpoints1, endpoints2, seg_ids = _compute_boundary_distances(segmentation, resolution, n_threads)
144
145    if save_path is not None:
146        np.savez(
147            save_path,
148            distances=distances,
149            endpoints1=endpoints1,
150            endpoints2=endpoints2,
151            seg_ids=seg_ids,
152        )
153
154    return distances, endpoints1, endpoints2, seg_ids
155
156
157def _compute_seg_object_distances(segmentation, segmented_object, resolution, verbose):
158    distance_map, indices = distance_transform_edt(segmented_object == 0, return_indices=True, sampling=resolution)
159
160    seg_ids = np.unique(segmentation)[1:].tolist()
161    n = len(seg_ids)
162
163    distances = np.zeros(n)
164    ndim = segmentation.ndim
165    endpoints1 = np.zeros((n, ndim), dtype="int")
166    endpoints2 = np.zeros((n, ndim), dtype="int")
167
168    object_ids = []
169    # We use this so often, it should be refactored.
170    props = regionprops(segmentation)
171    for prop in tqdm(props, disable=not verbose):
172        bb = prop.bbox
173        offset = np.array(bb[:ndim])
174        if ndim == 2:
175            bb = np.s_[bb[0]:bb[2], bb[1]:bb[3]]
176        else:
177            bb = np.s_[bb[0]:bb[3], bb[1]:bb[4], bb[2]:bb[5]]
178
179        label = prop.label
180        mask = segmentation[bb] == label
181
182        dist, idx = distance_map[bb].copy(), indices[(slice(None),) + bb]
183        dist[~mask] = np.inf
184
185        min_dist_coord = np.argmin(dist)
186        min_dist_coord = np.unravel_index(min_dist_coord, mask.shape)
187        distance = dist[min_dist_coord]
188
189        object_coord = tuple(idx_[min_dist_coord] for idx_ in idx)
190        object_id = segmented_object[object_coord]
191        assert object_id != 0
192
193        seg_idx = seg_ids.index(label)
194        distances[seg_idx] = distance
195        endpoints1[seg_idx] = object_coord
196
197        min_dist_coord = [off + minc for off, minc in zip(offset, min_dist_coord)]
198        endpoints2[seg_idx] = min_dist_coord
199
200        object_ids.append(object_id)
201
202    return distances, endpoints1, endpoints2, np.array(seg_ids), np.array(object_ids)
203
204
205def measure_segmentation_to_object_distances(
206    segmentation: np.ndarray,
207    segmented_object: np.ndarray,
208    distance_type: str = "boundary",
209    resolution: Optional[Tuple[int, int, int]] = None,
210    save_path: Optional[os.PathLike] = None,
211    verbose: bool = False,
212) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
213    """Compute the distance betwen all objects in a segmentation and another object.
214
215    Args:
216        segmentation: The input segmentation.
217        segmented_object: The segmented object.
218        distance_type: The type of distance to compute. Only 'boundary', the distance between
219            the boundary / surface of the objects, is supported.
220        resolution: The resolution / pixel size of the data.
221        save_path: Path for saving the measurement results in numpy zipped format.
222        verbose: Whether to print the progress of the distance computation.
223
224    Returns:
225        The segmentation to object distances.
226        The 'left' endpoint coordinates of the distances.
227        The 'right' endpoint coordinates of the distances.
228        The segmentation ids corresponding to the distances.
229    """
230    if distance_type == "boundary":
231        distances, endpoints1, endpoints2, seg_ids, object_ids = _compute_seg_object_distances(
232            segmentation, segmented_object, resolution, verbose
233        )
234        assert len(distances) == len(endpoints1) == len(endpoints2) == len(seg_ids) == len(object_ids)
235    else:
236        raise NotImplementedError
237
238    if save_path is not None:
239        np.savez(
240            save_path,
241            distances=distances,
242            endpoints1=endpoints1,
243            endpoints2=endpoints2,
244            seg_ids=seg_ids,
245            object_ids=object_ids,
246        )
247    return distances, endpoints1, endpoints2, seg_ids
248
249
250def _extract_nearest_neighbors(pairwise_distances, seg_ids, n_neighbors, remove_duplicates=True):
251    distance_matrix = pairwise_distances.copy()
252
253    # Set the diagonal (distance to self) to infinity.
254    distance_matrix[np.diag_indices(len(distance_matrix))] = np.inf
255    # Mirror the distances.
256    # (We only compute upper triangle, but need to take all distances into account here)
257    tril_indices = np.tril_indices_from(distance_matrix)
258    distance_matrix[tril_indices] = distance_matrix.T[tril_indices]
259
260    neighbor_distances = np.sort(distance_matrix, axis=1)[:, :n_neighbors]
261    neighbor_indices = np.argsort(distance_matrix, axis=1)[:, :n_neighbors]
262
263    pairs = []
264    for i, (dists, inds) in enumerate(zip(neighbor_distances, neighbor_indices)):
265        seg_id = seg_ids[i]
266        ngb_ids = [seg_ids[j] for j, dist in zip(inds, dists) if np.isfinite(dist)]
267        pairs.extend([[min(seg_id, ngb_id), max(seg_id, ngb_id)] for ngb_id in ngb_ids])
268
269    pairs = np.array(pairs)
270    pairs = np.sort(pairs, axis=1)
271    if remove_duplicates:
272        pairs = np.unique(pairs, axis=0)
273    return pairs
274
275
276def load_distances(
277    measurement_path: os.PathLike
278) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
279    """Load the saved distacnes from a zipped numpy file.
280
281    Args:
282        measurement_path: The path where the distances where saved.
283
284    Returns:
285        The segmentation to object distances.
286        The 'left' endpoint coordinates of the distances.
287        The 'right' endpoint coordinates of the distances.
288        The segmentation ids corresponding to the distances.
289    """
290    auto_dists = np.load(measurement_path)
291    distances, seg_ids = auto_dists["distances"], list(auto_dists["seg_ids"])
292    endpoints1, endpoints2 = auto_dists["endpoints1"], auto_dists["endpoints2"]
293    return distances, endpoints1, endpoints2, seg_ids
294
295
296def create_pairwise_distance_lines(
297    distances: np.ndarray,
298    endpoints1: np.ndarray,
299    endpoints2: np.ndarray,
300    seg_ids: List[List[int]],
301    n_neighbors: Optional[int] = None,
302    pairs: Optional[np.ndarray] = None,
303    bb: Optional[Tuple[slice]] = None,
304    scale: Optional[float] = None,
305    remove_duplicates: bool = True
306) -> Tuple[np.ndarray, Dict]:
307    """Create a line representation of pair-wise object distances for display in napari.
308
309    Args:
310        distances: The pairwise distances.
311        endpoints1: One set of distance end points.
312        endpoints2: The other set of distance end points.
313        seg_ids: The segmentation pair corresponding to each distance.
314        n_neighbors: The number of nearest neighbors to take into consideration
315            for creating the distance lines.
316        pairs: Optional list of ids to use for creating the distance lines.
317        bb: Bounding box for restricing the distance line creation.
318        scale: Scale factor for resizing the distance lines.
319            Use this if the corresponding segmentations were downscaled for visualization.
320        remove_duplicates: Remove duplicate id pairs from the distance lines.
321
322    Returns:
323        The lines for plotting in napari.
324        Additional attributes for the line layer in napari.
325    """
326    if pairs is None and n_neighbors is not None:
327        pairs = _extract_nearest_neighbors(distances, seg_ids, n_neighbors, remove_duplicates=remove_duplicates)
328    elif pairs is None:
329        pairs = [[id1, id2] for id1 in seg_ids for id2 in seg_ids if id1 < id2]
330
331    assert pairs is not None
332    pair_indices = (
333        np.array([seg_ids.index(pair[0]) for pair in pairs]),
334        np.array([seg_ids.index(pair[1]) for pair in pairs])
335    )
336
337    pairs = np.array(pairs)
338    distances = distances[pair_indices]
339    endpoints1 = endpoints1[pair_indices]
340    endpoints2 = endpoints2[pair_indices]
341
342    if bb is not None:
343        in_bb = np.where(
344            (endpoints1[:, 0] > bb[0].start) & (endpoints1[:, 0] < bb[0].stop) &
345            (endpoints1[:, 1] > bb[1].start) & (endpoints1[:, 1] < bb[1].stop) &
346            (endpoints1[:, 2] > bb[2].start) & (endpoints1[:, 2] < bb[2].stop) &
347            (endpoints2[:, 0] > bb[0].start) & (endpoints2[:, 0] < bb[0].stop) &
348            (endpoints2[:, 1] > bb[1].start) & (endpoints2[:, 1] < bb[1].stop) &
349            (endpoints2[:, 2] > bb[2].start) & (endpoints2[:, 2] < bb[2].stop)
350        )
351
352        pairs = pairs[in_bb]
353        distances, endpoints1, endpoints2 = distances[in_bb], endpoints1[in_bb], endpoints2[in_bb]
354
355        offset = np.array([b.start for b in bb])[None]
356        endpoints1 -= offset
357        endpoints2 -= offset
358
359    lines = np.array([[start, end] for start, end in zip(endpoints1, endpoints2)])
360
361    if scale is not None:
362        scale_factor = np.array(3 * [scale])[None, None]
363        lines //= scale_factor
364
365    properties = {
366        "id_a": pairs[:, 0],
367        "id_b": pairs[:, 1],
368        "distance": np.round(distances, 2),
369    }
370    return lines, properties
371
372
373def create_object_distance_lines(
374    distances: np.ndarray,
375    endpoints1: np.ndarray,
376    endpoints2: np.ndarray,
377    seg_ids: np.ndarray,
378    max_distance: Optional[float] = None,
379    filter_seg_ids: Optional[np.ndarray] = None,
380    scale: Optional[float] = None,
381) -> Tuple[np.ndarray, Dict]:
382    """Create a line representation of object distances for display in napari.
383
384    Args:
385        distances: The measurd distances.
386        endpoints1: One set of distance end points.
387        endpoints2: The other set of distance end points.
388        seg_ids: The segmentation ids corresponding to each distance.
389        max_distance: Maximal distance for drawing the distance line.
390        filter_seg_ids: Segmentation ids to restrict the distance lines.
391        scale: Scale factor for resizing the distance lines.
392            Use this if the corresponding segmentations were downscaled for visualization.
393
394    Returns:
395        The lines for plotting in napari.
396        Additional attributes for the line layer in napari.
397    """
398
399    if filter_seg_ids is not None:
400        id_mask = np.isin(seg_ids, filter_seg_ids)
401        distances = distances[id_mask]
402        endpoints1, endpoints2 = endpoints1[id_mask], endpoints2[id_mask]
403        seg_ids = filter_seg_ids
404
405    if max_distance is not None:
406        distance_mask = distances <= max_distance
407        distances, seg_ids = distances[distance_mask], seg_ids[distance_mask]
408        endpoints1, endpoints2 = endpoints1[distance_mask], endpoints2[distance_mask]
409
410    assert len(distances) == len(seg_ids) == len(endpoints1) == len(endpoints2)
411    lines = np.array([[start, end] for start, end in zip(endpoints1, endpoints2)])
412
413    if scale is not None and len(lines > 0):
414        scale_factor = np.array(3 * [scale])[None, None]
415        lines //= scale_factor
416
417    properties = {"id": seg_ids, "distance": np.round(distances, 2)}
418    return lines, properties
419
420
421def keep_direct_distances(
422    segmentation: np.ndarray,
423    distances: np.ndarray,
424    endpoints1: np.ndarray,
425    endpoints2: np.ndarray,
426    seg_ids: np.ndarray,
427    line_dilation: int = 0,
428    scale: Optional[Tuple[int, int, int]] = None,
429) -> List[List[int]]:
430    """Filter out all distances that are not direct; distances that are occluded by another segmented object.
431
432    Args:
433        segmentation: The segmentation from which the distances are derived.
434        distances: The measurd distances.
435        endpoints1: One set of distance end points.
436        endpoints2: The other set of distance end points.
437        seg_ids: The segmentation ids corresponding to each distance.
438        line_dilation: Dilation factor of the distance lines for determining occlusions.
439        scale: Scaling factor of the segmentation compared to the distance measurements.
440
441    Returns:
442        The list of id pairs that are kept.
443    """
444    distance_lines, properties = create_pairwise_distance_lines(
445        distances, endpoints1, endpoints2, list(seg_ids), scale=scale
446    )
447
448    ids_a, ids_b = properties["id_a"], properties["id_b"]
449    filtered_ids_a, filtered_ids_b = [], []
450
451    for i, line in tqdm(enumerate(distance_lines), total=len(distance_lines)):
452        id_a, id_b = ids_a[i], ids_b[i]
453
454        start, stop = line
455        line = line_nd(start, stop, endpoint=True)
456
457        if line_dilation > 0:
458            # TODO make this more efficient, ideally by dilating the mask coordinates
459            # instead of dilating the actual mask.
460            # We turn the line into a binary mask and dilate it to have some tolerance.
461            line_vol = np.zeros_like(segmentation)
462            line_vol[line] = 1
463            line_vol = binary_dilation(line_vol, iterations=line_dilation)
464        else:
465            line_vol = line
466
467        # Check if we cross any other segments:
468        # Extract the unique ids in the segmentation that overlap with the segmentation.
469        # We count this as a direct distance if no other object overlaps with the line.
470        line_seg_ids = np.unique(segmentation[line_vol])
471        line_seg_ids = np.setdiff1d(line_seg_ids, [0, id_a, id_b])
472
473        if len(line_seg_ids) == 0:  # No other objet is overlapping, we keep the line.
474            filtered_ids_a.append(id_a)
475            filtered_ids_b.append(id_b)
476
477    print("Keeping", len(filtered_ids_a), "/", len(ids_a), "distance pairs")
478    filtered_pairs = [[ida, idb] for ida, idb in zip(filtered_ids_a, filtered_ids_b)]
479    return filtered_pairs
480
481
482def filter_blocked_segmentation_to_object_distances(
483    segmentation: np.ndarray,
484    distances: np.ndarray,
485    endpoints1: np.ndarray,
486    endpoints2: np.ndarray,
487    seg_ids: np.ndarray,
488    line_dilation: int = 0,
489    scale: Optional[Tuple[int, int, int]] = None,
490    filter_seg_ids: Optional[List[int]] = None,
491    verbose: bool = False,
492) -> List[int]:
493    """Filter out all distances that are not direct; distances that are occluded by another segmented object.
494
495    Args:
496        segmentation: The segmentation from which the distances are derived.
497        distances: The measurd distances.
498        endpoints1: One set of distance end points.
499        endpoints2: The other set of distance end points.
500        seg_ids: The segmentation ids corresponding to each distance.
501        line_dilation: Dilation factor of the distance lines for determining occlusions.
502        scale: Scaling factor of the segmentation compared to the distance measurements.
503        filter_seg_ids: Segmentation ids to restrict the distance lines.
504        verbose: Whether to print progressbar.
505
506    Returns:
507        The list of id pairs that are kept.
508    """
509    distance_lines, properties = create_object_distance_lines(
510         distances, endpoints1, endpoints2, seg_ids, scale=scale
511    )
512    all_seg_ids = properties["id"]
513
514    filtered_ids = []
515    for seg_id, line in tqdm(zip(all_seg_ids, distance_lines), total=len(distance_lines), disable=not verbose):
516        if (filter_seg_ids is not None) and (seg_id not in filter_seg_ids):
517            continue
518
519        start, stop = line
520        line = line_nd(start, stop, endpoint=True)
521
522        if line_dilation > 0:
523            # TODO make this more efficient, ideally by dilating the mask coordinates
524            # instead of dilating the actual mask.
525            # We turn the line into a binary mask and dilate it to have some tolerance.
526            line_vol = np.zeros_like(segmentation)
527            line_vol[line] = 1
528            line_vol = binary_dilation(line_vol, iterations=line_dilation)
529        else:
530            line_vol = line
531
532        # Check if we cross any other segments:
533        # Extract the unique ids in the segmentation that overlap with the segmentation.
534        # We count this as a direct distance if no other object overlaps with the line.
535        line_seg_ids = np.unique(segmentation[line_vol])
536        line_seg_ids = np.setdiff1d(line_seg_ids, [0, seg_id])
537
538        if len(line_seg_ids) == 0:  # No other objet is overlapping, we keep the line.
539            filtered_ids.append(seg_id)
540
541    return filtered_ids
def compute_geodesic_distances( segmentation: numpy.ndarray, distance_to: numpy.ndarray, resolution: Union[int, float, Tuple[int, int, int], NoneType] = None, unsigned: bool = True) -> numpy.ndarray:
21def compute_geodesic_distances(
22    segmentation: np.ndarray,
23    distance_to: np.ndarray,
24    resolution: Optional[Union[int, float, Tuple[int, int, int]]] = None,
25    unsigned: bool = True,
26) -> np.ndarray:
27    """Compute the geodesic distances between a segmentation and a distance target.
28
29    This function require scikit-fmm to be installed.
30
31    Args:
32        segmentation: The binary segmentation.
33        distance_to: The binary distance target.
34        resolution: The voxel size of the data, used to scale the distances.
35        unsigned: Whether to return the unsigned or signed distances.
36
37    Returns:
38        Array with the geodesic distance values.
39    """
40    assert skfmm is not None, "Please install scikit-fmm to use compute_geodesic_distance."
41
42    invalid = segmentation == 0
43    input_ = np.ma.array(segmentation.copy(), mask=invalid)
44    input_[distance_to] = 0
45
46    if resolution is None:
47        dx = 1.0
48    elif isinstance(resolution, (int, float)):
49        dx = float(resolution)
50    else:
51        assert len(resolution) == segmentation.ndim
52        dx = resolution
53
54    distances = skfmm.distance(input_, dx=dx).data
55    distances[distances == 0] = np.inf
56    distances[distance_to] = 0
57
58    if unsigned:
59        distances = np.abs(distances)
60
61    return distances

Compute the geodesic distances between a segmentation and a distance target.

This function require scikit-fmm to be installed.

Arguments:
  • segmentation: The binary segmentation.
  • distance_to: The binary distance target.
  • resolution: The voxel size of the data, used to scale the distances.
  • unsigned: Whether to return the unsigned or signed distances.
Returns:

Array with the geodesic distance values.

def measure_pairwise_object_distances( segmentation: numpy.ndarray, distance_type: str = 'boundary', resolution: Optional[Tuple[int, int, int]] = None, n_threads: Optional[int] = None, save_path: Optional[os.PathLike] = None) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]:
119def measure_pairwise_object_distances(
120    segmentation: np.ndarray,
121    distance_type: str = "boundary",
122    resolution: Optional[Tuple[int, int, int]] = None,
123    n_threads: Optional[int] = None,
124    save_path: Optional[os.PathLike] = None,
125) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
126    """Compute the pairwise distances between all objects within a segmentation.
127
128    Args:
129        segmentation: The input segmentation.
130        distance_type: The type of distance to compute. Only 'boundary', the distance between
131            the boundary / surface of the objects, is supported.
132        resolution: The resolution / pixel size of the data.
133        n_threads: The number of threads for parallelizing the distance computation.
134        save_path: Path for saving the measurement results in numpy zipped format.
135
136    Returns:
137        The pairwise object distances.
138        The 'left' endpoint coordinates of the distances.
139        The 'right' endpoint coordinates of the distances.
140        The segmentation id pairs of the distances.
141    """
142    if distance_type != "boundary":
143        raise NotImplementedError(f"Distance type '{distance_type}' is not supported, only 'boundary'.")
144    distances, endpoints1, endpoints2, seg_ids = _compute_boundary_distances(segmentation, resolution, n_threads)
145
146    if save_path is not None:
147        np.savez(
148            save_path,
149            distances=distances,
150            endpoints1=endpoints1,
151            endpoints2=endpoints2,
152            seg_ids=seg_ids,
153        )
154
155    return distances, endpoints1, endpoints2, seg_ids

Compute the pairwise distances between all objects within a segmentation.

Arguments:
  • segmentation: The input segmentation.
  • distance_type: The type of distance to compute. Only 'boundary', the distance between the boundary / surface of the objects, is supported.
  • resolution: The resolution / pixel size of the data.
  • n_threads: The number of threads for parallelizing the distance computation.
  • save_path: Path for saving the measurement results in numpy zipped format.
Returns:

The pairwise object distances. The 'left' endpoint coordinates of the distances. The 'right' endpoint coordinates of the distances. The segmentation id pairs of the distances.

def measure_segmentation_to_object_distances( segmentation: numpy.ndarray, segmented_object: numpy.ndarray, distance_type: str = 'boundary', resolution: Optional[Tuple[int, int, int]] = None, save_path: Optional[os.PathLike] = None, verbose: bool = False) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]:
206def measure_segmentation_to_object_distances(
207    segmentation: np.ndarray,
208    segmented_object: np.ndarray,
209    distance_type: str = "boundary",
210    resolution: Optional[Tuple[int, int, int]] = None,
211    save_path: Optional[os.PathLike] = None,
212    verbose: bool = False,
213) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
214    """Compute the distance betwen all objects in a segmentation and another object.
215
216    Args:
217        segmentation: The input segmentation.
218        segmented_object: The segmented object.
219        distance_type: The type of distance to compute. Only 'boundary', the distance between
220            the boundary / surface of the objects, is supported.
221        resolution: The resolution / pixel size of the data.
222        save_path: Path for saving the measurement results in numpy zipped format.
223        verbose: Whether to print the progress of the distance computation.
224
225    Returns:
226        The segmentation to object distances.
227        The 'left' endpoint coordinates of the distances.
228        The 'right' endpoint coordinates of the distances.
229        The segmentation ids corresponding to the distances.
230    """
231    if distance_type == "boundary":
232        distances, endpoints1, endpoints2, seg_ids, object_ids = _compute_seg_object_distances(
233            segmentation, segmented_object, resolution, verbose
234        )
235        assert len(distances) == len(endpoints1) == len(endpoints2) == len(seg_ids) == len(object_ids)
236    else:
237        raise NotImplementedError
238
239    if save_path is not None:
240        np.savez(
241            save_path,
242            distances=distances,
243            endpoints1=endpoints1,
244            endpoints2=endpoints2,
245            seg_ids=seg_ids,
246            object_ids=object_ids,
247        )
248    return distances, endpoints1, endpoints2, seg_ids

Compute the distance betwen all objects in a segmentation and another object.

Arguments:
  • segmentation: The input segmentation.
  • segmented_object: The segmented object.
  • distance_type: The type of distance to compute. Only 'boundary', the distance between the boundary / surface of the objects, is supported.
  • resolution: The resolution / pixel size of the data.
  • save_path: Path for saving the measurement results in numpy zipped format.
  • verbose: Whether to print the progress of the distance computation.
Returns:

The segmentation to object distances. The 'left' endpoint coordinates of the distances. The 'right' endpoint coordinates of the distances. The segmentation ids corresponding to the distances.

def load_distances( measurement_path: os.PathLike) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]:
277def load_distances(
278    measurement_path: os.PathLike
279) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
280    """Load the saved distacnes from a zipped numpy file.
281
282    Args:
283        measurement_path: The path where the distances where saved.
284
285    Returns:
286        The segmentation to object distances.
287        The 'left' endpoint coordinates of the distances.
288        The 'right' endpoint coordinates of the distances.
289        The segmentation ids corresponding to the distances.
290    """
291    auto_dists = np.load(measurement_path)
292    distances, seg_ids = auto_dists["distances"], list(auto_dists["seg_ids"])
293    endpoints1, endpoints2 = auto_dists["endpoints1"], auto_dists["endpoints2"]
294    return distances, endpoints1, endpoints2, seg_ids

Load the saved distacnes from a zipped numpy file.

Arguments:
  • measurement_path: The path where the distances where saved.
Returns:

The segmentation to object distances. The 'left' endpoint coordinates of the distances. The 'right' endpoint coordinates of the distances. The segmentation ids corresponding to the distances.

def create_pairwise_distance_lines( distances: numpy.ndarray, endpoints1: numpy.ndarray, endpoints2: numpy.ndarray, seg_ids: List[List[int]], n_neighbors: Optional[int] = None, pairs: Optional[numpy.ndarray] = None, bb: Optional[Tuple[slice]] = None, scale: Optional[float] = None, remove_duplicates: bool = True) -> Tuple[numpy.ndarray, Dict]:
297def create_pairwise_distance_lines(
298    distances: np.ndarray,
299    endpoints1: np.ndarray,
300    endpoints2: np.ndarray,
301    seg_ids: List[List[int]],
302    n_neighbors: Optional[int] = None,
303    pairs: Optional[np.ndarray] = None,
304    bb: Optional[Tuple[slice]] = None,
305    scale: Optional[float] = None,
306    remove_duplicates: bool = True
307) -> Tuple[np.ndarray, Dict]:
308    """Create a line representation of pair-wise object distances for display in napari.
309
310    Args:
311        distances: The pairwise distances.
312        endpoints1: One set of distance end points.
313        endpoints2: The other set of distance end points.
314        seg_ids: The segmentation pair corresponding to each distance.
315        n_neighbors: The number of nearest neighbors to take into consideration
316            for creating the distance lines.
317        pairs: Optional list of ids to use for creating the distance lines.
318        bb: Bounding box for restricing the distance line creation.
319        scale: Scale factor for resizing the distance lines.
320            Use this if the corresponding segmentations were downscaled for visualization.
321        remove_duplicates: Remove duplicate id pairs from the distance lines.
322
323    Returns:
324        The lines for plotting in napari.
325        Additional attributes for the line layer in napari.
326    """
327    if pairs is None and n_neighbors is not None:
328        pairs = _extract_nearest_neighbors(distances, seg_ids, n_neighbors, remove_duplicates=remove_duplicates)
329    elif pairs is None:
330        pairs = [[id1, id2] for id1 in seg_ids for id2 in seg_ids if id1 < id2]
331
332    assert pairs is not None
333    pair_indices = (
334        np.array([seg_ids.index(pair[0]) for pair in pairs]),
335        np.array([seg_ids.index(pair[1]) for pair in pairs])
336    )
337
338    pairs = np.array(pairs)
339    distances = distances[pair_indices]
340    endpoints1 = endpoints1[pair_indices]
341    endpoints2 = endpoints2[pair_indices]
342
343    if bb is not None:
344        in_bb = np.where(
345            (endpoints1[:, 0] > bb[0].start) & (endpoints1[:, 0] < bb[0].stop) &
346            (endpoints1[:, 1] > bb[1].start) & (endpoints1[:, 1] < bb[1].stop) &
347            (endpoints1[:, 2] > bb[2].start) & (endpoints1[:, 2] < bb[2].stop) &
348            (endpoints2[:, 0] > bb[0].start) & (endpoints2[:, 0] < bb[0].stop) &
349            (endpoints2[:, 1] > bb[1].start) & (endpoints2[:, 1] < bb[1].stop) &
350            (endpoints2[:, 2] > bb[2].start) & (endpoints2[:, 2] < bb[2].stop)
351        )
352
353        pairs = pairs[in_bb]
354        distances, endpoints1, endpoints2 = distances[in_bb], endpoints1[in_bb], endpoints2[in_bb]
355
356        offset = np.array([b.start for b in bb])[None]
357        endpoints1 -= offset
358        endpoints2 -= offset
359
360    lines = np.array([[start, end] for start, end in zip(endpoints1, endpoints2)])
361
362    if scale is not None:
363        scale_factor = np.array(3 * [scale])[None, None]
364        lines //= scale_factor
365
366    properties = {
367        "id_a": pairs[:, 0],
368        "id_b": pairs[:, 1],
369        "distance": np.round(distances, 2),
370    }
371    return lines, properties

Create a line representation of pair-wise object distances for display in napari.

Arguments:
  • distances: The pairwise distances.
  • endpoints1: One set of distance end points.
  • endpoints2: The other set of distance end points.
  • seg_ids: The segmentation pair corresponding to each distance.
  • n_neighbors: The number of nearest neighbors to take into consideration for creating the distance lines.
  • pairs: Optional list of ids to use for creating the distance lines.
  • bb: Bounding box for restricing the distance line creation.
  • scale: Scale factor for resizing the distance lines. Use this if the corresponding segmentations were downscaled for visualization.
  • remove_duplicates: Remove duplicate id pairs from the distance lines.
Returns:

The lines for plotting in napari. Additional attributes for the line layer in napari.

def create_object_distance_lines( distances: numpy.ndarray, endpoints1: numpy.ndarray, endpoints2: numpy.ndarray, seg_ids: numpy.ndarray, max_distance: Optional[float] = None, filter_seg_ids: Optional[numpy.ndarray] = None, scale: Optional[float] = None) -> Tuple[numpy.ndarray, Dict]:
374def create_object_distance_lines(
375    distances: np.ndarray,
376    endpoints1: np.ndarray,
377    endpoints2: np.ndarray,
378    seg_ids: np.ndarray,
379    max_distance: Optional[float] = None,
380    filter_seg_ids: Optional[np.ndarray] = None,
381    scale: Optional[float] = None,
382) -> Tuple[np.ndarray, Dict]:
383    """Create a line representation of object distances for display in napari.
384
385    Args:
386        distances: The measurd distances.
387        endpoints1: One set of distance end points.
388        endpoints2: The other set of distance end points.
389        seg_ids: The segmentation ids corresponding to each distance.
390        max_distance: Maximal distance for drawing the distance line.
391        filter_seg_ids: Segmentation ids to restrict the distance lines.
392        scale: Scale factor for resizing the distance lines.
393            Use this if the corresponding segmentations were downscaled for visualization.
394
395    Returns:
396        The lines for plotting in napari.
397        Additional attributes for the line layer in napari.
398    """
399
400    if filter_seg_ids is not None:
401        id_mask = np.isin(seg_ids, filter_seg_ids)
402        distances = distances[id_mask]
403        endpoints1, endpoints2 = endpoints1[id_mask], endpoints2[id_mask]
404        seg_ids = filter_seg_ids
405
406    if max_distance is not None:
407        distance_mask = distances <= max_distance
408        distances, seg_ids = distances[distance_mask], seg_ids[distance_mask]
409        endpoints1, endpoints2 = endpoints1[distance_mask], endpoints2[distance_mask]
410
411    assert len(distances) == len(seg_ids) == len(endpoints1) == len(endpoints2)
412    lines = np.array([[start, end] for start, end in zip(endpoints1, endpoints2)])
413
414    if scale is not None and len(lines > 0):
415        scale_factor = np.array(3 * [scale])[None, None]
416        lines //= scale_factor
417
418    properties = {"id": seg_ids, "distance": np.round(distances, 2)}
419    return lines, properties

Create a line representation of object distances for display in napari.

Arguments:
  • distances: The measurd distances.
  • endpoints1: One set of distance end points.
  • endpoints2: The other set of distance end points.
  • seg_ids: The segmentation ids corresponding to each distance.
  • max_distance: Maximal distance for drawing the distance line.
  • filter_seg_ids: Segmentation ids to restrict the distance lines.
  • scale: Scale factor for resizing the distance lines. Use this if the corresponding segmentations were downscaled for visualization.
Returns:

The lines for plotting in napari. Additional attributes for the line layer in napari.

def keep_direct_distances( segmentation: numpy.ndarray, distances: numpy.ndarray, endpoints1: numpy.ndarray, endpoints2: numpy.ndarray, seg_ids: numpy.ndarray, line_dilation: int = 0, scale: Optional[Tuple[int, int, int]] = None) -> List[List[int]]:
422def keep_direct_distances(
423    segmentation: np.ndarray,
424    distances: np.ndarray,
425    endpoints1: np.ndarray,
426    endpoints2: np.ndarray,
427    seg_ids: np.ndarray,
428    line_dilation: int = 0,
429    scale: Optional[Tuple[int, int, int]] = None,
430) -> List[List[int]]:
431    """Filter out all distances that are not direct; distances that are occluded by another segmented object.
432
433    Args:
434        segmentation: The segmentation from which the distances are derived.
435        distances: The measurd distances.
436        endpoints1: One set of distance end points.
437        endpoints2: The other set of distance end points.
438        seg_ids: The segmentation ids corresponding to each distance.
439        line_dilation: Dilation factor of the distance lines for determining occlusions.
440        scale: Scaling factor of the segmentation compared to the distance measurements.
441
442    Returns:
443        The list of id pairs that are kept.
444    """
445    distance_lines, properties = create_pairwise_distance_lines(
446        distances, endpoints1, endpoints2, list(seg_ids), scale=scale
447    )
448
449    ids_a, ids_b = properties["id_a"], properties["id_b"]
450    filtered_ids_a, filtered_ids_b = [], []
451
452    for i, line in tqdm(enumerate(distance_lines), total=len(distance_lines)):
453        id_a, id_b = ids_a[i], ids_b[i]
454
455        start, stop = line
456        line = line_nd(start, stop, endpoint=True)
457
458        if line_dilation > 0:
459            # TODO make this more efficient, ideally by dilating the mask coordinates
460            # instead of dilating the actual mask.
461            # We turn the line into a binary mask and dilate it to have some tolerance.
462            line_vol = np.zeros_like(segmentation)
463            line_vol[line] = 1
464            line_vol = binary_dilation(line_vol, iterations=line_dilation)
465        else:
466            line_vol = line
467
468        # Check if we cross any other segments:
469        # Extract the unique ids in the segmentation that overlap with the segmentation.
470        # We count this as a direct distance if no other object overlaps with the line.
471        line_seg_ids = np.unique(segmentation[line_vol])
472        line_seg_ids = np.setdiff1d(line_seg_ids, [0, id_a, id_b])
473
474        if len(line_seg_ids) == 0:  # No other objet is overlapping, we keep the line.
475            filtered_ids_a.append(id_a)
476            filtered_ids_b.append(id_b)
477
478    print("Keeping", len(filtered_ids_a), "/", len(ids_a), "distance pairs")
479    filtered_pairs = [[ida, idb] for ida, idb in zip(filtered_ids_a, filtered_ids_b)]
480    return filtered_pairs

Filter out all distances that are not direct; distances that are occluded by another segmented object.

Arguments:
  • segmentation: The segmentation from which the distances are derived.
  • distances: The measurd distances.
  • endpoints1: One set of distance end points.
  • endpoints2: The other set of distance end points.
  • seg_ids: The segmentation ids corresponding to each distance.
  • line_dilation: Dilation factor of the distance lines for determining occlusions.
  • scale: Scaling factor of the segmentation compared to the distance measurements.
Returns:

The list of id pairs that are kept.

def filter_blocked_segmentation_to_object_distances( segmentation: numpy.ndarray, distances: numpy.ndarray, endpoints1: numpy.ndarray, endpoints2: numpy.ndarray, seg_ids: numpy.ndarray, line_dilation: int = 0, scale: Optional[Tuple[int, int, int]] = None, filter_seg_ids: Optional[List[int]] = None, verbose: bool = False) -> List[int]:
483def filter_blocked_segmentation_to_object_distances(
484    segmentation: np.ndarray,
485    distances: np.ndarray,
486    endpoints1: np.ndarray,
487    endpoints2: np.ndarray,
488    seg_ids: np.ndarray,
489    line_dilation: int = 0,
490    scale: Optional[Tuple[int, int, int]] = None,
491    filter_seg_ids: Optional[List[int]] = None,
492    verbose: bool = False,
493) -> List[int]:
494    """Filter out all distances that are not direct; distances that are occluded by another segmented object.
495
496    Args:
497        segmentation: The segmentation from which the distances are derived.
498        distances: The measurd distances.
499        endpoints1: One set of distance end points.
500        endpoints2: The other set of distance end points.
501        seg_ids: The segmentation ids corresponding to each distance.
502        line_dilation: Dilation factor of the distance lines for determining occlusions.
503        scale: Scaling factor of the segmentation compared to the distance measurements.
504        filter_seg_ids: Segmentation ids to restrict the distance lines.
505        verbose: Whether to print progressbar.
506
507    Returns:
508        The list of id pairs that are kept.
509    """
510    distance_lines, properties = create_object_distance_lines(
511         distances, endpoints1, endpoints2, seg_ids, scale=scale
512    )
513    all_seg_ids = properties["id"]
514
515    filtered_ids = []
516    for seg_id, line in tqdm(zip(all_seg_ids, distance_lines), total=len(distance_lines), disable=not verbose):
517        if (filter_seg_ids is not None) and (seg_id not in filter_seg_ids):
518            continue
519
520        start, stop = line
521        line = line_nd(start, stop, endpoint=True)
522
523        if line_dilation > 0:
524            # TODO make this more efficient, ideally by dilating the mask coordinates
525            # instead of dilating the actual mask.
526            # We turn the line into a binary mask and dilate it to have some tolerance.
527            line_vol = np.zeros_like(segmentation)
528            line_vol[line] = 1
529            line_vol = binary_dilation(line_vol, iterations=line_dilation)
530        else:
531            line_vol = line
532
533        # Check if we cross any other segments:
534        # Extract the unique ids in the segmentation that overlap with the segmentation.
535        # We count this as a direct distance if no other object overlaps with the line.
536        line_seg_ids = np.unique(segmentation[line_vol])
537        line_seg_ids = np.setdiff1d(line_seg_ids, [0, seg_id])
538
539        if len(line_seg_ids) == 0:  # No other objet is overlapping, we keep the line.
540            filtered_ids.append(seg_id)
541
542    return filtered_ids

Filter out all distances that are not direct; distances that are occluded by another segmented object.

Arguments:
  • segmentation: The segmentation from which the distances are derived.
  • distances: The measurd distances.
  • endpoints1: One set of distance end points.
  • endpoints2: The other set of distance end points.
  • seg_ids: The segmentation ids corresponding to each distance.
  • line_dilation: Dilation factor of the distance lines for determining occlusions.
  • scale: Scaling factor of the segmentation compared to the distance measurements.
  • filter_seg_ids: Segmentation ids to restrict the distance lines.
  • verbose: Whether to print progressbar.
Returns:

The list of id pairs that are kept.