|
| 1 | +"""ABISS external wrapper decoder. |
| 2 | +
|
| 3 | +This module exposes a decoder that bridges prediction tensors to an external |
| 4 | +ABISS (or ABISS-compatible) command-line pipeline. |
| 5 | +
|
| 6 | +The wrapper writes predictions to temporary files, runs a user-specified |
| 7 | +command, then reads back an instance-label segmentation. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +from pathlib import Path |
| 13 | +from tempfile import TemporaryDirectory |
| 14 | +from typing import Any, Dict, List, Mapping, Optional, Sequence |
| 15 | +import os |
| 16 | +import subprocess |
| 17 | + |
| 18 | +import numpy as np |
| 19 | + |
| 20 | +from connectomics.data.io import read_hdf5, write_hdf5 |
| 21 | + |
| 22 | +from .utils import cast2dtype |
| 23 | + |
| 24 | +__all__ = ["decode_abiss"] |
| 25 | + |
| 26 | + |
| 27 | +def _format_command( |
| 28 | + command: str | Sequence[str], |
| 29 | + mapping: Mapping[str, str], |
| 30 | +) -> tuple[str | List[str], bool]: |
| 31 | + """Format command placeholders for shell/list execution.""" |
| 32 | + if isinstance(command, str): |
| 33 | + return command.format(**mapping), True |
| 34 | + if isinstance(command, Sequence): |
| 35 | + return [str(part).format(**mapping) for part in command], False |
| 36 | + raise TypeError(f"`command` must be str or sequence[str], got {type(command).__name__}.") |
| 37 | + |
| 38 | + |
| 39 | +def _load_output(output_h5: Path, output_npy: Path, output_dataset: str) -> np.ndarray: |
| 40 | + """Load decoded segmentation output from file.""" |
| 41 | + if output_h5.exists(): |
| 42 | + seg = read_hdf5(str(output_h5), dataset=output_dataset) |
| 43 | + elif output_npy.exists(): |
| 44 | + seg = np.load(output_npy) |
| 45 | + else: |
| 46 | + raise FileNotFoundError( |
| 47 | + "decode_abiss did not produce output file. " |
| 48 | + f"Expected one of: {output_h5}, {output_npy}" |
| 49 | + ) |
| 50 | + |
| 51 | + seg = np.asarray(seg) |
| 52 | + if seg.ndim == 4 and seg.shape[0] == 1: |
| 53 | + seg = seg[0] |
| 54 | + if seg.ndim != 3: |
| 55 | + raise ValueError( |
| 56 | + "decode_abiss output must be 3D label volume (Z, Y, X) " |
| 57 | + f"or singleton-channel 4D; got shape {seg.shape}." |
| 58 | + ) |
| 59 | + |
| 60 | + if not np.issubdtype(seg.dtype, np.integer): |
| 61 | + seg = np.rint(seg).astype(np.uint64, copy=False) |
| 62 | + |
| 63 | + return cast2dtype(seg) |
| 64 | + |
| 65 | + |
| 66 | +def decode_abiss( |
| 67 | + predictions: np.ndarray, |
| 68 | + command: str | Sequence[str], |
| 69 | + *, |
| 70 | + input_dataset: str = "main", |
| 71 | + output_dataset: str = "main", |
| 72 | + channels: Optional[Sequence[int]] = None, |
| 73 | + workdir: Optional[str] = None, |
| 74 | + keep_workspace: bool = False, |
| 75 | + timeout_sec: Optional[int] = None, |
| 76 | + env: Optional[Dict[str, Any]] = None, |
| 77 | + check: bool = True, |
| 78 | +) -> np.ndarray: |
| 79 | + """Decode instance segmentation with an external ABISS command. |
| 80 | +
|
| 81 | + Args: |
| 82 | + predictions: Model output, typically shape ``(C, Z, Y, X)``. |
| 83 | + command: External command to execute. Supports placeholders: |
| 84 | + - ``{workspace}``: working directory path |
| 85 | + - ``{input_h5}``, ``{input_npy}``: prediction file paths |
| 86 | + - ``{output_h5}``, ``{output_npy}``: expected output file paths |
| 87 | + - ``{input_dataset}``, ``{output_dataset}``: HDF5 dataset names |
| 88 | + input_dataset: Dataset name when writing input HDF5. |
| 89 | + output_dataset: Dataset name when reading output HDF5. |
| 90 | + channels: Optional channel indices to select before saving input. |
| 91 | + workdir: Optional fixed workspace directory. If None, uses temp dir. |
| 92 | + keep_workspace: Keep temp workspace when using auto temp dir. |
| 93 | + timeout_sec: Optional subprocess timeout in seconds. |
| 94 | + env: Optional extra environment variables for subprocess. |
| 95 | + check: Raise on non-zero return code if True. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + 3D instance label volume ``(Z, Y, X)``. |
| 99 | + """ |
| 100 | + pred = np.asarray(predictions) |
| 101 | + if pred.ndim not in (3, 4): |
| 102 | + raise ValueError( |
| 103 | + f"decode_abiss expects 3D/4D predictions, got shape {pred.shape}." |
| 104 | + ) |
| 105 | + |
| 106 | + if channels is not None: |
| 107 | + if pred.ndim != 4: |
| 108 | + raise ValueError("`channels` can only be used for 4D predictions (C, Z, Y, X).") |
| 109 | + pred = pred[np.asarray(channels)] |
| 110 | + |
| 111 | + if workdir is not None: |
| 112 | + workspace_path = Path(workdir).resolve() |
| 113 | + workspace_path.mkdir(parents=True, exist_ok=True) |
| 114 | + temp_ctx = None |
| 115 | + else: |
| 116 | + temp_ctx = TemporaryDirectory(prefix="decode_abiss_") |
| 117 | + workspace_path = Path(temp_ctx.name).resolve() |
| 118 | + |
| 119 | + try: |
| 120 | + input_h5 = workspace_path / "predictions.h5" |
| 121 | + input_npy = workspace_path / "predictions.npy" |
| 122 | + output_h5 = workspace_path / "segmentation.h5" |
| 123 | + output_npy = workspace_path / "segmentation.npy" |
| 124 | + |
| 125 | + # Save both formats so external command can choose the easiest input. |
| 126 | + write_hdf5(str(input_h5), pred, dataset=input_dataset) |
| 127 | + np.save(input_npy, pred) |
| 128 | + |
| 129 | + mapping = { |
| 130 | + "workspace": str(workspace_path), |
| 131 | + "input_h5": str(input_h5), |
| 132 | + "input_npy": str(input_npy), |
| 133 | + "output_h5": str(output_h5), |
| 134 | + "output_npy": str(output_npy), |
| 135 | + "input_dataset": input_dataset, |
| 136 | + "output_dataset": output_dataset, |
| 137 | + } |
| 138 | + cmd, use_shell = _format_command(command, mapping) |
| 139 | + |
| 140 | + proc_env = os.environ.copy() |
| 141 | + if env: |
| 142 | + proc_env.update({str(k): str(v) for k, v in env.items()}) |
| 143 | + |
| 144 | + subprocess.run( |
| 145 | + cmd, |
| 146 | + shell=use_shell, |
| 147 | + env=proc_env, |
| 148 | + cwd=str(workspace_path), |
| 149 | + check=check, |
| 150 | + timeout=timeout_sec, |
| 151 | + ) |
| 152 | + |
| 153 | + return _load_output(output_h5=output_h5, output_npy=output_npy, output_dataset=output_dataset) |
| 154 | + finally: |
| 155 | + if temp_ctx is not None and not keep_workspace: |
| 156 | + temp_ctx.cleanup() |
0 commit comments