From 0e9cdfa48ec53500f2a5eb60c144c604116450ec Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:57:59 +0000 Subject: [PATCH 1/2] Brightness of a time series (time_series, plan N72): moved from the OpticalFlow3D Profiler frame_means, brightness_trend, equalise_brightness and match_histograms, time first, against a reference time point the caller chooses (contract section 3.7). Additive: no existing output, API, column or schema_version changes; NumPy only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AERqtoqUxiixuPVPV --- AGENTS.md | 3 + CHANGELOG.md | 7 + README.md | 3 + docs/contract.md | 28 +++ docs/plan.md | 7 + pyproject.toml | 1 + src/morphobricks_normalization/__init__.py | 12 ++ src/morphobricks_normalization/time_series.py | 182 ++++++++++++++++++ tests/test_time_series.py | 85 ++++++++ 9 files changed, 328 insertions(+) create mode 100644 src/morphobricks_normalization/time_series.py create mode 100644 tests/test_time_series.py diff --git a/AGENTS.md b/AGENTS.md index 5a29916..f2af28e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,6 +74,9 @@ src/morphobricks_normalization/ cross-product completion, collinearity and conditioning checks), unmixing, region_white and region_vectors (RegionEstimate, N70) (NumPy only; the `custom_od` presets) + time_series.py brightness of a time series (time first): frame_means, brightness_trend, + equalise_brightness, match_histograms against a reference time point + (contract §3.7, N72; moved from the OpticalFlow3D Profiler) scalar_inputs.py input checks of the presets: RGB with declared axes, single YX planes fitting.py fit, by channel ID parameters.py Parameters (apply, select, to_columns, from_columns with diff --git a/CHANGELOG.md b/CHANGELOG.md index dd97845..89f06f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ The decisions are in [docs/plan.md](docs/plan.md) §12. ## Unreleased +- **Brightness of a time series** (plan N72, contract §3.7): new module `time_series` with + `frame_means`, `brightness_trend`, `equalise_brightness`, `match_histograms` and + `TimeSeriesError`, moved from the OpticalFlow3D Profiler (`brightness.py`) at the owner's + request. Time is the first axis; corrections are against a reference time point the caller + chooses and return new float64 arrays. Additive: no existing output, API, message, column or + `schema_version` changes; the package still imports with NumPy only. + - Tests: the vendored Spec test material (`tests/spec_fixtures`) is re-pinned from `cc9820f` to MorphoBricks-Spec main `1167108`, regenerated with the Spec's `tools/vendor.py`. New fixtures i136–i141, t14–t15, v39–v40; i111 is now the valid fixture v38 (`parent_labels`, owner diff --git a/README.md b/README.md index a30d02d..c99ac9a 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,9 @@ out of scope for now. | Fluorescence | min-max, percentile range (default 1–99.8), z-score, robust z-score, each channel separately | | RGB | StarDist's percentile normalization (1–99.8), the three colour channels together | +Time series (opt-in): the brightness trend of a time series, and its correction by mean +equalisation or histogram matching against a reference time point (contract §3.7). + | Scope | Parameters from | |---|---| | Biological repeat | One biological repeat across all conditions, technical repeats merged | diff --git a/docs/contract.md b/docs/contract.md index 052e0ac..9630f8c 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -25,6 +25,7 @@ with modality profiles, purpose rules, colour statistics and references is withd | 1.5 and 6. Channels by canonical channel ID (`plane_histograms.csv` schema version 5); per-channel columns of 7.1 and 8.1 by ID | Stage 3 S3.2 ([ADR 0003](https://github.com/CellMigrationLab/MorphoBricks-Spec/blob/main/docs/adr/0003-plane-histograms-v5.md); v0.5.0) | | 3.5 Regions (`check_region`, `RegionEstimate`) and the resolver-version refusal | [ADR 0005](https://github.com/CellMigrationLab/MorphoBricks-Spec/blob/main/docs/adr/0005-binary-masks.md) step 1 (plan N70; v0.7.0) | | 3.6 Stable optical-density helpers (`check_white`, `optical_density`, `rgb_yxc`) | Documented as stable API for preprocessing's H&E tissue mask (P2; no code change; v0.7.1) | +| 3.7 Brightness of a time series (`time_series`) | Moved from the OpticalFlow3D Profiler (plan N72; unreleased) | | 9. Validation | With the milestone of each check | Notation: `x` is a pixel value in source units; `n` a pixel count; channels are numbered @@ -873,6 +874,33 @@ float]`** returns a **pair** `(od, floored_fraction)`, never the array alone; ca outputs of `rgb_yxc` and `check_white`, and a consumer always passes its inputs through them first (as `stain.py` does). Other inputs are outside this contract. +### 3.7 Brightness of a time series (`time_series.py`, plan N72) + +Functions for methods that assume constant brightness across time (optical flow, for +example), moved from the OpticalFlow3D Profiler. Time is the **first axis** of +every array; the other axes (`ZYX`, `YX`) are pooled. Integer and floating-point pixels are +accepted; a non-finite pixel, an array without a time axis or pixels, or a non-numeric type is +refused with `TimeSeriesError` (a `ValueError`) naming the problem. The input is never +modified. + +```python +means = frame_means(stack) # float64, one mean per time point +trend = brightness_trend(means, reference) # relative change per time point +scaled, factors = equalise_brightness(stack, reference) +matched = match_histograms(stack, reference) +``` + +| Function | Rule | +|---|---| +| `frame_means` | `mean(stack[t])` over every axis but time, in float64. | +| `brightness_trend` | `slope / means[reference]`, the least-squares slope of the means against the time index `0..T-1` (`numpy.polyfit`, degree 1), divided by the reference mean. NaN when the reference mean is not above 0 or `T = 1`. A check: it changes nothing. | +| `equalise_brightness` | `stack[t] * factor[t]` in float64 with `factor[t] = means[reference] / means[t]` (the reference's factor is exactly 1): Fiji Bleach Correction's "Simple Ratio" without a background. Returns the scaled series and the factors. Refuses a time point whose mean is not above 0, naming it. A constant camera offset is scaled too. | +| `match_histograms` | For every `t` but the reference, `p' = interp(F_t(p), F_ref, v_ref)`: `F_t` the empirical cumulative distribution of time point `t` at each of its distinct values, `v_ref` the reference's distinct values and `F_ref` their cumulative distribution, with NumPy's linear interpolation: Fiji Bleach Correction's "Histogram Matching". Float64; the reference time point is returned unchanged. Monotonic, non-linear. | +| `reference` | A whole-number index `0 <= reference < T` (a boolean or a float is refused, never converted). The caller chooses it; the profiler uses the central frame of each optical-flow window. | + +These are opt-in corrections: no function here is called by `fit`, `apply` or any other +method, and no file format or column changes. + ## 4. Scopes, groups and weights ### 4.1 Scopes diff --git a/docs/plan.md b/docs/plan.md index 529021f..0a6c808 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -613,6 +613,13 @@ binary masks", accepted; decisions BM3, BM7, BM8 and BM10, step 1 of its impleme platform and `+0.0` on another writes the same bytes. The computed values keep their sign; only what is written changes, and it reads back as an equal float. Not a format change: `0.0 == -0.0`, so no `schema_version` changes (contract §6.1, §8.2). +66. **N72** (23 November 2026, owner's request) The brightness of a time series moves here from + the OpticalFlow3D Profiler (its `brightness.py`): `time_series.frame_means`, + `brightness_trend`, `equalise_brightness` and `match_histograms`, time first, against a + reference time point the caller chooses (contract §3.7). They are opt-in corrections for + methods that assume constant brightness across time; nothing else in the library calls + them, and no file format, column or existing output changes. The formulas are the + profiler's, unchanged, so its results stay bit-identical. Implementation choices of S3.2 where the Spec leaves the detail open (open questions 1-7 of pull request #90), each taken on the side the Spec states or the safer one, and listed in that diff --git a/pyproject.toml b/pyproject.toml index 8240606..219183b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -128,6 +128,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_normalization.stain" = "pure" "morphobricks_normalization.stain_presets" = "pure" "morphobricks_normalization.optical_density" = "pure" +"morphobricks_normalization.time_series" = "pure" "morphobricks_normalization.scalar_inputs" = "pure" "morphobricks_normalization.regions" = "pure" "morphobricks_normalization.contracts" = "pure" diff --git a/src/morphobricks_normalization/__init__.py b/src/morphobricks_normalization/__init__.py index 87c1d71..27cea2c 100644 --- a/src/morphobricks_normalization/__init__.py +++ b/src/morphobricks_normalization/__init__.py @@ -67,6 +67,13 @@ iter_image_summaries, summary_columns, ) +from .time_series import ( + TimeSeriesError, + brightness_trend, + equalise_brightness, + frame_means, + match_histograms, +) __all__ = [ "OUTPUT_FILENAME", @@ -93,10 +100,12 @@ "PooledHistogram", "PooledStatistics", "RangeCheck", + "TimeSeriesError", "UnsupportedDtypeError", "WeightedHistogram", "__version__", "apply_rgb", + "brightness_trend", "check_channel_id", "check_channel_ids", "check_measurements", @@ -104,7 +113,9 @@ "compute_block_histogram", "compute_plane_histogram", "default_bin_count", + "equalise_brightness", "fit", + "frame_means", "group_key", "group_name", "group_records", @@ -113,6 +124,7 @@ "iter_image_summaries", "intensity_checks", "make_plane_id", + "match_histograms", "min_max", "percentile_range", "pooled_statistics", diff --git a/src/morphobricks_normalization/time_series.py b/src/morphobricks_normalization/time_series.py new file mode 100644 index 0000000..3b16608 --- /dev/null +++ b/src/morphobricks_normalization/time_series.py @@ -0,0 +1,182 @@ +"""Brightness of a time series: its trend, and two opt-in corrections (contract §3.7). + +Methods that assume constant brightness across time (optical flow, for example) read a +global brightness change (illumination warm-up, focus settling, bleaching, expression +changes) partly as motion. The functions here measure that change and, only when the caller +asks, correct it against one **reference** time point. Time is the first axis of every array; +the other axes (``ZYX`` for a 3-D stack, ``YX`` for a plane) are pooled. + +- :func:`frame_means`: the mean of every time point, in float64. +- :func:`brightness_trend`: the least-squares slope of those means against the time index, + relative to the reference mean (``0.05`` is a brightening by 5 % of the reference + brightness per time point). It is a check: it changes nothing. +- :func:`equalise_brightness`: every time point multiplied so that its mean equals the + reference's mean (Fiji Bleach Correction's "Simple Ratio" without a background). It is + linear, so relative intensities within a time point are kept; a constant camera offset is + scaled too, so the correction is approximate when the offset is a large part of the mean. +- :func:`match_histograms`: every time point's intensity distribution mapped onto the + reference's (Fiji Bleach Correction's "Histogram Matching"): ``p' = F_ref^-1(F_t(p))`` with + linear interpolation between the reference's distinct values. It is monotonic but + non-linear: it changes relative intensities, which the Fiji author recommends for + segmentation rather than for intensity measurements. + +The input is never modified; the corrections return new float64 arrays and the reference +time point is returned unchanged (as float64). Non-finite pixels are refused: a mean or a +distribution with them has no defined value. Moved from the OpticalFlow3D Profiler +(``brightness.py``), whose optical-flow input used the central frame of each time window as +the reference (plan N72). +""" + +from __future__ import annotations + +import numpy as np + + +class TimeSeriesError(ValueError): + """A time series that cannot be measured or corrected (see the message).""" + + +def _checked(stack: np.ndarray, reference: int | None = None) -> np.ndarray: + """Return ``stack`` as an array after the checks every function shares.""" + stack = np.asarray(stack) + if stack.ndim < 2 or stack.shape[0] < 1 or stack[0].size == 0: + raise TimeSeriesError( + f"A time series needs time as the first axis and at least one pixel per time point " + f"(got shape {stack.shape}); pass an array of shape (T, ...), for example TZYX or TYX." + ) + if not (np.issubdtype(stack.dtype, np.integer) or np.issubdtype(stack.dtype, np.floating)): + raise TimeSeriesError( + f"Pixel type {stack.dtype} is not an integer or a floating-point type; convert the " + "time series to one before measuring its brightness." + ) + if np.issubdtype(stack.dtype, np.floating) and not np.isfinite(stack).all(): + raise TimeSeriesError( + "The time series holds non-finite pixels (NaN or infinity); their mean and " + "distribution are undefined. Remove them before measuring or correcting brightness." + ) + if reference is not None and not ( + isinstance(reference, int | np.integer) + and not isinstance(reference, bool) + and 0 <= reference < stack.shape[0] + ): + raise TimeSeriesError( + f"The reference time point {reference!r} is not an index of the {stack.shape[0]} " + f"time points; choose a whole number from 0 to {stack.shape[0] - 1}." + ) + return stack + + +def frame_means(stack: np.ndarray) -> np.ndarray: + """Return the mean intensity of every time point of ``stack`` (time first), in float64. + + Raises + ------ + TimeSeriesError + For an array without a time axis or pixels, a non-numeric type or non-finite pixels. + """ + stack = _checked(stack) + return stack.reshape(stack.shape[0], -1).mean(axis=1, dtype=np.float64) + + +def brightness_trend(means: np.ndarray, reference: int) -> float: + """Return the relative brightness change per time point of a series of means. + + Parameters + ---------- + means + :func:`frame_means` of the series, in time order. + reference + The time point whose mean the slope is expressed against. + + Returns + ------- + float + Least-squares slope of the means against the time index, divided by the reference + mean. NaN when the reference mean is not above 0 or there is a single time point + (no slope). + + Raises + ------ + TimeSeriesError + For means that are not a 1-D finite series or an invalid reference. + """ + means = np.asarray(means, dtype=np.float64) + if means.ndim != 1 or not np.isfinite(means).all(): + raise TimeSeriesError("The means must be one finite value per time point, in time order.") + _checked(means[:, None], reference) + if len(means) < 2 or not means[reference] > 0: + return float("nan") + slope = np.polyfit(np.arange(len(means), dtype=np.float64), means, 1)[0] + return float(slope / means[reference]) + + +def equalise_brightness(stack: np.ndarray, reference: int) -> tuple[np.ndarray, np.ndarray]: + """Scale every time point so that its mean equals the reference time point's mean. + + Parameters + ---------- + stack + Time series, time first (not modified). + reference + The time point every other is matched to. + + Returns + ------- + tuple of numpy.ndarray + The scaled series (float64) and the factor of each time point (``mean_ref / + mean_t``; 1 for the reference). + + Raises + ------ + TimeSeriesError + For an invalid series or reference, or a time point whose mean is not above 0 (it + cannot be scaled to a positive mean). + """ + means = frame_means(stack) + _checked(np.asarray(stack), reference) + low = np.flatnonzero(~(means > 0)) + if low.size: + raise TimeSeriesError( + f"Time point(s) {', '.join(map(str, low))} have a mean intensity that is not above 0, " + "so they cannot be scaled to the reference's mean; use histogram matching or no " + "correction." + ) + factors = means[reference] / means + factors[reference] = 1.0 + shape = (len(factors),) + (1,) * (np.ndim(stack) - 1) + return np.asarray(stack, dtype=np.float64) * factors.reshape(shape), factors + + +def match_histograms(stack: np.ndarray, reference: int) -> np.ndarray: + """Map every time point's intensity distribution onto the reference time point's. + + Parameters + ---------- + stack + Time series, time first (not modified). + reference + The time point whose distribution every other takes. + + Returns + ------- + numpy.ndarray + The matched series (float64); the reference time point is unchanged. + + Raises + ------ + TimeSeriesError + For an invalid series or reference. + """ + stack = _checked(stack, reference) + ref_values, ref_counts = np.unique(stack[reference], return_counts=True) + ref_cdf = np.cumsum(ref_counts, dtype=np.float64) / stack[reference].size + out = np.empty(stack.shape, dtype=np.float64) + for t in range(stack.shape[0]): + if t == reference: + out[t] = stack[t] + continue + _, inverse, counts = np.unique(stack[t], return_inverse=True, return_counts=True) + cdf = np.cumsum(counts, dtype=np.float64) / stack[t].size + mapped = np.interp(cdf, ref_cdf, ref_values.astype(np.float64)) + out[t] = mapped[inverse].reshape(stack[t].shape) + return out diff --git a/tests/test_time_series.py b/tests/test_time_series.py new file mode 100644 index 0000000..2f3015a --- /dev/null +++ b/tests/test_time_series.py @@ -0,0 +1,85 @@ +"""Brightness of a time series (contract §3.7): each function against a direct implementation.""" + +import numpy as np +import pytest + +from morphobricks_normalization import ( + TimeSeriesError, + brightness_trend, + equalise_brightness, + frame_means, + match_histograms, +) + +rng = np.random.default_rng(7) +# A 3-D time series (TZYX) that brightens by 5 % per time point, and a 2-D one (TYX). +BASE = rng.integers(100, 400, (3, 12, 12)).astype(np.uint16) +STACK = np.stack([np.round(BASE * (1 + 0.05 * t)).astype(np.uint16) for t in range(7)]) +PLANES = rng.normal(500, 40, (5, 16, 16)) + + +def test_frame_means_pool_every_axis_but_time_in_float64(): + means = frame_means(STACK) + assert means.dtype == np.float64 and means.shape == (7,) + assert means == pytest.approx([STACK[t].astype(np.float64).mean() for t in range(7)]) + assert frame_means(PLANES) == pytest.approx(PLANES.mean(axis=(1, 2))) + + +def test_brightness_trend_is_the_slope_relative_to_the_reference(): + means = frame_means(STACK) + slope = np.polyfit(np.arange(7.0), means, 1)[0] + assert brightness_trend(means, 3) == slope / means[3] + assert brightness_trend(means, 3) == pytest.approx(0.05 / 1.15, rel=0.02) + assert brightness_trend(np.full(4, 10.0), 0) == pytest.approx(0.0, abs=1e-12) + assert np.isnan(brightness_trend(np.array([0.0, 1.0, 2.0]), 0)) # reference mean 0 + assert np.isnan(brightness_trend(np.array([5.0]), 0)) # no slope from one time point + + +def test_equalise_brightness_matches_every_mean_to_the_reference(): + before = STACK.copy() + scaled, factors = equalise_brightness(STACK, 3) + assert np.array_equal(STACK, before) # never modified + means = frame_means(STACK) + assert np.array_equal(factors, np.where(np.arange(7) == 3, 1.0, means[3] / means)) + assert scaled.dtype == np.float64 + assert np.array_equal(scaled, STACK.astype(np.float64) * factors[:, None, None, None]) + assert frame_means(scaled) == pytest.approx(np.full(7, means[3])) + assert np.array_equal(scaled[3], STACK[3].astype(np.float64)) # the reference unchanged + with pytest.raises(TimeSeriesError, match="not above 0"): + equalise_brightness(np.zeros((3, 4, 4)), 1) + + +def test_match_histograms_gives_every_time_point_the_reference_distribution(): + before = STACK.copy() + matched = match_histograms(STACK, 3) + assert np.array_equal(STACK, before) + assert matched.dtype == np.float64 + assert np.array_equal(matched[3], STACK[3].astype(np.float64)) + # Direct implementation: p' = F_ref^-1(F_t(p)), linear between the reference's values. + ref = np.sort(STACK[3].ravel()).astype(np.float64) + values, counts = np.unique(STACK[3], return_counts=True) + ref_cdf = np.cumsum(counts) / STACK[3].size + for t in (0, 6): + flat = STACK[t].ravel() + own_cdf = np.array([np.mean(flat <= v) for v in flat]) + expected = np.interp(own_cdf, ref_cdf, values.astype(np.float64)) + assert matched[t].ravel() == pytest.approx(expected) + # Monotonic: a brighter pixel never becomes darker. + order = np.argsort(flat, kind="stable") + assert np.all(np.diff(matched[t].ravel()[order]) >= 0) + assert frame_means(matched)[0] == pytest.approx(ref.mean(), rel=0.02) + + +def test_refusals_name_the_problem(): + with pytest.raises(TimeSeriesError, match="first axis"): + frame_means(np.arange(5.0)) + with pytest.raises(TimeSeriesError, match="non-finite"): + frame_means(np.array([[1.0, np.nan]])) + with pytest.raises(TimeSeriesError, match="not an integer or a floating-point"): + frame_means(np.ones((2, 3), dtype=bool)) + for bad in (7, -1, 1.0, True): + with pytest.raises(TimeSeriesError, match="reference time point"): + match_histograms(STACK, bad) + with pytest.raises(TimeSeriesError, match="one finite value per time point"): + brightness_trend(np.ones((2, 2)), 0) + assert isinstance(TimeSeriesError("x"), ValueError) From 8814dc165e81f9b1410e230dbaf8d87061985da2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:02:32 +0000 Subject: [PATCH 2/2] Contract 3.7: format the example as Ruff does Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp9AERqtoqUxiixuPVPV --- docs/contract.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/contract.md b/docs/contract.md index 9630f8c..013ab13 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -884,8 +884,8 @@ refused with `TimeSeriesError` (a `ValueError`) naming the problem. The input is modified. ```python -means = frame_means(stack) # float64, one mean per time point -trend = brightness_trend(means, reference) # relative change per time point +means = frame_means(stack) # float64, one mean per time point +trend = brightness_trend(means, reference) # relative change per time point scaled, factors = equalise_brightness(stack, reference) matched = match_histograms(stack, reference) ```