diff --git a/src/ndr/format/smartspim/__init__.py b/src/ndr/format/smartspim/__init__.py index 74da2cb..b29da6f 100644 --- a/src/ndr/format/smartspim/__init__.py +++ b/src/ndr/format/smartspim/__init__.py @@ -10,6 +10,7 @@ from ndr.format.smartspim.readAcquisitionMetadata import readAcquisitionMetadata from ndr.format.smartspim.readAllChannelsInfo import readAllChannelsInfo from ndr.format.smartspim.readAllChannelsVolume import readAllChannelsVolume +from ndr.format.smartspim.readImsNotes import readImsNotes from ndr.format.smartspim.readStitcherXml import readStitcherXml from ndr.format.smartspim.readTileInfo import readTileInfo from ndr.format.smartspim.readTileVolume import readTileVolume @@ -22,6 +23,7 @@ "readAcquisitionMetadata", "readAllChannelsInfo", "readAllChannelsVolume", + "readImsNotes", "readStitcherXml", "readTileInfo", "readTileVolume", diff --git a/src/ndr/format/smartspim/listChannels.py b/src/ndr/format/smartspim/listChannels.py index f487c89..dabd250 100644 --- a/src/ndr/format/smartspim/listChannels.py +++ b/src/ndr/format/smartspim/listChannels.py @@ -13,6 +13,7 @@ from pydantic import validate_call from ndr.format.smartspim.readAcquisitionMetadata import readAcquisitionMetadata +from ndr.format.smartspim.readImsNotes import readImsNotes __all__ = ["listChannels"] @@ -62,14 +63,17 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: 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: + Some versions of the SmartSPIM software (6.0) name channel folders + ``Ex__Em_``, with no ``_Ch`` (metadata.json's + ``subfolder_format_string`` says so). Such a folder's ``filterChannel`` + is then taken from metadata.json's tiles of its laser and filter, when + they all give one number, and is NaN otherwise (its ``numTiles`` counts + those tiles). Several channel folders of which one has no filter-channel + number from either source, and is not named in ``IMS_Notes.txt`` + (:func:`readImsNotes`), 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. + could swap two channels unnoticed. A single channel folder may lack one. """ if not rootDir: raise ValueError("rootDir must be a non-empty string.") @@ -80,16 +84,6 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: 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]] = [] @@ -124,10 +118,15 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: 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") + # A folder without "_Ch": metadata.json's tiles of its laser and + # filter give its filter-channel number (when they agree on one) + # and its tile count. + mine = [t for t in tiles if t["laser"] == wavelength and t["filter"] == filter_name] + if mine: + n = float(len(mine)) + fch = {t["filterChannel"] for t in mine if not math.isnan(t["filterChannel"])} + if len(fch) == 1: + filter_channel = float(fch.pop()) channels.append( { "name": name, @@ -139,4 +138,19 @@ def listChannels(rootDir: str) -> list[dict[str, Any]]: "numTiles": n, } ) + unresolved = [c["name"] for c in channels if math.isnan(c["filterChannel"])] + if len(channels) > 1 and unresolved: + # Which All_Channels _Ch is whose would be a guess -- unless + # SmartSPIM's IMS_Notes.txt names every such folder's Ch. + noted = {n["channelName"] for n in readImsNotes(rootDir)} + missing = [n for n in unresolved if n not in noted] + if missing: + which = "one has" if len(missing) == 1 else f"{len(missing)} have" + raise ValueError( + f"{rootDir} has {len(names)} channel folders ({', '.join(names)}), and " + f'{which} no "_Ch" filter-channel number that metadata.json or ' + 'IMS_Notes.txt supplies, so which All_Channels "_ch" slices belong to ' + 'which channel is not known. Only a single channel folder may omit "_Ch" ' + "without one." + ) return channels diff --git a/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml b/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml index 083c194..479b2a9 100644 --- a/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml +++ b/src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml @@ -22,7 +22,7 @@ functions: - name: listChannels matlab_path: "+ndr/+format/+smartspim/listChannels.m" status: regular_port - matlab_last_sync_hash: "147073c" + matlab_last_sync_hash: "a77f2d6" python_path: "ndr/format/smartspim/listChannels.py" decision_log: >- Enumerates channel directories under rootDir and enriches each with @@ -40,6 +40,10 @@ functions: 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. + 2026-11-12: synchronized with NDR-matlab a77f2d6: a folder without + _Ch takes its filterChannel from metadata.json's tiles of its laser + and filter when they all give one number; several folders are refused + only when one still has no number and IMS_Notes.txt does not name it. - name: listTiles matlab_path: "+ndr/+format/+smartspim/listTiles.m" @@ -135,7 +139,7 @@ functions: - name: readAllChannelsInfo matlab_path: "+ndr/+format/+smartspim/readAllChannelsInfo.m" status: regular_port - matlab_last_sync_hash: "147073c" + matlab_last_sync_hash: "a77f2d6" python_path: "ndr/format/smartspim/readAllChannelsInfo.py" decision_log: >- Indexes SmartSPIM AutoStitch's stitched output @@ -159,6 +163,23 @@ functions: 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. + 2026-11-12: synchronized with NDR-matlab a77f2d6: a channel's _ch + comes from its _MIP_stitched suffix, else IMS_Notes.txt (readImsNotes), + else the filter-channel rank; unnumbered folders mapped by rank raise + ValueError (MATLAB ChannelOrderDisagrees) when that rank and the order + the channels first appear in metadata.json's tiles disagree. + + - name: readImsNotes + matlab_path: "+ndr/+format/+smartspim/readImsNotes.m" + status: regular_port + matlab_last_sync_hash: "a77f2d6" + python_path: "ndr/format/smartspim/readImsNotes.py" + decision_log: >- + Reads IMS_Notes.txt, the note SmartSPIM writes beside Convert2IMS.bat + ("The folder _stitched is represented as Ch ..."), into one + dict per channel (channelName, chIndex). readAllChannelsInfo prefers it + to the filter-channel rank. A missing or unreadable file gives [], as + MATLAB gives an empty struct array; it never raises. - 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 e99ebb9..d49efb7 100644 --- a/src/ndr/format/smartspim/readAllChannelsInfo.py +++ b/src/ndr/format/smartspim/readAllChannelsInfo.py @@ -20,9 +20,17 @@ ``_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, ...). A single channel whose folder has no -``_Ch`` (``Ex__Em_``; see :func:`listChannels`) takes -whichever one ``_ch`` the slices carry. +(Ch1 -> ch0, Ch2 -> ch1, ...). Between the two, ``IMS_Notes.txt`` ("The +folder _stitched is represented as Ch", written when SmartSPIM +converts All_Channels to Imaris; :func:`readImsNotes`) is used when it names +the channel; SmartSPIM 6.0 writes no ``_ch`` suffix in ``_MIP_stitched``. A +channel folder without ``_Ch`` (``Ex__Em_``) gets its +filter-channel number from metadata.json (see :func:`listChannels`); a single +one takes whichever one ``_ch`` the slices carry. When such folders are +mapped by filter-channel rank, that rank must match the order the channels +first appear in metadata.json's tiles, or :class:`ValueError` is raised +(MATLAB ``ndr:format:smartspim:readAllChannelsInfo:ChannelOrderDisagrees``): +which order the stitcher follows for them is not yet known. """ from __future__ import annotations @@ -37,6 +45,7 @@ from ndr.format.smartspim.listChannels import listChannels from ndr.format.smartspim.readAcquisitionMetadata import readAcquisitionMetadata +from ndr.format.smartspim.readImsNotes import readImsNotes __all__ = ["readAllChannelsInfo"] @@ -87,16 +96,63 @@ def _index_slices(folder: Path) -> list[tuple[int, int, str]]: return out -def _channel_index(root: Path, channel_name: str, acq_channels: list[dict[str, Any]]) -> int: +def _check_rank_matches_metadata_order(rootDir: str, acq_channels: list[dict[str, Any]]) -> None: + """Refuse when filter-channel order and metadata.json order disagree. + + Channel folders without ``_Ch`` (SmartSPIM 6.0) and no direct record + of which ``_Ch`` is whose: the filter-channel rank decides, as for + numbered folders. Until an acquisition shows which of the two the + stitcher follows there, refuse when that rank and the order the channels + first appear in metadata.json's tiles disagree. + """ + try: + tiles = list(readAcquisitionMetadata(rootDir)["tiles"]) + except (OSError, ValueError): + tiles = [] + first_seen = [] + for c in acq_channels: + j = next( + ( + i + for i, t in enumerate(tiles) + if t["laser"] == c["wavelength"] and t["filter"] == c["filterName"] + ), + math.inf, + ) + first_seen.append(j) + by_filter = sorted(range(len(acq_channels)), key=lambda i: acq_channels[i]["filterChannel"]) + by_metadata = sorted(range(len(acq_channels)), key=lambda i: first_seen[i]) + if math.inf in first_seen or by_filter != by_metadata: + raise ValueError( + f'In {rootDir} the channel folders have no "_Ch" and nothing records which ' + 'All_Channels "_ch" is which channel, and the channels\' filter-channel order ' + f"({', '.join(acq_channels[i]['name'] for i in by_filter)}) differs from the order " + f"they appear in metadata.json ({', '.join(acq_channels[i]['name'] for i in by_metadata)}), " + "so it is not known which order the stitcher used." + ) + + +def _channel_index( + root: Path, + channel_name: str, + acq_channels: list[dict[str, Any]], + notes: list[dict[str, Any]], +) -> tuple[int, bool]: + """The channel's _ch, and whether it came from the filter-channel rank.""" # Preferred: the single _ch suffix used in _MIP_stitched. mip_dir = root / f"{channel_name}_MIP_stitched" if mip_dir.is_dir(): ks = {k for k, _, _ in _index_slices(mip_dir)} if len(ks) == 1: - return ks.pop() + return ks.pop(), False + # Next: SmartSPIM's own statement in IMS_Notes.txt ("The folder + # _stitched is represented as Ch"). + for n in notes: + if n["channelName"] == channel_name: + return int(n["chIndex"]), False # Fallback: rank of the filter-channel number (stable on ties). ranked = sorted(acq_channels, key=lambda c: c["filterChannel"]) - return [c["name"] for c in ranked].index(channel_name) + return [c["name"] for c in ranked].index(channel_name), True @validate_call @@ -143,12 +199,21 @@ def readAllChannelsInfo(rootDir: str, *, ReadHeader: bool = True) -> dict[str, A acq_channels = listChannels(rootDir) names = [c["name"] for c in acq_channels] 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. + if ( + len(acq_channels) == 1 + and not re.search(r"_Ch\d+$", acq_channels[0]["name"]) + and len(ks) == 1 + ): + # A single channel folder without "_Ch": its slices are the only + # _ch there is, whatever number metadata.json gives it. ch_indices = [next(iter(ks))] else: - ch_indices = [_channel_index(root, n, acq_channels) for n in names] + notes = readImsNotes(rootDir) + found = [_channel_index(root, n, acq_channels, notes) for n in names] + ch_indices = [k for k, _ in found] + unnumbered = any(not re.search(r"_Ch\d+$", n) for n in names) + if len(names) > 1 and unnumbered and any(by_rank for _, by_rank in found): + _check_rank_matches_metadata_order(rootDir, acq_channels) 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/src/ndr/format/smartspim/readImsNotes.py b/src/ndr/format/smartspim/readImsNotes.py new file mode 100644 index 0000000..ea4e2a9 --- /dev/null +++ b/src/ndr/format/smartspim/readImsNotes.py @@ -0,0 +1,42 @@ +"""SmartSPIM's record of which channel folder is which ``Ch``. + +Port of ``+ndr/+format/+smartspim/readImsNotes.m``. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any + +__all__ = ["readImsNotes"] + +_LINE_RE = re.compile(r"The folder\s+(\S+?)_stitched\s+is represented as\s+Ch(\d+)", re.IGNORECASE) + + +def readImsNotes(rootDir: Any) -> list[dict[str, Any]]: + """Read ``rootDir/IMS_Notes.txt``: which channel folder is which ``Ch``. + + The SmartSPIM software writes it when it converts the stitched + ``All_Channels`` volume to Imaris, one line per channel, e.g.:: + + The folder Ex_561_Em_561F_stitched is represented as Ch0 with a Hex color value of #ff0000 + + Returns one dict per such line: ``channelName`` (the channel folder, the + named ``_stitched`` folder without ``_stitched``) and + ``chIndex`` (float, the ``k`` of that channel's ``All_Channels`` + ``_Ch`` slices). This is the stitcher's own statement of the mapping, + so :func:`readAllChannelsInfo` prefers it to inferring the mapping from + filter-channel numbers. An absent or unreadable file, or one with no such + lines, gives ``[]``; it never raises. + """ + if not isinstance(rootDir, (str, Path)) or not str(rootDir): + return [] + p = Path(rootDir) / "IMS_Notes.txt" + try: + text = p.read_text(errors="replace") + except OSError: + return [] + return [ + {"channelName": m.group(1), "chIndex": float(m.group(2))} for m in _LINE_RE.finditer(text) + ] diff --git a/tests/test_smartspim_all_channels.py b/tests/test_smartspim_all_channels.py index 3e9b8e5..a4d45e7 100644 --- a/tests/test_smartspim_all_channels.py +++ b/tests/test_smartspim_all_channels.py @@ -14,6 +14,7 @@ from __future__ import annotations +import json import math import shutil from pathlib import Path @@ -30,6 +31,7 @@ listChannels, readAllChannelsInfo, readAllChannelsVolume, + readImsNotes, ) from ndr.reader.smartspim import ndr_reader_smartspim # noqa: E402 from tests._smartspim_fixture import make_example_fixture # noqa: E402 @@ -44,6 +46,17 @@ def fixture_dir(tmp_path): return make_example_fixture(tmp_path, all_channels=True) +def _write_ims_notes(root: Path, rows: list[tuple[str, int]]) -> None: + """IMS_Notes.txt as SmartSPIM writes it.""" + (root / "IMS_Notes.txt").write_text( + "\n\n".join( + f"The folder {name}_stitched is represented as Ch{k} with a Hex color value of #ff0000" + for name, k in rows + ) + + "\n" + ) + + def _all_dir(fixture_dir: Path) -> Path: return fixture_dir / "All_Channels" @@ -115,7 +128,7 @@ def test_single_channel_without_ch_number(self, fixture_dir): (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["filterChannel"] == 2, "from metadata.json's tiles of its laser and filter" assert ch["numTiles"] == 2, "tiles of its laser and filter" assert hasAllChannels(str(root)) is True info = readAllChannelsInfo(str(root)) @@ -125,21 +138,85 @@ def test_single_channel_without_ch_number(self, fixture_dir): 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. + def test_several_channels_numbered_by_metadata(self, fixture_dir): + # SmartSPIM 6.0 names channel folders Ex__Em_ (no + # _Ch); metadata.json's tiles give each its FilterChannel (561F -> + # 2, 640F -> 3) and the filter-channel rank gives _ch. + 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") + ch = listChannels(str(root)) + assert [c["name"] for c in ch] == ["Ex_561_Em_561F", "Ex_640_Em_640F"] + assert [c["filterChannel"] for c in ch] == [2, 3] + assert [c["numTiles"] for c in ch] == [2, 2] + info = readAllChannelsInfo(str(root)) + assert info["channelNames"] == ["Ex_561_Em_561F", "Ex_640_Em_640F"] + vol = readAllChannelsVolume(str(root), "Ex_640_Em_640F") + assert list(vol[:, 0, 0]) == [2000, 2001, 2002, 2003], "640 is _ch1" + # One numbered and one not works the same way. + (root / "Ex_561_Em_561F").rename(root / "Ex_561_Em_561F_Ch2") + info = readAllChannelsInfo(str(root)) + assert info["channelNames"] == ["Ex_561_Em_561F_Ch2", "Ex_640_Em_640F"] + + def test_filter_order_and_metadata_order_must_agree(self, fixture_dir): + # Unnumbered folders mapped by filter-channel rank are refused when + # metadata.json lists the channels in the other order. + 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") + meta_path = root / "metadata.json" + meta = json.loads(meta_path.read_text()) + tiles = meta["tiles"] + meta["tiles"] = [t for t in tiles if t["Laser"] == "640"] + [ + t for t in tiles if t["Laser"] != "640" + ] + meta_path.write_text(json.dumps(meta)) + with pytest.raises(ValueError, match="not known which order the stitcher used"): + readAllChannelsInfo(str(root)) + assert hasAllChannels(str(root)) is False + # A direct record settles it. + _write_ims_notes(root, [("Ex_561_Em_561F", 0), ("Ex_640_Em_640F", 1)]) + info = readAllChannelsInfo(str(root)) + assert info["channelNames"] == ["Ex_561_Em_561F", "Ex_640_Em_640F"] + + def test_several_unnumbered_channels_without_evidence_are_refused(self, fixture_dir): + # No _Ch, no metadata.json numbers, no IMS_Notes.txt: refuse. 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") + (root / "metadata.json").unlink() 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") + # IMS_Notes.txt naming only one of them is not enough. + _write_ims_notes(root, [("Ex_561_Em_561F", 0)]) with pytest.raises(ValueError, match="one has"): listChannels(str(root)) + def test_ims_notes_name_each_channels_slices(self, fixture_dir): + # IMS_Notes.txt is SmartSPIM's own record; it settles unnumbered + # folders and outranks the filter-channel rank (here the opposite). + 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") + (root / "metadata.json").unlink() + _write_ims_notes(root, [("Ex_561_Em_561F", 1), ("Ex_640_Em_640F", 0)]) + notes = readImsNotes(str(root)) + assert notes == [ + {"channelName": "Ex_561_Em_561F", "chIndex": 1.0}, + {"channelName": "Ex_640_Em_640F", "chIndex": 0.0}, + ] + info = readAllChannelsInfo(str(root)) + assert info["channelNames"] == ["Ex_640_Em_640F", "Ex_561_Em_561F"] + vol = readAllChannelsVolume(str(root), "Ex_561_Em_561F") + assert list(vol[:, 0, 0]) == [2000, 2001, 2002, 2003], "561 is _ch1 here" + + def test_read_ims_notes_without_a_file(self, fixture_dir): + assert readImsNotes(str(fixture_dir)) == [] + assert readImsNotes("") == [] + 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)