Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ These rules override other implementation preferences.
`mask_file`, `y0/y1/x0/x1`, `z0/z1`, `t`, `c`, `label_id`,
`center_y`/`center_x`/`center_z`, `touches_border`, `area_px`,
`patch_file`, `output_height`/`output_width`, `config_file`, `valid`,
`reason`, `source_relative_path`, `object_set`, `channel_id`). These are exactly the columns written to the exported metadata
`reason`, `source_relative_path`, `object_set`, `channel_id`, `channel_ids`). These are exactly the columns written to the exported metadata
CSV (`save_metadata_csv` in `src/cellpatcher/export.py`, plus the
computed `height`/`width` convenience columns from `PatchRegion.to_dict()`),
and downstream repos may already depend on them. New fields may be
Expand Down Expand Up @@ -489,7 +489,11 @@ bricks (core dependencies, pinned tags in `setup.py`), CellPatcher:
November 2026): in a file run those of the run's description, checked by
`RunInputs.resolve_request` (CP-3), in memory `image_metadata["channel_ids"]`;
each ID is the C index it has in each image (each split patch's `channel_id`
names its channel, `patch_id` keeps `c`) (follow-up C5).
names its channel, `patch_id` keeps `c`) (follow-up C5);
- records on every patch of a described run the ID of each channel plane it holds,
in its own C order (`channel_ids`, `;`-separated in `patches.csv`; issue #125), whatever
the normalization and splitting settings: a reader matches planes to channels by it,
never by position.

The notebook offers all of these, with the image type taken from the
run's description by `statistics.recorded_image_type` (follow-up C4; `Fov.image_type` since CP-4). In summary:
Expand Down
3 changes: 2 additions & 1 deletion docs/configuration_reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,9 @@ Every generated patch is a `PatchRegion` dataclass. The fields below are populat
| `output_axes` | `str \| None` | Axes of the delivered/exported array, in order: `common.image_axes` without the Z/T axes a plane policy resolved and, for split channels, without `C` (e.g. `"CYX"`, `"YX"`, `"ZCYX"` with `z_policy="keep"`). Exported TIFF/NPY files carry no axes of their own. `None` unless arrays were extracted. |
| `object_set` | `str \| None` | Cell mode: the object set (mask) the patch's `label_id` belongs to (see "Patch identity" above); `None` in other modes. |
| `channel_id` | `str \| None` | The canonical channel ID of the patch's `c` in its own image (CP-3): in a file run, the run's description through `RunInputs` (`Fov.channel_ids[c]`), so one channel has one ID whatever its C index in each image; in memory, `image_metadata["channel_ids"][c]` when given. `None` for a patch without `c` (every channel in one patch, or no C axis). Appended after the patch-geometry contract columns (`requested_*` ... `square_index`); `patch_id` keeps `c` and is never parsed for it. |
| `channel_ids` | `tuple[str, ...] \| None` | The canonical ID of every channel plane the patch holds, **in its own C order**, `;`-separated in `patches.csv` (`DNA;ACTIN`; issue #125). Filled for every patch of a described run whatever the normalization and splitting settings: a patch of every channel has its image's `Fov.channel_ids` (the run's description through `RunInputs`, the order the resolver's selections index), a split-channel patch its one `channel_id`, an image without a C axis its one ID. Two units that store the same channels in different orders therefore give patches with different `channel_ids`, and a reader matches each array plane to its channel by this column, never by position. In memory, from `image_metadata["channel_ids"]` (the same rules); `None` for an image without them, and for a plane without C axis and without `image_metadata["c"]` given the IDs of several channels (which one it is is not known). With normalization it equals `normalization_channels`. Appended after `channel_id`; read back by `read_patch_table` as a tuple. |

The geometry columns come after every earlier one, `object_set` after them, then the patch-geometry contract columns and `channel_id`, so the order of the existing columns does not change.
The geometry columns come after every earlier one, `object_set` after them, then the patch-geometry contract columns, `channel_id` and `channel_ids`, so the order of the existing columns does not change.

### Shared MorphoBricks CSV contract

Expand Down
2 changes: 1 addition & 1 deletion docs/normalization_contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ empty and there are no channel pairs.
| `normalization_group` | text | §7 group key |
| `normalization_exact` | `true`/`false` | `true` when every channel's parameters are exact (§6) |
| `normalization_parameters_version` | `2` | The parameter columns' version (normalization v0.5.0); a row without it is refused on load |
| `normalization_channels` | text | The patch's channel IDs in its own C order, `;`-separated; each channel is normalized with its ID's pair |
| `normalization_channels` | text | The patch's channel IDs in its own C order, `;`-separated; each channel is normalized with its ID's pair. The same IDs are in the `channel_ids` column of every patch, with or without normalization (issue #125, configuration reference) |
| `Normalization_Offset_<ID>` | number | Offset of channel ID `<ID>` (a file run: the description's ID of each C index, `Fov.channel_ids`, which must equal the `plane_histograms.csv` row's, else `channel_id_mismatch`; in memory, `image_metadata["channel_ids"]`, compared with the rows the same way. At a CSV scope an image of more than one channel without them is refused before any fit, `channel_ids_required` (v0.7.1; never matched by position), as is one plane of a multichannel image that its `image_metadata["c"]` does not name, without them or given the IDs of all its image's channels; at the patch scope, without IDs: `C<i>` by position, `R`/`G`/`B` for RGB) |
| `Normalization_Scale_<ID>` | number | Scale of channel ID `<ID>` |

Expand Down
35 changes: 35 additions & 0 deletions notebooks/CellPatcher/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,41 @@ Release v0.3.0
Pin preprocessing v0.4.0rc4; prepare v0.2.0rc2

---
## [Unreleased] - Channel IDs on every patch (#125)

For v0.7.2. Found by the S3.4 adversarial suite (MorphoFeature draft PR #240, gate G3).

### Fixed
- **#125: every patch of a described run records its channel IDs, in its C order.** Without normalization and
without channel splitting, v0.7.1 recorded no channel ID at all (`c`, `channel_id` and `normalization_channels`
empty, on the patch and in `patches.csv`), so the patches of two units storing DNA, ACTIN and ACTIN, DNA could
only be told apart by assuming the channel order. The new field `PatchRegion.channel_ids` (column `channel_ids`,
`;`-separated, after `channel_id`) holds the ID of every channel plane the patch holds, in its C order, from the
run's description (`Fov.channel_ids`, the order the resolver's selections index): every ID of the image for a
patch of every channel, `(channel_id,)` for a split-channel patch, the one ID of an image without a C axis. It is
filled whatever the normalization and splitting settings, and equals `normalization_channels` when normalizing.
In memory it comes from `image_metadata["channel_ids"]` by the same rules, and stays `None` for an image without
them (as documented, nothing is taken by position), and for a plane without C axis and without
`image_metadata["c"]` given the IDs of several channels. No existing field was used: `channel_id` names the one
channel of a patch with `c`, and `normalization_channels` is documented as empty without normalization and is
written only with the parameter columns. `tests/test_patch_channel_ids.py` (Spec v04 with the G4 suite's pixels:
a plane depends on the image and the channel ID, never the C index, so the IDs are checked against the pixels).
In memory, an image with several channels along C given `image_metadata["channel_ids"]` and `image_metadata["c"]`
(without splitting) is refused: its patches hold every channel, so `c` would have labelled them with one ID
(review of #127).

### Changed
- **Outputs:** `patches.csv` has one new last field column, `channel_ids` (before the dynamic `mask_fraction_*`
columns); every other column, value, patch file, `images.csv` and `positions.csv` is unchanged. The parity golden
`tests/fixtures/v062_parity/digests.json` changes in its 57 `patches.csv` digests only, one per table of every
case: each new table with its `channel_ids` column removed has the v0.6.2 digest again (`DNA;ACTIN` in every row,
the C order of Spec fixtures v07, v08 and v13; the grid tables there have no rows, so only their header changed).
`tests/test_patch_geometry.py` expects the column after `channel_id`.
- **Reading:** `read_patch_table` (and `ExportedPatchTorchDataset`, which checks the same columns) refuses a table
without the `channel_ids` column, like any table missing a column CellPatcher writes (nothing is defaulted): a
table written by v0.7.1 or earlier must be written again by running CellPatcher again. A `channel_ids` cell is
read as a tuple and checked with the normalization brick's `check_channel_ids`.

## [0.7.1] - 2026-11-16 - Fixes from the external audit of v0.7.0 (CP1, CP2, CP3, F3, F4); preprocessing v0.6.1

The v0.7.1 patch release (16 November 2026), from #121 and its review #123: fixes for the defects an external audit
Expand Down
9 changes: 7 additions & 2 deletions src/cellpatcher/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from cellpatcher.positions import POSITION_TABLE_FILENAME, save_position_table_csv
from cellpatcher.types import (
_NOT_COLUMNS,
CHANNEL_SEPARATOR,
IMAGE_TABLE_COLUMNS,
MASK_FRACTION_PREFIX,
NORMALIZATION_CHANNELS_COLUMN,
Expand Down Expand Up @@ -234,7 +235,7 @@ class PatchTableError(ValueError):


def _field_kinds() -> dict[str, tuple[type, bool]]:
"""PatchRegion column -> (int, float, bool or str; whether it may be None)."""
"""PatchRegion column -> (int, float, bool, str or tuple, the channel IDs; whether it may be None)."""
import typing

hints = typing.get_type_hints(PatchRegion)
Expand All @@ -245,7 +246,7 @@ def _field_kinds() -> dict[str, tuple[type, bool]]:
arguments = typing.get_args(hints[item.name])
optional = type(None) in arguments
base = next((kind for kind in (arguments or (hints[item.name],)) if kind is not type(None)), str)
kinds[item.name] = (base, optional)
kinds[item.name] = (tuple if typing.get_origin(base) is tuple else base, optional)
return kinds


Expand All @@ -257,6 +258,10 @@ def _typed(text: str, kind: type, optional: bool, column: str):
raise ValueError(f"{column} is empty")
if kind is str:
return text
if kind is tuple: # channel_ids: canonical channel IDs in C order, ";"-separated (issue #125)
from morphobricks_normalization.channels import check_channel_ids

return check_channel_ids(text.split(CHANNEL_SEPARATOR), column)
if kind is bool:
value = _BOOLEAN_TEXT.get(text.lower())
if value is None:
Expand Down
36 changes: 28 additions & 8 deletions src/cellpatcher/ids.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,12 +330,17 @@ def stamp_channel_ids(
images: Sequence | None = None,
image_axes: str | None = None,
) -> None:
"""Set each patch's ``channel_id``: the canonical ID of its channel ``c`` (CP-3).
"""Set each patch's ``channel_id`` (CP-3) and ``channel_ids`` (issue #125) from its image's channel IDs.

``image_metadata[i]["channel_ids"]`` is the ID of every C index of image *i*, in C order; a
file run gives each image's own (``Fov.channel_ids`` through ``RunInputs``, so one ID may be
a different C index in another image). A patch without ``c`` (every channel in one patch,
or an image without a C axis) gets none. ``patch_id`` is not changed: it keeps ``c``.
a different C index in another image). ``channel_id`` is the ID of the patch's ``c``; a patch
without ``c`` (every channel in one patch, or an image without a C axis) gets none.
``channel_ids`` is the ID of every channel plane the patch holds, in its C order, whatever the
normalization and splitting settings: ``(channel_id,)`` with ``c``, every ID of an image with a
C axis, and the one ID of an image without one. A plane without C axis or ``c`` given the IDs of
several channels gets none: which of them it is is not known, and nothing is taken by position.
An image without IDs gives no patch either. ``patch_id`` is not changed: it keeps ``c``.

Every image's IDs are checked first, whether or not it gave patches or its channels are split:
distinct canonical IDs (the normalization brick's ``check_channel_ids``) and, when *images* and
Expand All @@ -345,13 +350,16 @@ def stamp_channel_ids(
------
ValueError
If ``channel_ids`` are not distinct canonical IDs, are not one per C index of an image with a
C axis, or hold no ID for a patch's ``c``.
C axis, or hold no ID for a patch's ``c``; or if an image given them has several channels along
C and ``image_metadata["c"]`` too (its patches hold every channel, not the one ``c`` names).
"""
from morphobricks_normalization.channels import check_channel_ids

per_image = {}
has_c_axis = {}
for index, meta in enumerate(image_metadata or ()):
ids = (meta or {}).get("channel_ids")
count = None
if ids is not None:
where = f'image {index}: image_metadata["channel_ids"]'
ids = check_channel_ids(ids, where) # e.g. ("DNA", "DNA") refused
Expand All @@ -361,11 +369,23 @@ def stamp_channel_ids(
f"{where} names {len(ids)} channel(s) ({', '.join(ids)}) for an image with {count} channel(s) "
"along C: give exactly one ID per C index, in C order."
)
if count is not None and count > 1 and plane_index(meta, "c") is not None:
# Its patches hold every channel plane: c would name one of them as the patch's channel.
raise ValueError(
f'image {index}: image_metadata["c"]={meta["c"]!r} names one channel plane, but the image holds '
f"{count} channels along C ({', '.join(ids)}): give c only for an image that is one channel "
"plane (no C axis), or split its channels with extraction.split_channels."
)
per_image[f"image_{index:04d}"] = ids
has_c_axis[f"image_{index:04d}"] = count is not None
for patch in patches:
ids = per_image.get(patch.image_id)
if ids is None or patch.c is None:
if ids is None:
continue
if patch.c >= len(ids):
raise ValueError(f'image_metadata["channel_ids"] names {len(ids)} channels, none for c={patch.c}.')
patch.channel_id = ids[patch.c]
if patch.c is not None:
if patch.c >= len(ids):
raise ValueError(f'image_metadata["channel_ids"] names {len(ids)} channels, none for c={patch.c}.')
patch.channel_id = ids[patch.c]
patch.channel_ids = (patch.channel_id,)
elif has_c_axis[patch.image_id] or len(ids) == 1:
patch.channel_ids = tuple(ids)
18 changes: 18 additions & 0 deletions src/cellpatcher/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ class PatchRegion:
- ``normalization_channels``: the patch's channel IDs in its own C order
(``None`` without normalization), written as the ``;``-separated column
``normalization_channels`` beside the parameter columns.
- ``channel_ids``: the canonical ID of every channel plane the patch holds,
in its own C order (issue #125): a described run's ``Fov.channel_ids``
for a patch of every channel, ``(channel_id,)`` for a patch of one
channel; in memory, from ``image_metadata["channel_ids"]``. Filled
whatever the normalization and splitting settings; ``None`` without IDs,
or for a plane without ``c`` given the IDs of several channels. Written
as the ``;``-separated column ``channel_ids``.
- ``image_height``, ``image_width``: the Y/X size of the source image
(plane) the rectangle ``y0/y1/x0/x1`` lies in; set by ``run_patching``
for every patch, whether or not arrays are extracted.
Expand Down Expand Up @@ -178,6 +185,12 @@ class PatchRegion:
# one channel has one ID whatever its C index in each image; None without c. Appended after every
# earlier field so existing CSV columns keep their order; patch_id keeps c.
channel_id: str | None = None
# The canonical ID of every channel plane the patch holds, in its C order (issue #125): a described
# run's Fov.channel_ids (the order the resolver's selections index), or (channel_id,) for a patch of
# one channel; in memory image_metadata["channel_ids"]. Filled whatever the normalization and
# splitting settings; None only without IDs. Written as the ";"-separated channel_ids column, after
# channel_id, so existing CSV columns keep their order.
channel_ids: tuple[str, ...] | None = None
# Mask name -> share of y0/y1/x0/x1 in that mask's foreground, for the
# fraction masks given to run_patching; cell patches also carry
# "own_object" (the share inside the object's own label). Not a column
Expand Down Expand Up @@ -228,13 +241,18 @@ def to_dict(self) -> dict:
data = {f.name: getattr(self, f.name) for f in fields(self) if f.name not in _NOT_COLUMNS}
data["height"] = self.height
data["width"] = self.width
if self.channel_ids is not None:
data["channel_ids"] = CHANNEL_SEPARATOR.join(self.channel_ids)
if self.normalization_parameters is not None:
data.update(normalization_channel_columns(self.normalization_parameters, self.normalization_channels))
for name, fraction in (self.mask_fractions or {}).items():
data[f"{MASK_FRACTION_PREFIX}{name}"] = fraction
return data


CHANNEL_SEPARATOR = ";"
"""The separator of the channel IDs of one ``patches.csv`` cell (``channel_ids``, ``normalization_channels``)."""

# PatchRegion fields written as several columns of their own, not as one.
_NOT_COLUMNS = ("normalization_parameters", "normalization_channels", "mask_fractions")
MASK_FRACTION_PREFIX = "mask_fraction_"
Expand Down
Loading
Loading