|
| 1 | +import os |
| 2 | +import re |
| 3 | +from typing import Dict, List, Optional, Tuple |
| 4 | + |
| 5 | +import imageio.v3 as imageio |
| 6 | +import numpy as np |
| 7 | +import pandas as pd |
| 8 | +import zarr |
| 9 | + |
| 10 | +from scipy.ndimage import distance_transform_edt |
| 11 | +from scipy.optimize import linear_sum_assignment |
| 12 | +from skimage.measure import regionprops_table |
| 13 | +from skimage.segmentation import relabel_sequential |
| 14 | +from tqdm import tqdm |
| 15 | + |
| 16 | +from .s3_utils import get_s3_path, BUCKET_NAME, SERVICE_ENDPOINT |
| 17 | + |
| 18 | + |
| 19 | +def _normalize_cochlea_name(name): |
| 20 | + match = re.search(r"\d+", name) |
| 21 | + pos = match.start() if match else None |
| 22 | + assert pos is not None, name |
| 23 | + prefix = name[:pos] |
| 24 | + prefix = f"{prefix[0]}_{prefix[1:]}" |
| 25 | + number = int(name[pos:-1]) |
| 26 | + postfix = name[-1] |
| 27 | + return f"{prefix}_{number:06d}_{postfix}" |
| 28 | + |
| 29 | + |
| 30 | +def parse_annotation_path(annotation_path): |
| 31 | + fname = os.path.basename(annotation_path) |
| 32 | + name_parts = fname.split("_") |
| 33 | + cochlea = _normalize_cochlea_name(name_parts[0]) |
| 34 | + slice_id = int(name_parts[2][1:]) |
| 35 | + return cochlea, slice_id |
| 36 | + |
| 37 | + |
| 38 | +# TODO enable table component filtering with MoBIE table |
| 39 | +# NOTE: the main component is always #1 |
| 40 | +def fetch_data_for_evaluation( |
| 41 | + annotation_path: str, |
| 42 | + cache_path: Optional[str] = None, |
| 43 | + seg_name: str = "SGN", |
| 44 | + z_extent: int = 0, |
| 45 | + components_for_postprocessing: Optional[List[int]] = None, |
| 46 | +) -> Tuple[np.ndarray, pd.DataFrame]: |
| 47 | + """ |
| 48 | + """ |
| 49 | + # Load the annotations and normalize them for the given z-extent. |
| 50 | + annotations = pd.read_csv(annotation_path) |
| 51 | + annotations = annotations.drop(columns="index") |
| 52 | + if z_extent == 0: # If we don't have a z-extent then we just drop the first axis and rename the other two. |
| 53 | + annotations = annotations.drop(columns="axis-0") |
| 54 | + annotations = annotations.rename(columns={"axis-1": "axis-0", "axis-2": "axis-1"}) |
| 55 | + else: # Otherwise we have to center the first axis. |
| 56 | + # TODO |
| 57 | + raise NotImplementedError |
| 58 | + |
| 59 | + # Load the segmentaiton from cache path if it is given and if it is already cached. |
| 60 | + if cache_path is not None and os.path.exists(cache_path): |
| 61 | + segmentation = imageio.imread(cache_path) |
| 62 | + return segmentation, annotations |
| 63 | + |
| 64 | + # Parse which ID and which cochlea from the name. |
| 65 | + cochlea, slice_id = parse_annotation_path(annotation_path) |
| 66 | + |
| 67 | + # Open the S3 connection, get the path to the SGN segmentation in S3. |
| 68 | + internal_path = os.path.join(cochlea, "images", "ome-zarr", f"{seg_name}.ome.zarr") |
| 69 | + s3_store, fs = get_s3_path(internal_path, bucket_name=BUCKET_NAME, service_endpoint=SERVICE_ENDPOINT) |
| 70 | + |
| 71 | + # Compute the roi for the given z-extent. |
| 72 | + if z_extent == 0: |
| 73 | + roi = slice_id |
| 74 | + else: |
| 75 | + roi = slice(slice_id - z_extent, slice_id + z_extent) |
| 76 | + |
| 77 | + # Download the segmentation for this slice and the given z-extent. |
| 78 | + input_key = "s0" |
| 79 | + with zarr.open(s3_store, mode="r") as f: |
| 80 | + segmentation = f[input_key][roi] |
| 81 | + |
| 82 | + if components_for_postprocessing is not None: |
| 83 | + # Filter the IDs so that only the ones part of 'components_for_postprocessing_remain'. |
| 84 | + |
| 85 | + # First, we download the MoBIE table for this segmentation. |
| 86 | + internal_path = os.path.join(BUCKET_NAME, cochlea, "tables", seg_name, "default.tsv") |
| 87 | + with fs.open(internal_path, "r") as f: |
| 88 | + table = pd.read_csv(f, sep="\t") |
| 89 | + |
| 90 | + # Then we get the ids for the components and us them to filter the segmentation. |
| 91 | + component_mask = np.isin(table.component_labels.values, components_for_postprocessing) |
| 92 | + keep_label_ids = table.label_id.values[component_mask].astype("int64") |
| 93 | + filter_mask = ~np.isin(segmentation, keep_label_ids) |
| 94 | + segmentation[filter_mask] = 0 |
| 95 | + |
| 96 | + segmentation, _, _ = relabel_sequential(segmentation) |
| 97 | + |
| 98 | + # Cache it if required. |
| 99 | + if cache_path is not None: |
| 100 | + imageio.imwrite(cache_path, segmentation, compression="zlib") |
| 101 | + |
| 102 | + return segmentation, annotations |
| 103 | + |
| 104 | + |
| 105 | +# We should use the hungarian based matching, but I can't find the bug in it right now. |
| 106 | +def _naive_matching(annotations, segmentation, segmentation_ids, matching_tolerance, coordinates): |
| 107 | + distances, indices = distance_transform_edt(segmentation == 0, return_indices=True) |
| 108 | + |
| 109 | + matched_ids = {} |
| 110 | + matched_distances = {} |
| 111 | + annotation_id = 0 |
| 112 | + for _, row in annotations.iterrows(): |
| 113 | + coordinate = tuple(int(np.round(row[coord])) for coord in coordinates) |
| 114 | + object_distance = distances[coordinate] |
| 115 | + if object_distance <= matching_tolerance: |
| 116 | + closest_object_coord = tuple(idx[coordinate] for idx in indices) |
| 117 | + object_id = segmentation[closest_object_coord] |
| 118 | + if object_id not in matched_ids or matched_distances[object_id] > object_distance: |
| 119 | + matched_ids[object_id] = annotation_id |
| 120 | + matched_distances[object_id] = object_distance |
| 121 | + annotation_id += 1 |
| 122 | + |
| 123 | + tp_ids_objects = np.array(list(matched_ids.keys())) |
| 124 | + tp_ids_annotations = np.array(list(matched_ids.values())) |
| 125 | + return tp_ids_objects, tp_ids_annotations |
| 126 | + |
| 127 | + |
| 128 | +# There is a bug in here that neither I nor o3 can figure out ... |
| 129 | +def _assignment_based_matching(annotations, segmentation, segmentation_ids, matching_tolerance, coordinates): |
| 130 | + n_objects, n_annotations = len(segmentation_ids), len(annotations) |
| 131 | + |
| 132 | + # In order to get the full distance matrix, we compute the distance to all objects for each annotation. |
| 133 | + # This is not very efficient, but it's the most straight-forward and most rigorous approach. |
| 134 | + scores = np.zeros((n_objects, n_annotations), dtype="float") |
| 135 | + i = 0 |
| 136 | + for _, row in tqdm(annotations.iterrows(), total=n_annotations, desc="Compute pairwise distances"): |
| 137 | + coordinate = tuple(int(np.round(row[coord])) for coord in coordinates) |
| 138 | + distance_input = np.ones(segmentation.shape, dtype="bool") |
| 139 | + distance_input[coordinate] = False |
| 140 | + distances = distance_transform_edt(distance_input) |
| 141 | + |
| 142 | + props = regionprops_table(segmentation, intensity_image=distances, properties=("label", "min_intensity")) |
| 143 | + distances = props["min_intensity"] |
| 144 | + assert len(distances) == scores.shape[0] |
| 145 | + scores[:, i] = distances |
| 146 | + i += 1 |
| 147 | + |
| 148 | + # Find the assignment of points to objects. |
| 149 | + # These correspond to the TP ids in the point / object annotations. |
| 150 | + tp_ids_objects, tp_ids_annotations = linear_sum_assignment(scores) |
| 151 | + match_ok = scores[tp_ids_objects, tp_ids_annotations] <= matching_tolerance |
| 152 | + tp_ids_objects, tp_ids_annotations = tp_ids_objects[match_ok], tp_ids_annotations[match_ok] |
| 153 | + tp_ids_objects = segmentation_ids[tp_ids_objects] |
| 154 | + |
| 155 | + return tp_ids_objects, tp_ids_annotations |
| 156 | + |
| 157 | + |
| 158 | +def compute_matches_for_annotated_slice( |
| 159 | + segmentation: np.typing.ArrayLike, |
| 160 | + annotations: pd.DataFrame, |
| 161 | + matching_tolerance: float = 0.0, |
| 162 | +) -> Dict[str, np.ndarray]: |
| 163 | + """Computes the ids of matches and non-matches for a annotated validation slice. |
| 164 | +
|
| 165 | + Computes true positive ids (for objects and annotations), false positive ids and false negative ids |
| 166 | + by solving a linear cost assignment of distances between objects and annotations. |
| 167 | +
|
| 168 | + Args: |
| 169 | + segmentation: The segmentation for this slide. We assume that it is relabeled consecutively. |
| 170 | + annotations: The annotations, marking cell centers. |
| 171 | + matching_tolerance: The maximum distance for matching an annotation to a segmented object. |
| 172 | +
|
| 173 | + Returns: |
| 174 | + A dictionary with keys 'tp_objects', 'tp_annotations' 'fp' and 'fn', mapping to the respective ids. |
| 175 | + """ |
| 176 | + assert segmentation.ndim in (2, 3) |
| 177 | + coordinates = ["axis-0", "axis-1"] if segmentation.ndim == 2 else ["axis-0", "axis-1", "axis-2"] |
| 178 | + segmentation_ids = np.unique(segmentation)[1:] |
| 179 | + |
| 180 | + # Crop to the minimal enclosing bounding box of points and segmented objects. |
| 181 | + bb_seg = np.where(segmentation != 0) |
| 182 | + bb_seg = tuple(slice(int(bb.min()), int(bb.max())) for bb in bb_seg) |
| 183 | + bb_points = tuple( |
| 184 | + slice(int(np.floor(annotations[coords].min())), int(np.ceil(annotations[coords].max())) + 1) |
| 185 | + for coords in coordinates |
| 186 | + ) |
| 187 | + bbox = tuple(slice(min(bbs.start, bbp.start), max(bbs.stop, bbp.stop)) for bbs, bbp in zip(bb_seg, bb_points)) |
| 188 | + segmentation = segmentation[bbox] |
| 189 | + |
| 190 | + annotations = annotations.copy() |
| 191 | + for coord, bb in zip(coordinates, bbox): |
| 192 | + annotations[coord] -= bb.start |
| 193 | + assert (annotations[coord] <= bb.stop).all() |
| 194 | + |
| 195 | + # tp_ids_objects, tp_ids_annotations =\ |
| 196 | + # _assignment_based_matching(annotations, segmentation, segmentation_ids, matching_tolerance, coordinates) |
| 197 | + tp_ids_objects, tp_ids_annotations =\ |
| 198 | + _naive_matching(annotations, segmentation, segmentation_ids, matching_tolerance, coordinates) |
| 199 | + assert len(tp_ids_objects) == len(tp_ids_annotations) |
| 200 | + |
| 201 | + # Find the false positives: objects that are not part of the matches. |
| 202 | + fp_ids = np.setdiff1d(segmentation_ids, tp_ids_objects) |
| 203 | + |
| 204 | + # Find the false negatives: annotations that are not part of the matches. |
| 205 | + fn_ids = np.setdiff1d(np.arange(len(annotations)), tp_ids_annotations) |
| 206 | + |
| 207 | + return {"tp_objects": tp_ids_objects, "tp_annotations": tp_ids_annotations, "fp": fp_ids, "fn": fn_ids} |
| 208 | + |
| 209 | + |
| 210 | +def compute_scores_for_annotated_slice( |
| 211 | + segmentation: np.typing.ArrayLike, |
| 212 | + annotations: pd.DataFrame, |
| 213 | + matching_tolerance: float = 0.0, |
| 214 | +) -> Dict[str, int]: |
| 215 | + """Computes the scores for a annotated validation slice. |
| 216 | +
|
| 217 | + Computes true positives, false positives and false negatives for scoring. |
| 218 | +
|
| 219 | + Args: |
| 220 | + segmentation: The segmentation for this slide. We assume that it is relabeled consecutively. |
| 221 | + annotations: The annotations, marking cell centers. |
| 222 | + matching_tolerance: The maximum distance for matching an annotation to a segmented object. |
| 223 | +
|
| 224 | + Returns: |
| 225 | + A dictionary with keys 'tp', 'fp' and 'fn', mapping to the respective counts. |
| 226 | + """ |
| 227 | + result = compute_matches_for_annotated_slice(segmentation, annotations, matching_tolerance) |
| 228 | + |
| 229 | + # To determine the TPs, FPs and FNs. |
| 230 | + tp = len(result["tp_objects"]) |
| 231 | + fp = len(result["fp"]) |
| 232 | + fn = len(result["fn"]) |
| 233 | + return {"tp": tp, "fp": fp, "fn": fn} |
| 234 | + |
| 235 | + |
| 236 | +def for_visualization(segmentation, annotations, matches): |
| 237 | + green_red = ["#00FF00", "#FF0000"] |
| 238 | + |
| 239 | + seg_vis = np.zeros_like(segmentation) |
| 240 | + tps, fps = matches["tp_objects"], matches["fp"] |
| 241 | + seg_vis[np.isin(segmentation, tps)] = 1 |
| 242 | + seg_vis[np.isin(segmentation, fps)] = 2 |
| 243 | + |
| 244 | + seg_props = dict(colormap={1: green_red[0], 2: green_red[1]}) |
| 245 | + |
| 246 | + point_vis = annotations.copy() |
| 247 | + tps = matches["tp_annotations"] |
| 248 | + match_properties = ["tp" if aid in tps else "fn" for aid in range(len(annotations))] |
| 249 | + # The color cycle assigns the first color to the first property etc. |
| 250 | + # So we need to set the first color to red if the first id is a false negative and vice versa. |
| 251 | + color_cycle = green_red[::-1] if match_properties[0] == "fn" else green_red |
| 252 | + point_props = dict( |
| 253 | + properties={ |
| 254 | + "id": list(range(len(annotations))), |
| 255 | + "match": match_properties, |
| 256 | + }, |
| 257 | + face_color="match", |
| 258 | + face_color_cycle=color_cycle, |
| 259 | + border_width=0.25, |
| 260 | + size=10, |
| 261 | + ) |
| 262 | + |
| 263 | + return seg_vis, point_vis, seg_props, point_props |
0 commit comments