From 0d68649807e8726501a1df1e490c7b74921ab374 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 17:41:53 +0000 Subject: [PATCH 1/2] SmartSPIM: read Z_Ch.tif slices and a single channel folder without _Ch Port of NDR-matlab 147073c. Some SmartSPIM software versions write a single-channel acquisition with a channel folder named Ex__Em_ (no _Ch) and stitched slices named Z_Ch.tif, which were not recognized. - readAllChannelsInfo accepts Z_Ch.tif(f). - listChannels / isSmartSPIM accept a lone channel folder without _Ch (filterChannel NaN; numTiles counted by laser and filter). Working folders such as _MIP and _stitched are still not channels. - Several channel folders when any lacks _Ch raise ValueError rather than guess which _ch slices are whose. - Bridge: isSmartSPIM, listChannels and readAllChannelsInfo synced to 147073c. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01E59gJ2kMfx16TfRmzo2SnL --- src/ndr/format/smartspim/isSmartSPIM.py | 6 ++- src/ndr/format/smartspim/listChannels.py | 47 +++++++++++++++++-- .../smartspim/ndr_matlab_python_bridge.yaml | 19 ++++++-- .../format/smartspim/readAllChannelsInfo.py | 20 +++++--- tests/test_smartspim_all_channels.py | 45 ++++++++++++++++++ 5 files changed, 122 insertions(+), 15 deletions(-) diff --git a/src/ndr/format/smartspim/isSmartSPIM.py b/src/ndr/format/smartspim/isSmartSPIM.py index 273713f..198a495 100644 --- a/src/ndr/format/smartspim/isSmartSPIM.py +++ b/src/ndr/format/smartspim/isSmartSPIM.py @@ -13,7 +13,7 @@ __all__ = ["isSmartSPIM"] -_CHANNEL_RE = re.compile(r"^Ex_\d+_Em_\w+_Ch\d+$") +_CHANNEL_RE = re.compile(r"^Ex_\d+_Em_(\w+_Ch\d+|[A-Za-z0-9]+)$") @validate_call @@ -25,7 +25,9 @@ def isSmartSPIM(rootDir: str) -> bool: - ``rootDir`` is a folder - ``rootDir/metadata.json`` exists and parses as JSON - ``rootDir`` contains at least one channel directory whose name - matches ``"Ex__Em__Ch"`` + matches ``"Ex__Em__Ch"``, or + ``"Ex__Em_"`` (a single-channel acquisition + from SmartSPIM software that omits the filter-channel number) Any read/parse failure returns FALSE rather than raising, so callers can use this to decide whether to attempt the SmartSPIM code path at diff --git a/src/ndr/format/smartspim/listChannels.py b/src/ndr/format/smartspim/listChannels.py index 09974db..5564488 100644 --- a/src/ndr/format/smartspim/listChannels.py +++ b/src/ndr/format/smartspim/listChannels.py @@ -17,6 +17,11 @@ __all__ = ["listChannels"] _CHANNEL_RE = re.compile(r"^Ex_(\d+)_Em_(.+)_Ch(\d+)$") +# A single channel's folder from SmartSPIM software that omits the +# filter-channel number. The filter name has no underscores, so working +# folders (_MIP, _stitched, _MIDDLE, ...) are not taken for channels. +_UNNUMBERED_RE = re.compile(r"^Ex_(\d+)_Em_([A-Za-z0-9]+)$") +_FOLDER_RE = re.compile(r"^Ex_\d+_Em_(\w+_Ch\d+|[A-Za-z0-9]+)$") def _laser_key(wavelength: float) -> str: @@ -25,9 +30,15 @@ def _laser_key(wavelength: float) -> str: def _parse_channel_name(name: str) -> tuple[float, str, float]: m = _CHANNEL_RE.match(name) + if m: + return float(m.group(1)), m.group(2), float(m.group(3)) + m = _UNNUMBERED_RE.match(name) if not m: - raise ValueError(f'Cannot parse channel name "{name}"; ' 'expected "Ex__Em__Ch".') - return float(m.group(1)), m.group(2), float(m.group(3)) + raise ValueError( + f'Cannot parse channel name "{name}"; expected "Ex__Em__Ch" ' + '(or "Ex__Em_" for a single channel).' + ) + return float(m.group(1)), m.group(2), math.nan @validate_call @@ -39,7 +50,8 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: - ``name``: directory name (e.g. ``"Ex_561_Em_561F_Ch2"``) - ``wavelength``: excitation wavelength (nm) - ``filterName``: emission filter identifier (e.g. ``"561F"``) - - ``filterChannel``: hardware filter channel number + - ``filterChannel``: hardware filter channel number (NaN for a folder + named without ``_Ch``) - ``laserPowerLeft``: left-side laser power percent, NaN if unknown - ``laserPowerRight``: right-side laser power percent, NaN if unknown - ``numTiles``: tile count from ``metadata.json`` (NaN if metadata.json @@ -49,6 +61,15 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: convention. metadata.json is consulted for laser power and per-channel tile counts; missing metadata is tolerated. Sorted alphabetically by name for a stable listing. + + Some versions of the SmartSPIM software name a single-channel + acquisition's folder ``Ex__Em_``, with no ``_Ch``; + that is accepted when it is the only channel folder (its ``numTiles`` + counts metadata.json's tiles of that laser and filter). Several channel + folders when any lacks ``_Ch`` raise :class:`ValueError` (MATLAB: + ``ndr:format:smartspim:listChannels:UnnumberedChannels``): nothing then + says which ``All_Channels`` ``_ch`` slices are whose, and a guess + could swap two channels unnoticed. """ if not rootDir: raise ValueError("rootDir must be a non-empty string.") @@ -56,12 +77,22 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: if not root.is_dir(): raise NotADirectoryError(f"Not a directory: {rootDir}") - names = sorted(e.name for e in root.iterdir() if e.is_dir() and _CHANNEL_RE.match(e.name)) + names = sorted(e.name for e in root.iterdir() if e.is_dir() and _FOLDER_RE.match(e.name)) if not names: raise ValueError(f"No channel directories (Ex_*_Em_*_Ch*) found in {rootDir}") + unnumbered = [n for n in names if not _CHANNEL_RE.match(n)] + if unnumbered and len(names) > 1: + which = "one has" if len(unnumbered) == 1 else f"{len(unnumbered)} have" + raise ValueError( + f"{rootDir} has {len(names)} channel folders ({', '.join(names)}), and {which} " + 'no "_Ch" filter-channel number, so which All_Channels "_ch" slices ' + 'belong to which channel is not known. Only a single channel folder may omit ' + '"_Ch".' + ) laser_by_wavelength: dict[str, dict[str, float]] = {} num_tiles_by_name: dict[str, int] = {} + tiles: list[dict[str, Any]] = [] meta_path = root / "metadata.json" if meta_path.is_file(): try: @@ -70,6 +101,7 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: if math.isnan(lp["wavelength"]): continue laser_by_wavelength[_laser_key(lp["wavelength"])] = lp + tiles = list(meta["tiles"]) for t in meta["tiles"]: cn = t["channelName"] if not cn: @@ -91,6 +123,13 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: left_pct = float("nan") right_pct = float("nan") n = float(num_tiles_by_name.get(name, float("nan"))) + if math.isnan(n) and math.isnan(filter_channel): + # An unnumbered (single) channel folder: count the tiles of its + # laser and filter, whatever filter channel metadata.json gives. + count = sum( + 1 for t in tiles if t["laser"] == wavelength and t["filter"] == filter_name + ) + n = float(count) if count else float("nan") channels.append( { "name": name, diff --git a/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml b/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml index 4a9878f..083c194 100644 --- a/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml +++ b/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml @@ -7,18 +7,22 @@ functions: - name: isSmartSPIM matlab_path: "+ndr/+format/+smartspim/isSmartSPIM.m" status: regular_port - matlab_last_sync_hash: "d329021" + matlab_last_sync_hash: "147073c" python_path: "ndr/format/smartspim/isSmartSPIM.py" decision_log: >- Cheap non-throwing probe: TRUE iff the directory has a metadata.json that parses as JSON AND at least one channel directory whose name matches "Ex__Em__Ch". Straight port using stdlib json + re. + 2026-11-10: synchronized with NDR-matlab 147073c: a channel folder named + Ex__Em_ (no _Ch; filter name without underscores, so + _MIP / _stitched working folders do not count) also marks an + acquisition, as some SmartSPIM software writes for a single channel. - name: listChannels matlab_path: "+ndr/+format/+smartspim/listChannels.m" status: regular_port - matlab_last_sync_hash: "87ef61d" + matlab_last_sync_hash: "147073c" python_path: "ndr/format/smartspim/listChannels.py" decision_log: >- Enumerates channel directories under rootDir and enriches each with @@ -30,6 +34,12 @@ functions: the Python port keys directly on the channel name because Python dict keys have no MATLAB-identifier restriction. Result is a list of dicts sorted alphabetically by name. + 2026-11-10: synchronized with NDR-matlab 147073c: a single channel + folder named Ex__Em_ (no _Ch) is accepted, with + filterChannel NaN and numTiles counted from metadata.json's tiles of + its laser and filter; several channel folders when any lacks _Ch + raise ValueError (MATLAB ndr:format:smartspim:listChannels: + UnnumberedChannels) rather than guess which _ch slices are whose. - name: listTiles matlab_path: "+ndr/+format/+smartspim/listTiles.m" @@ -125,7 +135,7 @@ functions: - name: readAllChannelsInfo matlab_path: "+ndr/+format/+smartspim/readAllChannelsInfo.m" status: regular_port - matlab_last_sync_hash: "15d82e1" + matlab_last_sync_hash: "147073c" python_path: "ndr/format/smartspim/readAllChannelsInfo.py" decision_log: >- Indexes SmartSPIM AutoStitch's stitched output @@ -146,6 +156,9 @@ functions: identifiers map to NotADirectoryError / FileNotFoundError (missing folder, slices or channel) / ValueError (duplicate ch, bad header). + 2026-11-10: synchronized with NDR-matlab 147073c: slices named + Z_Ch.tif(f) are read too, and a lone channel folder without + _Ch takes whichever single _ch its slices carry. - name: readAllChannelsVolume matlab_path: "+ndr/+format/+smartspim/readAllChannelsVolume.m" diff --git a/src/ndr/format/smartspim/readAllChannelsInfo.py b/src/ndr/format/smartspim/readAllChannelsInfo.py index a9ee12a..e99ebb9 100644 --- a/src/ndr/format/smartspim/readAllChannelsInfo.py +++ b/src/ndr/format/smartspim/readAllChannelsInfo.py @@ -12,15 +12,17 @@ ``All_Channels`` is a flat folder of 2-D TIFFs, one per (z, channel), named ``___ch.tiff`` (e.g. ``675050_455000_000110_ch1.tiff``) or, by other versions of the -pipeline, ``_ch.tiff`` (e.g. ``000110_ch1.tiff``), plus an -``ImageList.txt`` for -Imaris. Every slice spans the whole stitched canvas (height = Y, +pipeline, ``_ch.tiff`` (e.g. ``000110_ch1.tiff``) or +``Z_Ch.tif`` (e.g. ``Z000110_Ch0.tif``; case does not matter), +plus an ``ImageList.txt`` for Imaris. Every slice spans the whole stitched canvas (height = Y, width = X), so there are no tiles. The ``ch`` index follows the filter-channel number, NOT the acquisition order. It is taken from the ``_MIP_stitched`` folder, whose files carry the same ``_ch`` suffix; when that folder is absent (e.g. a partial restore), ``k`` is the rank of the channel's filter-channel number among all channels -(Ch1 -> ch0, Ch2 -> ch1, ...). +(Ch1 -> ch0, Ch2 -> ch1, ...). A single channel whose folder has no +``_Ch`` (``Ex__Em_``; see :func:`listChannels`) takes +whichever one ``_ch`` the slices carry. """ from __future__ import annotations @@ -40,7 +42,7 @@ # e.g. 675050_455000_000110_ch0.tiff -> (z*10, k), and, as other versions # of the pipeline name them, without the origins: 000110_ch0.tiff -_SLICE_RE = re.compile(r"^(?:\d+_\d+_)?(\d+)_ch(\d+)\.tiff?$", re.IGNORECASE) +_SLICE_RE = re.compile(r"^(?:\d+_\d+_|Z)?(\d+)_ch(\d+)\.tiff?$", re.IGNORECASE) _MATLAB_CLASS = {"float32": "single", "float64": "double", "bool": "logical"} @@ -140,7 +142,13 @@ def readAllChannelsInfo(rootDir: str, *, ReadHeader: bool = True) -> dict[str, A acq_channels = listChannels(rootDir) names = [c["name"] for c in acq_channels] - ch_indices = [_channel_index(root, n, acq_channels) for n in names] + ks = {kk for kk, _, _ in index} + if len(acq_channels) == 1 and math.isnan(acq_channels[0]["filterChannel"]) and len(ks) == 1: + # A single channel folder without "_Ch" (listChannels refuses + # several): its slices are the only _ch there is. + ch_indices = [next(iter(ks))] + else: + ch_indices = [_channel_index(root, n, acq_channels) for n in names] if len(set(ch_indices)) != len(ch_indices): raise ValueError(f"Two channels map to the same All_Channels _ch index in {rootDir}.") diff --git a/tests/test_smartspim_all_channels.py b/tests/test_smartspim_all_channels.py index ee562d1..3e9b8e5 100644 --- a/tests/test_smartspim_all_channels.py +++ b/tests/test_smartspim_all_channels.py @@ -26,6 +26,8 @@ from ndr.format.smartspim import ( # noqa: E402 hasAllChannels, + isSmartSPIM, + listChannels, readAllChannelsInfo, readAllChannelsVolume, ) @@ -95,6 +97,49 @@ def test_slices_named_without_origins(self, fixture_dir): assert [c["numSlices"] for c in info["channels"]] == [4, 4] assert Path(info["channels"][1]["slicePaths"][-1]).name == "000030_ch1.tiff" + def test_single_channel_without_ch_number(self, fixture_dir): + # Some SmartSPIM software versions name a single channel's folder + # Ex__Em_ (no _Ch) and its stitched slices + # Z_Ch.tif. Working folders beside it are not channels. + root = fixture_dir + shutil.rmtree(root / "Ex_640_Em_640F_Ch3") + for p in _all_dir(root).glob("*_ch1.tiff"): + p.unlink() + (root / "Ex_561_Em_561F_Ch2").rename(root / "Ex_561_Em_561F") + for w in ("_MIP", "_MIP_stitched", "_stitched", "_MIDDLE"): + (root / f"Ex_561_Em_561F{w}").mkdir() + for p in list(_all_dir(root).glob("*_ch0.tiff")): + z = p.name.split("_")[2] + p.rename(p.with_name(f"Z{z}_Ch0.tif")) + assert isSmartSPIM(str(root)) is True + (ch,) = listChannels(str(root)) + assert ch["name"] == "Ex_561_Em_561F" + assert ch["wavelength"] == 561 and ch["filterName"] == "561F" + assert math.isnan(ch["filterChannel"]) + assert ch["numTiles"] == 2, "tiles of its laser and filter" + assert hasAllChannels(str(root)) is True + info = readAllChannelsInfo(str(root)) + assert info["channelNames"] == ["Ex_561_Em_561F"] + assert info["channels"][0]["chIndex"] == 0 + assert info["channels"][0]["numSlices"] == 4 + vol = readAllChannelsVolume(str(root), "Ex_561_Em_561F") + assert list(vol[:, 0, 0]) == [1000, 1001, 1002, 1003], "in z order" + + def test_several_channels_without_ch_number_are_refused(self, fixture_dir): + # Nothing would say which _ch slices are whose: refuse, not guess. + root = fixture_dir + (root / "Ex_561_Em_561F_Ch2").rename(root / "Ex_561_Em_561F") + (root / "Ex_640_Em_640F_Ch3").rename(root / "Ex_640_Em_640F") + with pytest.raises(ValueError, match="Only a single channel folder"): + listChannels(str(root)) + with pytest.raises(ValueError, match="Only a single channel folder"): + readAllChannelsInfo(str(root)) + assert hasAllChannels(str(root)) is False + # One numbered and one not is refused too. + (root / "Ex_561_Em_561F").rename(root / "Ex_561_Em_561F_Ch2") + with pytest.raises(ValueError, match="one has"): + listChannels(str(root)) + def test_two_files_for_one_slice_are_refused(self, fixture_dir): # Same channel and z under two names (tiles, not stitched slices). d = _all_dir(fixture_dir) From 87098c4b5dca8471d5b80a6dd4ba8e654d436802 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 17:43:36 +0000 Subject: [PATCH 2/2] listChannels: black formatting (CI's black 26.10.1) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01E59gJ2kMfx16TfRmzo2SnL --- src/ndr/format/smartspim/listChannels.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/ndr/format/smartspim/listChannels.py b/src/ndr/format/smartspim/listChannels.py index 5564488..f487c89 100644 --- a/src/ndr/format/smartspim/listChannels.py +++ b/src/ndr/format/smartspim/listChannels.py @@ -86,7 +86,7 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: raise ValueError( f"{rootDir} has {len(names)} channel folders ({', '.join(names)}), and {which} " 'no "_Ch" filter-channel number, so which All_Channels "_ch" slices ' - 'belong to which channel is not known. Only a single channel folder may omit ' + "belong to which channel is not known. Only a single channel folder may omit " '"_Ch".' ) @@ -126,9 +126,7 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: if math.isnan(n) and math.isnan(filter_channel): # An unnumbered (single) channel folder: count the tiles of its # laser and filter, whatever filter channel metadata.json gives. - count = sum( - 1 for t in tiles if t["laser"] == wavelength and t["filter"] == filter_name - ) + count = sum(1 for t in tiles if t["laser"] == wavelength and t["filter"] == filter_name) n = float(count) if count else float("nan") channels.append( {