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
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
28 changes: 28 additions & 0 deletions docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions docs/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
12 changes: 12 additions & 0 deletions src/morphobricks_normalization/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -93,18 +100,22 @@
"PooledHistogram",
"PooledStatistics",
"RangeCheck",
"TimeSeriesError",
"UnsupportedDtypeError",
"WeightedHistogram",
"__version__",
"apply_rgb",
"brightness_trend",
"check_channel_id",
"check_channel_ids",
"check_measurements",
"check_settings",
"compute_block_histogram",
"compute_plane_histogram",
"default_bin_count",
"equalise_brightness",
"fit",
"frame_means",
"group_key",
"group_name",
"group_records",
Expand All @@ -113,6 +124,7 @@
"iter_image_summaries",
"intensity_checks",
"make_plane_id",
"match_histograms",
"min_max",
"percentile_range",
"pooled_statistics",
Expand Down
182 changes: 182 additions & 0 deletions src/morphobricks_normalization/time_series.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading