Source code for zarr_vectors_tools.algorithms.segment_link

"""Find one segment in several stores: its skeleton, its mesh, its synapses.

EM stores keep the segment id of each object as the ``segment_id`` object
attribute: the precomputed skeleton and mesh ingests write it, and so does
the synapse join, whose objects are numbered like its skeleton store's.
Nothing else links the stores.  A segment id is the key they share, so a
segment picked in the mesh store can be found in the skeleton store, with
its metrics, and in the synapse store.

The lookup is by value, not by position, and no store is assumed to be
sorted: a skeleton pyramid's coarser level zeroes the segment id of each
object sparsity dropped, and a synapse store's unassigned object has
segment id 0.  A segment is *present* at a level when its object there has
geometry; one that sparsity dropped resolves to ``None``, the same as one
the store never held.

Levels without their own ``segment_id`` answer with level 0's, since the
mesh and point pyramid builders keep object ids.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import numpy as np
import numpy.typing as npt

SEGMENT_ID_ATTR = "segment_id"


@dataclass(frozen=True)
class _Index:
    """One store level's segment ids, searchable."""

    segments: npt.NDArray[np.uint64]     # indexed by object id
    order: npt.NDArray[np.int64]         # argsort of segments
    ranked: npt.NDArray[np.uint64]       # segments[order]

    def object_ids(self, segment_ids: npt.NDArray[np.uint64]) -> npt.NDArray[np.int64]:
        """Object id per segment id, ``-1`` where the level does not list it."""
        pos = np.searchsorted(self.ranked, segment_ids)
        inside = pos < len(self.ranked)
        hit = np.zeros(len(segment_ids), dtype=bool)
        hit[inside] = self.ranked[pos[inside]] == segment_ids[inside]
        out = np.full(len(segment_ids), -1, dtype=np.int64)
        out[hit] = self.order[pos[hit]]
        # Segment 0 is background: the synapse join's unassigned object.
        out[segment_ids == 0] = -1
        return out


[docs] def store_segment_ids(store: str | Path, *, level: int = 0) -> npt.NDArray[np.uint64]: """The segment id of each object at ``level``, indexed by object id. Raises: ValueError: The store has no ``segment_id`` at ``level`` or level 0. """ from zarr_vectors.building import get_resolution_level, open_store, read_object_attributes root = open_store(str(store)) for source in dict.fromkeys((level, 0)): try: values = read_object_attributes(get_resolution_level(root, source), SEGMENT_ID_ATTR) except Exception: # noqa: BLE001 - absent here; try level 0 continue return np.asarray(values).reshape(-1).astype(np.uint64) raise ValueError( f"{store} has no object_attributes/{SEGMENT_ID_ATTR} at level {level} or 0; " f"segment ids come from the precomputed ingests and the synapse join" )
def _is_na(value: Any) -> bool: try: import pandas as pd return bool(pd.isna(value)) except (TypeError, ValueError): return False