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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ For development setup and documentation builds, see [CONTRIBUTING.md](CONTRIBUTI

## Register raster recordings

`register_multiroi` registers every trial and DMD path of a MATLAB-written trial table, as GIAnT-MATLAB's `MultiRoiRegistration` does, and writes the same files: `E<epoch>T<trial>DMD<path>_REGISTERED_DOWNSAMPLED-80Hz.tif` (or `.h5`) and `..._ALIGNMENTDATA.h5` under `<savedr>/motion_correction`. It then rewrites the table's `motion_correction` group in MATLAB's layout, so GIAnT-MATLAB SILo can use the results unchanged.
`register_multiroi` registers every trial and DMD path of a MATLAB-written trial table, as GIAnT-MATLAB's `MultiRoiRegistration` does, and writes the same files: `E<epoch>T<trial>DMD<path>_REGISTERED_DOWNSAMPLED-80Hz.h5` (or `.tif`) and `..._ALIGNMENTDATA.h5` under `<savedr>/motion_correction`. It then rewrites the table's `motion_correction` group in MATLAB's layout, so GIAnT-MATLAB SILo can use the results unchanged.

```python
from giant_python import ExecutionOptions, register_multiroi
Expand All @@ -43,7 +43,7 @@ or `giant register path/to/trial_table.h5 --device cuda`. On the CPU, trials run

- By default frames are registered sequentially, in MATLAB's order, so results match GIAnT-MATLAB within single-precision rounding. `schedule="grow"` instead matches frames in batches, growing outward from seed frames spread over the trial (see `giant_python.registration.growth`); it is experimental and gives slightly different motion.
- `compensate_online=True` (`--compensate-online`) undoes the online motion correction line by line, as MATLAB's `compensateOnline` does. The alignment file then records each frame's reference offset (`slap2/onlineCompensation`).
- `varFacDS` is stored deflate-compressed (`var_factor_deflate=1`, about 16x smaller, identical values; MATLAB's `h5read` decompresses transparently). Set it to 0 for MATLAB's uncompressed layout. Registered movies stay TIFF by default; `save_tif=False` (`--h5`) writes a deflated HDF5 movie (`movie_deflate=1`, about 7x smaller), which MATLAB SILo also reads.
- `varFacDS` is stored deflate-compressed (`var_factor_deflate=1`, about 16x smaller, identical values; MATLAB's `h5read` decompresses transparently). Set it to 0 for MATLAB's uncompressed layout. Registered movies are deflated HDF5 by default (`movie_deflate=1`, about 7x smaller than TIFF), which MATLAB SILo also reads. `save_tif=True` (`--tif`) writes MATLAB's default BigTIFF instead.
- Not yet ported: `refStackTemplate`, `isReVolt` and integration ROIs. Setting any of them raises `NotImplementedError`.
- Only single-plane recordings with one or two channels are supported.

Expand Down
5 changes: 3 additions & 2 deletions docs/source/file_formats.rst
Original file line number Diff line number Diff line change
Expand Up @@ -405,8 +405,9 @@ Trial table fields
* - ``motion_correction/fn_reg_ds``
- nPaths x total trials
- string
- Registered and downsampled TIFF filename (empty where Python
registration raised or the cell has no recording).
- Registered and downsampled movie filename, ``.tif`` or ``.h5``
(empty where Python registration raised or the cell has no
recording).
* - ``motion_correction/fn_adata``
- nPaths x total trials
- string
Expand Down
18 changes: 14 additions & 4 deletions src/giant_python/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,21 @@ def _add_register_options(parser: argparse.ArgumentParser) -> None:
action="store_true",
help="Re-register trials whose outputs exist.",
)
parser.add_argument(
"--h5",
movie = parser.add_mutually_exclusive_group()
movie.add_argument(
"--tif",
dest="save_tif",
action="store_true",
help="Save registered movies as HDF5 instead of TIFF.",
help="Save registered movies as TIFF, as GIAnT-MATLAB does, instead "
"of deflated HDF5 (the default).",
)
movie.add_argument(
"--h5",
dest="save_tif",
action="store_false",
help="Save registered movies as deflated HDF5 (the default).",
)
parser.set_defaults(save_tif=defaults.save_tif)
parser.add_argument(
"--compensate-online",
action="store_true",
Expand Down Expand Up @@ -267,7 +277,7 @@ def _cmd_register(args: argparse.Namespace) -> int:
maxshift=args.maxshift,
clip_shift=args.clip_shift,
overwrite_existing=args.overwrite,
save_tif=not args.h5,
save_tif=args.save_tif,
compensate_online=args.compensate_online,
schedule=args.schedule,
polish=args.polish,
Expand Down
14 changes: 7 additions & 7 deletions src/giant_python/extraction/raster/trial.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""Load and localize one registered SLAP2 trial as SiLo does.

Port of GIAnT-MATLAB's ``loadAndProcessTrialAsync.m``: the registered 80 Hz
movie (``*_REGISTERED_DOWNSAMPLED-80Hz.tif``, channels interleaved by frame)
and its ``*_ALIGNMENTDATA.h5`` give the activity channel, NaN at the frames
discarded for motion (from ``recNegErr``) and at the first
``discardInitial_s``, the variance factor ``slap2.varFacDS`` and the trial's
mean image; :func:`localize_trial` then runs
movie (``*_REGISTERED_DOWNSAMPLED-80Hz.h5`` or ``.tif``, channels
interleaved by frame) and its ``*_ALIGNMENTDATA.h5`` give the activity
channel, NaN at the frames discarded for motion (from ``recNegErr``) and at
the first ``discardInitial_s``, the variance factor ``slap2.varFacDS`` and
the trial's mean image; :func:`localize_trial` then runs
:func:`~giant_python.extraction.raster.localization.localize_sources`, with
the F0 network's ``<trial>_BASELINE-80Hz.h5`` when a baseline folder is given
(GIAnT-MATLAB branch ``localization-network-baseline``).
the F0 network's ``<trial>_BASELINE-80Hz.h5`` when a baseline folder is
given (GIAnT-MATLAB branch ``localization-network-baseline``).

Arrays are ``(frames, rows, cols)`` in MATLAB's row and column orientation
(the TIFF pages are transposed, as MATLAB's reader returns them).
Expand Down
10 changes: 6 additions & 4 deletions src/giant_python/models/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ class MultiRoiRegistrationParams:
are kept if they were made with the same settings (all fields but
this one), and registered again if not.
save_tif : bool
Save the registered movie as TIFF (else HDF5 ``/data``).
Save the registered movie as TIFF, as GIAnT-MATLAB does by default.
Otherwise (the default) it is a deflated HDF5 ``/data``, about 7x
smaller, which GIAnT-MATLAB SILo also reads.
ref_stack_template, is_revolt, include_integration_rois : bool
MATLAB options not yet ported; must be False.
compensate_online : bool
Expand Down Expand Up @@ -199,16 +201,16 @@ class MultiRoiRegistrationParams:
it uncompressed, as MATLAB does. MATLAB's ``h5read`` decompresses
transparently.
movie_deflate : int
Deflate level (0-9) of HDF5 movies (``save_tif=False``); MATLAB
writes 4.
Deflate level (0-9) of HDF5 movies (``save_tif=False``, the
default); MATLAB writes 4.
"""

align_hz: float = 80.0
maxshift: int = 40
clip_shift: int = 5
alpha: float = 0.005
overwrite_existing: bool = False
save_tif: bool = True
save_tif: bool = False
ref_stack_template: bool = False
is_revolt: bool = False
include_integration_rois: bool = False
Expand Down
31 changes: 31 additions & 0 deletions tests/raster/test_raster_trial.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,37 @@ def test_load_registered_trial(tmp_path, layout):
np.testing.assert_allclose(tr.var_factor, vf.transpose(0, 2, 1))


@pytest.mark.parametrize("save_tif", [False, True])
def test_load_registration_movie(tmp_path, save_tif):
"""Movies written by GIAnT-Python's registration, HDF5 (the default) or
TIFF, load as the same frames in MATLAB's rows and columns."""
if save_tif:
pytest.importorskip("tifffile")
from giant_python.registration.outputs import MovieWriter

n, rows, cols = 50, 6, 9
rng = np.random.default_rng(1)
act = rng.poisson(5, (n, rows, cols)).astype(np.float32)
act[3, 2, 4] = np.nan
other = np.full((n, rows, cols), 100, np.float32)
stem = "E1T1DMD1"
name = f"{stem}_REGISTERED_DOWNSAMPLED-80Hz" + (
".tif" if save_tif else ".h5"
)
movie = MovieWriter(tmp_path / name, (rows, cols), 2 * n, save_tif)
for a, o in zip(act, other):
movie.write(a)
movie.write(o)
movie.close()
movie.tmp.rename(movie.path)
with h5py.File(tmp_path / f"{stem}_ALIGNMENTDATA.h5", "w") as f:
f["alignHz"] = np.array([[80.0]])
f["recNegErr"] = np.full((1, n), -0.5)
tr = load_registered_trial(tmp_path, name, 2)
np.testing.assert_array_equal(tr.movie, act)
np.testing.assert_allclose(tr.mean_im[..., 1], 100)


def test_localize_trial_retries_numerical_failures(monkeypatch):
"""Any failure of the localization itself is retried with the outer
rows and columns NaN (MATLAB's catch); invalid inputs are not."""
Expand Down
34 changes: 34 additions & 0 deletions tests/registration/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,37 @@ def test_register_reports_failed_trials(
assert ("registrationFailed" in out) == flagged
assert ("trial 2 (path 1)" in err) == (code == 1)
assert ("No recording (skipped): trial 2 (path 1)" in out) == (n_rec == 1)


@pytest.mark.parametrize(
"flags,save_tif", [([], False), (["--h5"], False), (["--tif"], True)]
)
def test_register_movie_format(monkeypatch, flags, save_tif):
"""Registered movies are HDF5 unless ``--tif`` asks for TIFF."""
from types import SimpleNamespace

from giant_python.io import trial_table
from giant_python.pipeline import register

seen = {}

def fake(table, params, **kwargs):
seen["params"] = params
return {
"registration_failed": np.array([[False]]),
"fn_reg_ds": np.array([["a"]], dtype=object),
"fn_adata": np.array([["a"]], dtype=object),
"align_params": {},
}

monkeypatch.setattr(register, "register_multiroi", fake)
table = SimpleNamespace(filename=np.array([["x"]], dtype=object))
monkeypatch.setattr(trial_table, "read_trial_table", lambda path: table)
assert cli.main(["register", "trial_table.h5", *flags]) == 0
assert seen["params"].save_tif is save_tif


def test_register_movie_formats_exclusive():
"""``--tif`` and ``--h5`` cannot be combined."""
with pytest.raises(SystemExit):
cli.main(["register", "trial_table.h5", "--tif", "--h5"])