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
6 changes: 4 additions & 2 deletions src/ndr/format/smartspim/isSmartSPIM.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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_<digits>_Em_<chars>_Ch<digits>"``
matches ``"Ex_<digits>_Em_<chars>_Ch<digits>"``, or
``"Ex_<digits>_Em_<letters/digits>"`` (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
Expand Down
45 changes: 41 additions & 4 deletions src/ndr/format/smartspim/listChannels.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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_<n>_Em_<f>_Ch<n>".')
return float(m.group(1)), m.group(2), float(m.group(3))
raise ValueError(
f'Cannot parse channel name "{name}"; expected "Ex_<n>_Em_<f>_Ch<n>" '
'(or "Ex_<n>_Em_<f>" for a single channel).'
)
return float(m.group(1)), m.group(2), math.nan


@validate_call
Expand All @@ -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<n>``)
- ``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
Expand All @@ -49,19 +61,38 @@ 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_<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:
``ndr:format:smartspim:listChannels:UnnumberedChannels``): nothing then
says which ``All_Channels`` ``_ch<k>`` slices are whose, and a guess
could swap two channels unnoticed.
"""
if not rootDir:
raise ValueError("rootDir must be a non-empty string.")
root = Path(rootDir)
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<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]] = []
meta_path = root / "metadata.json"
if meta_path.is_file():
try:
Expand All @@ -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:
Expand All @@ -91,6 +123,11 @@ 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,
Expand Down
19 changes: 16 additions & 3 deletions src/ndr/format/smartspim/ndr_matlab_python_bridge.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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_<n>_Em_<f>_Ch<n>". Straight port
using stdlib json + re.
2026-11-10: synchronized with NDR-matlab 147073c: a channel folder named
Ex_<laser>_Em_<filter> (no _Ch<n>; 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
Expand All @@ -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_<laser>_Em_<filter> (no _Ch<n>) 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<n>
raise ValueError (MATLAB ndr:format:smartspim:listChannels:
UnnumberedChannels) rather than guess which _ch<k> slices are whose.

- name: listTiles
matlab_path: "+ndr/+format/+smartspim/listTiles.m"
Expand Down Expand Up @@ -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
Expand All @@ -146,6 +156,9 @@ functions:
identifiers map to NotADirectoryError / FileNotFoundError (missing
folder, slices or channel) / ValueError (duplicate ch<k>, bad
header).
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.

- name: readAllChannelsVolume
matlab_path: "+ndr/+format/+smartspim/readAllChannelsVolume.m"
Expand Down
20 changes: 14 additions & 6 deletions src/ndr/format/smartspim/readAllChannelsInfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@
``All_Channels`` is a flat folder of 2-D TIFFs, one per (z, channel),
named ``<Y origin>_<X origin>_<z*10>_ch<k>.tiff`` (e.g.
``675050_455000_000110_ch1.tiff``) or, by other versions of the
pipeline, ``<z*10>_ch<k>.tiff`` (e.g. ``000110_ch1.tiff``), plus an
``ImageList.txt`` for
Imaris. Every slice spans the whole stitched canvas (height = Y,
pipeline, ``<z*10>_ch<k>.tiff`` (e.g. ``000110_ch1.tiff``) or
``Z<z*10>_Ch<k>.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<k>`` index follows the
filter-channel number, NOT the acquisition order. It is taken from the
``<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, ...).
(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.
"""

from __future__ import annotations
Expand All @@ -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"}

Expand Down Expand Up @@ -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<n>" (listChannels refuses
# several): its slices are the only _ch<k> 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<k> index in {rootDir}.")

Expand Down
45 changes: 45 additions & 0 deletions tests/test_smartspim_all_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

from ndr.format.smartspim import ( # noqa: E402
hasAllChannels,
isSmartSPIM,
listChannels,
readAllChannelsInfo,
readAllChannelsVolume,
)
Expand Down Expand Up @@ -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_<laser>_Em_<filter> (no _Ch<n>) and its stitched slices
# Z<z*10>_Ch<k>.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<k> 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)
Expand Down
Loading