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
8 changes: 7 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ src/morphobricks_normalization/
bins a value can fall in and whether centres map back (#86)
integer_representatives.py integer bin representatives (nearest float64 midpoint) and
their exact bound for 64-bit values float64 cannot hold (#28)
integer_bins.py whole-number bin starts and limits of integer planes, per-value counts
summed into bins, the bin of a value: NumPy int64 where no step can
overflow, exact Python integers (as in v0.7.0) for wide 64-bit ranges
ranges.py HistogramSettings, RangeCheck, range_check_issues (Milestone 5)
integrity.py invariants every PlaneHistogram and HistogramTail checks when made
(counts, limits, tail moments) and the pixel type of every block
Expand Down Expand Up @@ -88,7 +91,10 @@ tests/ pytest with simulated planes (tests/simulation.py); tests/da
stain_v060_parity.json, the v0.6.0 refusals and output digests of
tests/test_stain_check_options.py (recorded by tests/stain_parity_cases.py),
and region_v061_parity.json, the v0.6.1 region whites and stain vectors of
tests/test_regions.py (recorded by tests/region_parity_cases.py)
tests/test_regions.py (recorded by tests/region_parity_cases.py), and
histogram_v070_parity.json, the v0.7.0 histograms, representatives, bounds
and range checks of tests/test_histogram_parity.py (recorded by
tests/histogram_parity_cases.py)
tools/check.py the release gate: ruff format, pytest and the code standards (design v0.4 §9);
`--rules` runs only the standards (CI); tools/code_rules.py is the shared
copy (SHA-256 pinned in tests/test_code_rules.py), tools/code_rules_baseline.json
Expand Down
41 changes: 41 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,47 @@ 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

Speed only (MorphoBricks preprocessing speed plan, step D6; measured in preprocessing draft PR
#318, `experiments/histogram_numba_study/`): every output is bitwise that of v0.7.0. No new
dependency (NumPy only, no Numba), no API, file format or message change.

- **Per-bin work of integer planes in NumPy int64** (new module `integer_bins`). The bin starts
(a 65,537-item Python list per call before), the sums of per-value counts into bins, the
integer bin limits, the representatives, `max_representative_error` and the bin of each order
statistic of the range check were Python loops over every bin; they are now NumPy int64
arithmetic on the same formulas (the bin of a value is one exact integer division).
- **The exact Python integers are kept where int64 could not be exact**, chosen by explicit
conditions: bin starts when `bin_count * width >= 2**62` (64-bit planes with a wide range);
representatives and the bound from `2**51` on (unchanged `Fraction` bound, #28); bin sums
when a plane's per-value counts total `2**52` or more (v0.7.0's float64 sums are kept there);
and histograms a caller built with NumPy integer limits or a NumPy bin count, so their
results keep v0.7.0's NumPy types (and int64 products never wrap). Float bin positions, tail moments and 32/64-bit pixel binning are unchanged.
- **Identity**: `tests/test_histogram_parity.py` compares every `PlaneHistogram` field, the
representatives and bound as raw bits, the integer bin limits and their types, `is_exact` and
the `RangeCheck` of 4,236 cases (the ten pixel types, NaN and +/-inf, subnormal, constant,
empty and dtype-extreme planes, bin-edge float grids, several bin counts, min-max and robust,
whole and in 3 blocks, 64-bit ranges on both sides of each int64 condition) with
`tests/data/histogram_v070_parity.json`, recorded on v0.7.0 (`c6a9f9d`) by
`tests/histogram_parity_cases.py`; and the kept Python paths with the int64 ones switched off.
`tools/dump_outputs.py` (default and `--corpus`) gives the digests of v0.7.0.
- **Measured** (the study's data and scripts: `tools/benchmark_run_workers.py` at scale 1, 14 images,
76 planes, 303 MiB, memory limit 64 MiB; preprocessing v0.6.1 `37c583e`; Linux, 4 shared CPUs,
load average 2.6–3.4, Python 3.13.18, NumPy 2.5.5; 5 repeats, variants interleaved in rotating
order, a fresh process per run). Wall time of `run_experiment`, median (min–max):

| workers | v0.7.0 | this change | speed-up |
|---|---|---|---|
| 1 (serial) | 7.23 s (6.25–7.70) | 4.95 s (4.66–5.31) | 1.46× |
| 2 | 6.24 s (5.78–6.63) | 4.16 s (4.10–5.04) | 1.50× |
| 4 | 6.18 s (5.66–6.52) | 4.78 s (4.16–5.17) | 1.29× |
| auto (4) | 6.40 s (5.54–6.56) | 4.51 s (4.11–4.75) | 1.42× |

Median CPU time fell from 6.6–7.3 s to 4.9–5.5 s. All 40 runs wrote the same bytes in all 6
files (fixed clock). The normalization suite runs in 20 s instead of 51 s before the new
parity tests (45 s with them).

## v0.7.0 (2026-11-15)

Step 1 of MorphoBricks-Spec [ADR 0005](https://github.com/CellMigrationLab/MorphoBricks-Spec/blob/main/docs/adr/0005-binary-masks.md)
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ baseline = "tools/code_rules_baseline.json"
"morphobricks_normalization.fitting" = "pure"
"morphobricks_normalization.histogram" = "pure"
"morphobricks_normalization.integrity" = "pure"
"morphobricks_normalization.integer_bins" = "pure"
"morphobricks_normalization.integer_representatives" = "pure"
"morphobricks_normalization.issues" = "pure"
"morphobricks_normalization.normalization" = "pure"
Expand Down
52 changes: 21 additions & 31 deletions src/morphobricks_normalization/histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@

from __future__ import annotations

import bisect
import math
from collections.abc import Callable, Iterable
from dataclasses import dataclass
Expand All @@ -53,6 +52,12 @@

from .bin_centres import float_bin_centres, float_bin_position
from .dtypes import check_supported, default_bin_count, is_integer, validate_bin_count
from .integer_bins import (
counts_from_per_value,
integer_bin_index,
integer_bin_offsets,
search_starts,
)
from .integer_representatives import beyond_float_exact, integer_representatives, wide_integer_error
from .integrity import check_histogram, check_tail, checked_blocks
from .ranges import CENTRAL_PERCENTILES, HistogramSettings, RangeCheck
Expand Down Expand Up @@ -191,7 +196,10 @@ def max_representative_error(self) -> float:
return wide_integer_error(self)
if is_integer(self.dtype):
first, last = self._integer_bin_limits
widest = max(b - a + 1 for a, b in zip(first, last, strict=True))
if isinstance(first, np.ndarray):
widest = int((last - first).max()) + 1
else:
widest = max(b - a + 1 for a, b in zip(first, last, strict=True))
bins = (widest - 1) / 2
else:
lo, hi = float(self.binning_min), float(self.binning_max)
Expand Down Expand Up @@ -223,15 +231,16 @@ def integer_bin_limits(self) -> list[tuple[int, int]]:
if self.is_empty:
return []
first, last = self._integer_bin_limits
if isinstance(first, np.ndarray):
first, last = first.tolist(), last.tolist()
return [
(self.binning_min + a, self.binning_min + b) for a, b in zip(first, last, strict=True)
]

@cached_property
def _integer_bin_limits(self) -> tuple[list[int], list[int]]:
"""Bin limits as offsets from ``binning_min`` (exact Python integers)."""
starts = _integer_bin_starts(self.binning_max + 1 - self.binning_min, self.bin_count)
return starts[:-1], [s - 1 for s in starts[1:]]
def _integer_bin_limits(self) -> tuple[np.ndarray, np.ndarray] | tuple[list[int], list[int]]:
"""Bin limits as offsets from ``binning_min``: int64 arrays or exact Python integers."""
return integer_bin_offsets(self.binning_min, self.binning_max, self.bin_count)


def compute_plane_histogram(
Expand Down Expand Up @@ -417,28 +426,13 @@ def _measure(
return _wide_histogram(blocks, dtype, n, settings, check)


def _integer_bin_starts(width: int, bin_count: int) -> list[int]:
"""Offsets at which bins ``0 .. bin_count`` start (the last entry is ``width``)."""
if width <= bin_count:
# One value per bin from the start; the remaining bins stay empty.
return [min(i, width) for i in range(bin_count + 1)]
return [-((-i * width) // bin_count) for i in range(bin_count + 1)]


def _as_ordered_uint64(values: np.ndarray) -> np.ndarray:
"""Map integers to uint64 while keeping their order, without overflow."""
if values.dtype.kind == "u":
return values.astype(np.uint64)
return values.astype(np.int64).view(np.uint64) ^ np.uint64(1 << 63)


def _counts_from_per_value(per_value: np.ndarray, starts: list[int], n: int) -> np.ndarray:
"""Sum per-value counts (offsets ``0 .. width - 1``) into bins starting at ``starts``."""
bin_of_value = np.searchsorted(np.array(starts[:-1]), np.arange(per_value.size), side="right")
counts = np.bincount(bin_of_value - 1, weights=per_value, minlength=n)
return np.rint(counts).astype(np.int64)


def _small_integer_histogram(
blocks: Iterable[np.ndarray],
dtype: np.dtype,
Expand Down Expand Up @@ -466,9 +460,7 @@ def _small_integer_histogram(
smallest = int(np.iinfo(dtype).min)

def min_max() -> PlaneHistogram:
counts = _counts_from_per_value(
table[first : last + 1], _integer_bin_starts(last + 1 - first, n), n
)
counts = counts_from_per_value(table[first : last + 1], n)
lo, hi = smallest + first, smallest + last
return PlaneHistogram(dtype, n, lo, hi, counts, total, total, pixel_min=lo, pixel_max=hi)

Expand All @@ -486,8 +478,7 @@ def order(q: float) -> _Order:
orders = [order(q) for q in quantiles]
if settings.robust:
low, high = orders[0].value - smallest, orders[1].value - smallest
starts = _integer_bin_starts(high + 1 - low, n)
counts = _counts_from_per_value(table[low : high + 1], starts, n)
counts = counts_from_per_value(table[low : high + 1], n)
histogram = PlaneHistogram(
dtype,
n,
Expand Down Expand Up @@ -614,11 +605,11 @@ def _integer_bins(
under: TailMoments,
over: TailMoments,
) -> np.ndarray:
"""Count integer pixels into bins: per value up to 2**24 values, else by searching starts."""
width = hi + 1 - lo
starts = _integer_bin_starts(width, n)
origin = _as_ordered_uint64(np.array([lo], dtype=dtype))[0]
per_value = np.zeros(width, dtype=np.int64) if width <= _PER_VALUE_COUNT_LIMIT else None
bin_starts = np.array(starts[:-1], dtype=np.uint64)
bin_starts = search_starts(width, n) if per_value is None else None
counts = np.zeros(n, dtype=np.int64)
for values in checked_blocks(blocks(), dtype):
if values.size == 0:
Expand All @@ -638,7 +629,7 @@ def _integer_bins(
index = np.searchsorted(bin_starts, offsets, side="right") - 1
counts += np.bincount(index, minlength=n)
if per_value is not None:
counts = _counts_from_per_value(per_value, starts, n)
counts = counts_from_per_value(per_value, n)
return counts


Expand Down Expand Up @@ -824,8 +815,7 @@ def _bin_index(
) -> int:
"""Return the bin of ``value`` with bins over ``[lo, hi]``, values outside clipped."""
if is_integer(dtype):
starts = _integer_bin_starts(hi + 1 - lo, n)
index = bisect.bisect_right(starts, value - lo, hi=n) - 1
index = integer_bin_index(value - lo, hi + 1 - lo, n)
elif lo == hi:
index = 0
else:
Expand Down
106 changes: 106 additions & 0 deletions src/morphobricks_normalization/integer_bins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
"""Whole-number bin limits of integer planes, in int64 where that is exact.

Bin ``i`` of ``n`` bins over ``width`` values starts at offset ``ceil(i * width / n)``
(or ``min(i, width)`` when ``width <= n``, one value per bin). Until v0.7.0 these limits,
the sums of per-value counts into bins and the bin of a value were found with loops over
every bin in Python. Here the same integers come from NumPy int64 arithmetic wherever no
step can overflow, and from the exact Python integers of v0.7.0 everywhere else
(64-bit planes with a wide range), so no count, limit or float built from them changes.
"""

from __future__ import annotations

import numpy as np

INT64_STARTS_LIMIT = 2**62
"""Bin starts are int64 when ``bin_count * width`` is below this: no product can overflow."""

EXACT_FLOAT_TOTAL = 2.0**52
"""Per-value counts are summed in int64 while their float64 total is below this.

Every partial sum is then below ``2**53``, so the float64 sums used until v0.7.0 were
exact and equal the int64 sums; beyond it (never for one plane in memory) they are kept.
"""


def integer_bin_starts(width: int, bin_count: int) -> list[int]:
"""Offsets at which bins ``0 .. bin_count`` start (the last entry is ``width``)."""
if width <= bin_count:
# One value per bin from the start; the remaining bins stay empty.
return [min(i, width) for i in range(bin_count + 1)]
return [-((-i * width) // bin_count) for i in range(bin_count + 1)]


def integer_bin_starts_int64(width: int, bin_count: int) -> np.ndarray | None:
"""Return :func:`integer_bin_starts` as an int64 array, or None if int64 could overflow.

The same integers from the same formula: NumPy's integer floor division rounds towards
minus infinity, as Python's does. None when ``bin_count * width`` reaches ``2**62``
(64-bit planes with a wide range), where only Python integers are exact.
"""
if bin_count * max(width, 1) >= INT64_STARTS_LIMIT:
return None
index = np.arange(bin_count + 1, dtype=np.int64)
if width <= bin_count:
return np.minimum(index, width)
return -((-index * width) // bin_count)


def integer_bin_offsets(
binning_min: int, binning_max: int, bin_count: int
) -> tuple[np.ndarray, np.ndarray] | tuple[list[int], list[int]]:
"""Return every bin's first and last value, as offsets from ``binning_min``.

int64 arrays when both limits and the bin count are Python integers (as in every
histogram computed or read by this library) and the starts fit int64; otherwise the
exact Python integers of v0.7.0, so that results built from them keep their values and
types. A NumPy bin count would make ``bin_count * width`` a NumPy product that can wrap.
"""
width = binning_max + 1 - binning_min
python_ints = type(width) is int and type(bin_count) is int
starts = integer_bin_starts_int64(width, bin_count) if python_ints else None
if starts is not None:
return starts[:-1], starts[1:] - 1
starts = integer_bin_starts(width, bin_count)
return starts[:-1], [s - 1 for s in starts[1:]]


def search_starts(width: int, bin_count: int) -> np.ndarray:
"""Return the starts of bins ``0 .. bin_count - 1`` as uint64, for a sorted search."""
starts = integer_bin_starts_int64(width, bin_count)
if starts is None: # a wide 64-bit range: computed as exact Python integers
return np.array(integer_bin_starts(width, bin_count)[:-1], dtype=np.uint64)
return starts[:-1].astype(np.uint64)


def counts_from_per_value(per_value: np.ndarray, bin_count: int) -> np.ndarray:
"""Sum per-value counts (offsets ``0 .. width - 1``) into ``bin_count`` bins over that width.

Exact int64 sums (differences of the cumulative counts at the bin starts) while the
total is below :data:`EXACT_FLOAT_TOTAL`; otherwise the float64 sums of v0.7.0.
"""
width = per_value.size
starts = integer_bin_starts_int64(width, bin_count)
if starts is not None and float(np.sum(per_value, dtype=np.float64)) < EXACT_FLOAT_TOTAL:
cumulative = np.zeros(width + 1, dtype=np.int64)
np.cumsum(per_value, out=cumulative[1:])
return cumulative[starts[1:]] - cumulative[starts[:-1]]
starts = integer_bin_starts(width, bin_count)
bin_of_value = np.searchsorted(np.array(starts[:-1]), np.arange(width), side="right")
counts = np.bincount(bin_of_value - 1, weights=per_value, minlength=bin_count)
return np.rint(counts).astype(np.int64)


def integer_bin_index(offset: int, width: int, bin_count: int) -> int:
"""Return ``bisect_right(integer_bin_starts(width, n), offset, hi=n) - 1`` in O(1).

Exact integer arithmetic: -1 below the range. With no more values than bins, value
``offset`` is in bin ``offset`` and a value above the range in the last bin. Otherwise
bin ``i`` starts at ``ceil(i * width / n)``, which is at most ``offset`` exactly when
``i <= offset * n / width``.
"""
if offset < 0:
return -1
if width <= bin_count:
return offset if offset < width else bin_count - 1
return min(offset * bin_count // width, bin_count - 1)
11 changes: 10 additions & 1 deletion src/morphobricks_normalization/integer_representatives.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,16 @@


def integer_representatives(histogram: PlaneHistogram) -> np.ndarray:
"""Return the float64 nearest the midpoint of every bin of a non-empty integer plane."""
"""Return the float64 nearest the midpoint of every bin of a non-empty integer plane.

Below ``2**51`` with int64 bin limits, ``first + last`` is an int64 below ``2**53`` and
so an exact float64, and halving it is exact: the same floats as the Python division.
"""
# The histogram's own limits (int64 arrays, or Python integers for wide 64-bit ranges).
first, last = histogram._integer_bin_limits
if isinstance(first, np.ndarray) and not beyond_float_exact(histogram):
lo = histogram.binning_min
return ((first + lo) + (last + lo)).astype(np.float64) / 2
return np.array(
[(first + last) / 2 for first, last in histogram.integer_bin_limits()], dtype=np.float64
)
Expand Down
Loading
Loading