diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e95544..e9af2ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,19 @@ Release notes and migration notes of `morphobricks-normalization`. Numbers are p issues of [CellMigrationLab/morphobricks-normalization](https://github.com/CellMigrationLab/morphobricks-normalization). The decisions are in [docs/plan.md](docs/plan.md) §12. -## Unreleased +## v0.8.0 (2026-11-23) + +Minor release (#111, #113, #114, #115): a new module `time_series` for the brightness of a time +series (contract §3.7), moved from the OpticalFlow3D Profiler. Additive: every existing output, +API, message, column and `schema_version` is unchanged, and the package still imports with NumPy +only. Consumers on v0.7.1 can re-pin without code changes; the recorded `library_version` +(settings, range-check and intensity-check provenance) reads `0.8.0`. + +- `time_series.equalise_brightness` refuses a positive mean ratio that rounds to 0 in float64 + (`[[1e-200], [1e200]]` with reference 0 returned a black second time point), and checks + finiteness one time point at a time instead of over the whole result (the boolean array of a + 7 × 11 × 1840 × 1840 window was about 261 MB). Finite results are unchanged, bit for bit + (OpticalFlow3D Profiler re-validation R5). - `time_series.equalise_brightness` refuses a factor or scaled value that overflows float64 (for example a time point whose mean is many orders of magnitude below the reference's) diff --git a/README.md b/README.md index c99ac9a..dcb9ce0 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ equalisation or histogram matching against a reference time point (contract §3. ## Status -Pre-alpha; the latest release is v0.7.1. The library offers: +Pre-alpha; the latest release is v0.8.0. The library offers: - supported pixel types, bin counts and per-plane histograms (`dtypes`, `histogram`), with a robust range and a range check; - plane records, `plane_histograms.csv` reading and writing and pooling of group statistics (`records`, `csv_io`, `pooling`): schema version 5 since v0.5.0, with channels named by canonical channel ID (ADR 0003; version 4 tables are refused, see the CHANGELOG migration notes); @@ -48,7 +48,10 @@ Pre-alpha; the latest release is v0.7.1. The library offers: - since v0.7.1, the optical-density helpers `optical_density.optical_density`, `optical_density.check_white` and `scalar_inputs.rgb_yxc` are stable API (contract §3.6), and the per-bin work of integer planes runs in NumPy int64 (same outputs, 1.3–1.5× faster); - every written float writes `-0.0` as `0.0` (#105). + every written float writes `-0.0` as `0.0` (#105); +- since v0.8.0, the brightness of a time series (`time_series`: `frame_means`, + `brightness_trend` and the opt-in corrections `equalise_brightness` and `match_histograms`; + contract §3.7). Release notes and migration notes are in [CHANGELOG.md](CHANGELOG.md). @@ -70,7 +73,7 @@ for key, rows in groups.items(): ## Installation ```bash -pip install "git+https://github.com/CellMigrationLab/morphobricks-normalization.git@v0.7.1" +pip install "git+https://github.com/CellMigrationLab/morphobricks-normalization.git@v0.8.0" ``` For development, from a clone: diff --git a/docs/contract.md b/docs/contract.md index bfda625..ced856d 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -25,7 +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) | +| 3.7 Brightness of a time series (`time_series`) | Moved from the OpticalFlow3D Profiler (plan N72; v0.8.0) | | 9. Validation | With the milestone of each check | Notation: `x` is a pixel value in source units; `n` a pixel count; channels are numbered @@ -894,7 +894,7 @@ matched = match_histograms(stack, reference) |---|---| | `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, and a factor or scaled value that is not finite (float64 overflow), naming them. A constant camera offset is scaled too. | +| `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, a factor float64 cannot hold (infinite, or a positive ratio rounded to 0, which would erase the time point) and a scaled value that is not finite (float64 overflow), naming them; finiteness is checked one time point at a time. 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. | diff --git a/docs/plan.md b/docs/plan.md index 0a6c808..595fb4b 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -2,7 +2,7 @@ > See also: [Preprocessing follow-up](archive/followup_preprocessing.md) (done) · [CellPatcher follow-up](archive/followup_cellpatcher.md) (done) -**Status:** implemented through v0.7.1 (Milestones 0 to 5 done; later changes in [CHANGELOG.md](../CHANGELOG.md)); design brief simplified on 26 October 2026 (decisions N29–N40, §12), with +**Status:** implemented through v0.8.0 (Milestones 0 to 5 done; later changes in [CHANGELOG.md](../CHANGELOG.md)); design brief simplified on 26 October 2026 (decisions N29–N40, §12), with channels moved into columns on 27 October 2026 (N41–N45). The earlier design with six modalities, two purposes, colour and stain methods and reference targets (N4–N28) is withdrawn where §12 says so. A robust histogram range was added on 28 October diff --git a/pyproject.toml b/pyproject.toml index 219183b..a5fc224 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "morphobricks-normalization" -version = "0.7.1" +version = "0.8.0" description = "MorphoBricks normalization brick: per-plane statistics, their file formats, and normalization methods for microscopy images." readme = "README.md" license = "MIT" diff --git a/src/morphobricks_normalization/time_series.py b/src/morphobricks_normalization/time_series.py index 2efa15c..d4397a2 100644 --- a/src/morphobricks_normalization/time_series.py +++ b/src/morphobricks_normalization/time_series.py @@ -130,11 +130,14 @@ def equalise_brightness(stack: np.ndarray, reference: int) -> tuple[np.ndarray, ------ TimeSeriesError For an invalid series or reference, a time point whose mean is not above 0 (it - cannot be scaled to a positive mean), or a factor or scaled value that is not finite - (float64 overflow): never returned as infinite pixels. + cannot be scaled to a positive mean), a factor float64 cannot hold (an infinite + factor, or a positive ratio rounded to 0, which would erase the time point), or a + scaled value that is not finite (float64 overflow): never returned as infinite or + erased pixels. Finiteness is checked one time point at a time, so no array larger + than one time point is allocated besides the result. """ means = frame_means(stack) - _checked(np.asarray(stack), reference) + stack = _checked(np.asarray(stack), reference) low = np.flatnonzero(~(means > 0)) if low.size: raise TimeSeriesError( @@ -142,19 +145,22 @@ def equalise_brightness(stack: np.ndarray, reference: int) -> tuple[np.ndarray, "so they cannot be scaled to the reference's mean; use histogram matching or no " "correction." ) - with np.errstate(over="ignore"): + with np.errstate(over="ignore", under="ignore"): factors = means[reference] / means - factors[reference] = 1.0 - shape = (len(factors),) + (1,) * (np.ndim(stack) - 1) - scaled = np.asarray(stack, dtype=np.float64) * factors.reshape(shape) - bad = np.flatnonzero( - ~np.isfinite(factors) | ~np.isfinite(scaled).reshape(len(factors), -1).all(axis=1) - ) + factors[reference] = 1.0 + bad = np.flatnonzero(~np.isfinite(factors) | ~(factors > 0)) + scaled = np.empty(stack.shape, dtype=np.float64) + if not bad.size: + with np.errstate(over="ignore"): + for t, factor in enumerate(factors): + np.multiply(stack[t], factor, out=scaled[t], dtype=np.float64) + if not np.isfinite(scaled[t]).all(): + bad = np.append(bad, t) if bad.size: raise TimeSeriesError( - f"Scaling time point(s) {', '.join(map(str, bad))} to the reference's mean gives " - "values float64 cannot hold (a mean far below the reference's); use histogram " - "matching or no correction." + f"Scaling time point(s) {', '.join(map(str, bad))} to the reference's mean needs a " + "factor or gives values float64 cannot hold (a mean many orders of magnitude from " + "the reference's); use histogram matching or no correction." ) return scaled, factors diff --git a/tests/test_time_series.py b/tests/test_time_series.py index e1c897f..e5c0ff8 100644 --- a/tests/test_time_series.py +++ b/tests/test_time_series.py @@ -49,6 +49,12 @@ def test_equalise_brightness_matches_every_mean_to_the_reference(): equalise_brightness(np.zeros((3, 4, 4)), 1) with pytest.raises(TimeSeriesError, match="float64 cannot hold"): equalise_brightness(np.array([[5e-324], [1.0]]), 1) # factor overflows to infinity + with pytest.raises(TimeSeriesError, match="float64 cannot hold"): + # 1e-200 / 1e200 rounds to 0: the second time point would be erased (re-validation R5). + equalise_brightness(np.array([[1e-200], [1e200]]), 0) + floats = rng.uniform(1, 1e4, (4, 3, 5)) # float input: the same products as broadcasting + scaled, factors = equalise_brightness(floats, 2) + assert np.array_equal(scaled, floats * factors[:, None, None]) def test_match_histograms_gives_every_time_point_the_reference_distribution():