From 469f4ae0613132b3a6927dfd69c1cc11235e348c Mon Sep 17 00:00:00 2001 From: KasparP Date: Sun, 22 Nov 2026 08:20:53 -0800 Subject: [PATCH 1/2] Write registered movies as deflated HDF5 by default save_tif now defaults to False, so register_multiroi writes E*_REGISTERED_DOWNSAMPLED-80Hz.h5 (deflate 1, about 7x smaller than TIFF) unless asked for TIFF. GIAnT-MATLAB SILo reads both. giant register gains --tif for MATLAB's BigTIFF; --h5 is kept and now matches the default. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- docs/source/file_formats.rst | 4 ++-- src/giant_python/cli.py | 18 ++++++++++++++---- src/giant_python/models/params.py | 10 ++++++---- tests/registration/test_cli.py | 29 +++++++++++++++++++++++++++++ 5 files changed, 53 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 3c07284..812eae0 100644 --- a/README.md +++ b/README.md @@ -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: `ETDMD_REGISTERED_DOWNSAMPLED-80Hz.tif` (or `.h5`) and `..._ALIGNMENTDATA.h5` under `/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: `ETDMD_REGISTERED_DOWNSAMPLED-80Hz.h5` (or `.tif`) and `..._ALIGNMENTDATA.h5` under `/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 @@ -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. diff --git a/docs/source/file_formats.rst b/docs/source/file_formats.rst index 90fdec9..57b5903 100644 --- a/docs/source/file_formats.rst +++ b/docs/source/file_formats.rst @@ -405,8 +405,8 @@ Trial table fields * - ``motion_correction/fn_reg_ds`` - nPaths x total trials - string - - Registered and downsampled TIFF filename (empty where Python - registration raised). + - Registered and downsampled movie filename, ``.tif`` or ``.h5`` + (empty where Python registration raised). * - ``motion_correction/fn_adata`` - nPaths x total trials - string diff --git a/src/giant_python/cli.py b/src/giant_python/cli.py index 81589dd..01d1ffe 100644 --- a/src/giant_python/cli.py +++ b/src/giant_python/cli.py @@ -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", @@ -266,7 +276,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, diff --git a/src/giant_python/models/params.py b/src/giant_python/models/params.py index e16066b..5566eed 100644 --- a/src/giant_python/models/params.py +++ b/src/giant_python/models/params.py @@ -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 @@ -199,8 +201,8 @@ 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 @@ -208,7 +210,7 @@ class MultiRoiRegistrationParams: 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 diff --git a/tests/registration/test_cli.py b/tests/registration/test_cli.py index bf42768..675bff3 100644 --- a/tests/registration/test_cli.py +++ b/tests/registration/test_cli.py @@ -34,3 +34,32 @@ def test_register_reports_failed_trials( assert f"{registered} of 2 trials registered" in out assert ("registrationFailed" in out) == (failed[0][0] or failed[0][1]) assert ("trial 2 (path 1)" in err) == (code == 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 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) + 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"]) From 734f54e56bd172a8add7c4b0eed2ef2d2363552f Mon Sep 17 00:00:00 2001 From: KasparP Date: Tue, 24 Nov 2026 09:08:30 -0800 Subject: [PATCH 2/2] Test that registration's HDF5 and TIFF movies load alike Raster localization reads the registered movie that GIAnT-Python's registration writes, now HDF5 by default. The new test writes the same frames with MovieWriter in both formats and checks that load_registered_trial returns them in MATLAB's rows and columns. Co-Authored-By: Claude Opus 5.5 --- src/giant_python/extraction/raster/trial.py | 14 +++++----- tests/raster/test_raster_trial.py | 31 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/giant_python/extraction/raster/trial.py b/src/giant_python/extraction/raster/trial.py index f9c1fad..9c25431 100644 --- a/src/giant_python/extraction/raster/trial.py +++ b/src/giant_python/extraction/raster/trial.py @@ -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 ``_BASELINE-80Hz.h5`` when a baseline folder is given -(GIAnT-MATLAB branch ``localization-network-baseline``). +the F0 network's ``_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). diff --git a/tests/raster/test_raster_trial.py b/tests/raster/test_raster_trial.py index c209a58..c7561e8 100644 --- a/tests/raster/test_raster_trial.py +++ b/tests/raster/test_raster_trial.py @@ -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."""