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
2 changes: 2 additions & 0 deletions src/ndr/format/smartspim/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,6 +23,7 @@
"readAcquisitionMetadata",
"readAllChannelsInfo",
"readAllChannelsVolume",
"readImsNotes",
"readStitcherXml",
"readTileInfo",
"readTileVolume",
Expand Down
54 changes: 34 additions & 20 deletions src/ndr/format/smartspim/listChannels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down Expand Up @@ -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_<laser>_Em_<filter>``, with no ``_Ch<n>``;
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<n>`` raise :class:`ValueError` (MATLAB:
Some versions of the SmartSPIM software (6.0) name channel folders
``Ex_<laser>_Em_<filter>``, with no ``_Ch<n>`` (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<k>`` 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.")
Expand All @@ -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<n>" filter-channel number, so which All_Channels "_ch<k>" slices '
"belong to which channel is not known. Only a single channel folder may omit "
'"_Ch<n>".'
)

laser_by_wavelength: dict[str, dict[str, float]] = {}
num_tiles_by_name: dict[str, int] = {}
tiles: list[dict[str, Any]] = []
Expand Down Expand Up @@ -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<n>": 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,
Expand All @@ -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<k> is whose would be a guess -- unless
# SmartSPIM's IMS_Notes.txt names every such folder's Ch<k>.
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<n>" filter-channel number that metadata.json or '
'IMS_Notes.txt supplies, so which All_Channels "_ch<k>" slices belong to '
'which channel is not known. Only a single channel folder may omit "_Ch<n>" '
"without one."
)
return channels
25 changes: 23 additions & 2 deletions src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -40,6 +40,10 @@ functions:
its laser and filter; several channel folders when any lacks _Ch<n>
raise ValueError (MATLAB ndr:format:smartspim:listChannels:
UnnumberedChannels) rather than guess which _ch<k> slices are whose.
2026-11-12: synchronized with NDR-matlab a77f2d6: a folder without
_Ch<n> 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"
Expand Down Expand Up @@ -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
Expand All @@ -159,6 +163,23 @@ functions:
2026-11-10: synchronized with NDR-matlab 147073c: slices named
Z<z*10>_Ch<k>.tif(f) are read too, and a lone channel folder without
_Ch<n> takes whichever single _ch<k> its slices carry.
2026-11-12: synchronized with NDR-matlab a77f2d6: a channel's _ch<k>
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 <channel>_stitched is represented as Ch<k> ..."), 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"
Expand Down
85 changes: 75 additions & 10 deletions src/ndr/format/smartspim/readAllChannelsInfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,17 @@
``<channel>_MIP_stitched`` folder, whose files carry the same ``_ch<k>``
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<n>`` (``Ex_<laser>_Em_<filter>``; see :func:`listChannels`) takes
whichever one ``_ch<k>`` the slices carry.
(Ch1 -> ch0, Ch2 -> ch1, ...). Between the two, ``IMS_Notes.txt`` ("The
folder <channel>_stitched is represented as Ch<k>", 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<n>`` (``Ex_<laser>_Em_<filter>``) gets its
filter-channel number from metadata.json (see :func:`listChannels`); a single
one takes whichever one ``_ch<k>`` 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
Expand All @@ -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"]

Expand Down Expand Up @@ -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<n>`` (SmartSPIM 6.0) and no direct record
of which ``_Ch<k>`` 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<n>" and nothing records which '
'All_Channels "_ch<k>" 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<k>, and whether it came from the filter-channel rank."""
# Preferred: the single _ch<k> suffix used in <channel>_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
# <channel>_stitched is represented as Ch<k>").
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
Expand Down Expand Up @@ -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<n>" (listChannels refuses
# several): its slices are the only _ch<k> 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<n>": its slices are the only
# _ch<k> 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<k> index in {rootDir}.")

Expand Down
42 changes: 42 additions & 0 deletions src/ndr/format/smartspim/readImsNotes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""SmartSPIM's record of which channel folder is which ``Ch<k>``.

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<k>``.

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 ``<channel>_stitched`` folder without ``_stitched``) and
``chIndex`` (float, the ``k`` of that channel's ``All_Channels``
``_Ch<k>`` 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)
]
Loading
Loading