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
35 changes: 35 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,41 @@ The decisions are in [docs/plan.md](docs/plan.md) §12.

## Unreleased

Signed zero is written as `0.0` (#105; owner decision 17 November 2026, plan N71). Behaviour
change for written text only: no computed value, algorithm, API, schema version or message
changes.

- **Every float the package writes goes through one module**, the new `float_text`
(`canonical_zero`, `float_text`, `positive_zero`): the float cells of `plane_histograms.csv`
(`Intensity_Min/MaxIntensity`, `Histogram_BinningMin/Max`, the underflow and overflow means
and standard deviations), the `Normalization_Offset/Scale_<ID>` columns of
`Parameters.to_columns()` and the percentiles of `percentile_name` (which already wrote
`-0.0` as `0`; now through the same helper).
- **Values handed to a caller who writes them change only at zero** (`positive_zero`): in
`ImageSummary.to_row()` and in the run-configuration dictionaries
`NormalizationSettings.to_dict()` (`percentile`), `HistogramSettings.to_dict()`
(`robust_quantiles`) and `IntensityCheckSettings.to_dict()` (`saturation_limit`), a float zero
of either sign, Python or NumPy, becomes the Python float `0.0`; every other value is returned
as given, with its type and text (an `int` stays an `int`, a `np.float32(0.1)` still writes
`0.1`), as in v0.7.0.
- **NumPy float limits of a caller-built `PlaneHistogram`** (`compute_*` always gives Python
numbers): a NumPy float zero of either sign is now written `0.0` too. Side fix: `np.float64`
limits were written as `np.float64(0.25)`, which the reader refuses; they are now written as
the Python float's `repr` (`0.25`) and read back. `np.float32` and integer limits are written
as before (`str`). A float
plane holding both `-0.0` and `+0.0` has a `pixel_min` or `pixel_max` of either zero
depending on NumPy's `min`/`max`, the element order and the platform; the same pixels now
write the same bytes everywhere. `x + 0.0` changes no float but `-0.0`; NaN and the
infinities are written as before. The in-memory `PlaneHistogram`, `Parameters` and
`ImageSummary` values keep their sign.
- **Files that change**: only those that held `-0.0`, now `0.0` in the same cells (they read
back as an equal float). No recorded golden or parity table of this repository holds a
`-0.0`, and `tools/dump_outputs.py` (default and `--corpus`) gives the same digests as
before (`032b395b…` and `0111f8bd…`).
- **Tests**: `tests/test_signed_zero.py`, which fails on v0.7.0 for every writer path, including
planes mixing signed zeros in every order of `[-0.0, 0.0, -0.0, 0.0]` and three mixed ones,
each written in three orders to the same bytes.

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.
Expand Down
12 changes: 7 additions & 5 deletions docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -988,8 +988,8 @@ Every MorphoBricks table with values per channel puts the channels in columns, n
does not have is blank there, never zero.

Common format: UTF-8, comma-separated, one header row, rows in a deterministic order, floats
written at full precision (Python `repr`), blanks for missing values, written to a temporary
file and replaced only once writing succeeded.
written at full precision (Python `repr`), `-0.0` written as `0.0` (N71, #105), blanks for
missing values, written to a temporary file and replaced only once writing succeeded.

### 6.2 `plane_histograms.csv` (schema version 5)

Expand Down Expand Up @@ -1070,8 +1070,9 @@ types (`IncompatibleSummariesError`, a `ValueError`). An `ImageSummary` whose pe
have different lengths is refused when made, and `intensity_checks` refuses summaries with
different numbers of channels or different percentile definitions, with the same error.
`ImageSummary.to_row()` gives the columns below as a dictionary, in this order (numbers as
floats, a blank as `None`, `Histogram_Exact_<ID>` as a bool; a channel the image does not
have is not in the row and is blank in a table), and `summary_columns(channel_ids)` the names
floats, `-0.0` as `0.0` (N71), a blank as `None`, `Histogram_Exact_<ID>` as a bool; a
channel the image does not have is not in the row and is blank in a table), and
`summary_columns(channel_ids)` the names
for the experiment's channel IDs, so the calling brick can show the rows as a table or write them; the
library writes no file (N50). The columns are the shared columns `source_relative_path`,
`condition`, `biological_repeat`, `technical_repeat`, `image_file`, and for each channel ID
Expand Down Expand Up @@ -1154,7 +1155,8 @@ selects a channel; one rule for every table was chosen over an RGB exception.

### 8.2 Formatting

- Numbers at full precision (Python `repr` of the float), read back unchanged.
- Numbers at full precision (Python `repr` of the float), read back unchanged; `-0.0` is
written as `0.0` (N71, #105).
- `from_columns` reads only the `Normalization_Offset_<ID>` and `Normalization_Scale_<ID>`
columns (N47, token by HV2), taking every `<ID>` that follows the Token rule, once
`normalization_parameters_version` is `2`. A column of the version-4 naming,
Expand Down
10 changes: 10 additions & 0 deletions docs/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,16 @@ binary masks", accepted; decisions BM3, BM7, BM8 and BM10, step 1 of its impleme
undefined estimate. normalization holds the only constructor of `RESOLVER_VERSION_UNSUPPORTED`,
`contracts.refuse_resolver_version(found, supported)`, which every consumer of
preprocessing's resolver calls (contract §3.5).
65. **N71** (17 November 2026, issue #105, owner's choice of rule 2) Signed zero is written as
`0.0`. Every float the package writes as text (the cells of `plane_histograms.csv`, the
parameter columns of §8, the percentiles of a method name) goes through
`float_text.canonical_zero`, and the values it hands a caller to write
(`ImageSummary.to_row()` and the `to_dict()` of `NormalizationSettings`,
`HistogramSettings` and `IntensityCheckSettings`) through `float_text.positive_zero`, which
replaces only a float zero; so a plane whose `pixel_min` or `pixel_max` is `-0.0` on one
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).

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 @@ -105,6 +105,7 @@ baseline = "tools/code_rules_baseline.json"
"morphobricks_normalization.csv_io" = "io"
"morphobricks_normalization.dtypes" = "pure"
"morphobricks_normalization.fitting" = "pure"
"morphobricks_normalization.float_text" = "pure"
"morphobricks_normalization.histogram" = "pure"
"morphobricks_normalization.integrity" = "pure"
"morphobricks_normalization.integer_bins" = "pure"
Expand Down
5 changes: 3 additions & 2 deletions src/morphobricks_normalization/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import numpy as np

from ._version import __version__
from .float_text import positive_zero
from .issues import (
CHANNEL_WITHOUT_FINITE_PIXELS,
IMAGE_INTENSITY_OUTLIER,
Expand Down Expand Up @@ -133,11 +134,11 @@ def __post_init__(self) -> None:
object.__setattr__(self, "min_images", int(min_images))

def to_dict(self) -> dict[str, Any]:
"""JSON-compatible limits, for the calling brick's run configuration."""
"""JSON-compatible limits, for the calling brick's run configuration (``-0.0`` as 0.0)."""
return {
"library_version": __version__,
"outlier_limit": self.outlier_limit,
"saturation_limit": self.saturation_limit,
"saturation_limit": positive_zero(self.saturation_limit),
"min_images": self.min_images,
}

Expand Down
11 changes: 8 additions & 3 deletions src/morphobricks_normalization/csv_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

Labels are always read back as text, so folder names such as ``NA``, ``001``
or ``TRUE`` keep their exact spelling. Float values are written at full
precision and read back unchanged.
precision and read back unchanged, but for ``-0.0``, written as ``0.0`` (#105).
"""

from __future__ import annotations
Expand All @@ -44,6 +44,7 @@

from .channels import check_channel_ids
from .dtypes import bit_depth, check_supported, is_integer
from .float_text import float_text, positive_zero
from .histogram import EMPTY_TAIL, HistogramTail, PlaneHistogram
from .records import (
ChannelMeasurementError,
Expand Down Expand Up @@ -552,7 +553,7 @@ def _duplicate_message(path: str | Path, plane_id: str, lines: dict[str, int], l


def _tail_text(tail: HistogramTail) -> tuple[str, str, str]:
return str(tail.count), repr(float(tail.mean)), repr(float(tail.std))
return str(tail.count), float_text(tail.mean), float_text(tail.std)


def _tail(texts: list[str]) -> HistogramTail:
Expand Down Expand Up @@ -582,10 +583,14 @@ def _earlier_version_message(path: str | Path, version: str) -> str:


def _text(value: object) -> str:
# A float zero of either sign, Python or NumPy, is written 0.0 (#105). Other Python and
# np.float64 values are written as repr of the Python float (np.float64's own repr would be
# np.float64(...)); other NumPy scalars and integers as str, as before.
if value is None:
return ""
value = positive_zero(value)
if isinstance(value, float):
return repr(value)
return float_text(value)
return str(value)


Expand Down
51 changes: 51 additions & 0 deletions src/morphobricks_normalization/float_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""The one place a float is turned into written text: signed zero is written as ``0.0`` (#105).

A float plane holding both ``-0.0`` and ``+0.0`` gets a ``pixel_min`` or ``pixel_max`` of
either zero, depending on NumPy's ``min``/``max``, the element order and the platform. So that
the same pixels write the same bytes everywhere, every float the package writes (the cells of
``plane_histograms.csv``, the parameter columns of contract §8.1 and the percentiles of a
method name) goes through :func:`canonical_zero`: ``-0.0`` becomes ``0.0``. Values handed to a
caller who writes them (the image summary rows of contract §7.1 and the ``to_dict()`` of the
three settings classes) go through
:func:`positive_zero`, which replaces a float zero and returns every other value as given.
Every other value, NaN and the infinities included, is unchanged, and no computed value
changes: only what is written does.
"""

from __future__ import annotations

from typing import TypeVar

import numpy as np

_Value = TypeVar("_Value")


def canonical_zero(value: float) -> float:
"""Return ``value`` as a Python float, with ``-0.0`` replaced by ``0.0``.

``x + 0.0`` is ``x`` for every float but ``-0.0``, whose sum with ``0.0`` is ``0.0``
under round-to-nearest (IEEE 754), so no other value can change.
"""
return float(value) + 0.0


def positive_zero(value: _Value) -> _Value | float:
"""Return ``0.0`` for a float zero of either sign, Python or NumPy; ``value`` otherwise.

For values handed to a caller who writes them (rows and settings dictionaries): only a
float zero is replaced, so every other value keeps its type and its text (an ``int``, a
``np.float32(0.1)``, None, a bool or text are returned as they are).
"""
if isinstance(value, float | np.floating) and value == 0:
return 0.0
return value


def float_text(value: float) -> str:
"""Return the written text of a float: its shortest round-trip ``repr``, ``0.0`` for ``-0.0``.

The text reads back as the same float (``float(float_text(x)) == x``), the sign of zero
aside.
"""
return repr(canonical_zero(value))
3 changes: 2 additions & 1 deletion src/morphobricks_normalization/normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import numpy as np

from .float_text import canonical_zero
from .parameter_checks import check_offset_scale
from .pooling import PooledHistogram

Expand Down Expand Up @@ -142,7 +143,7 @@ def percentile_name(low: float, high: float) -> str:

def _exact_decimal(value: float) -> str:
"""Shortest positional decimal that round-trips to ``value`` (``-0.0`` as ``0``)."""
return np.format_float_positional(float(value) + 0.0, unique=True, trim="-")
return np.format_float_positional(canonical_zero(value), unique=True, trim="-")


def z_score(pooled: PooledHistogram) -> NormalizationParameters:
Expand Down
7 changes: 4 additions & 3 deletions src/morphobricks_normalization/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import numpy as np

from .channels import CHANNEL_ID_PATTERN, check_channel_ids
from .float_text import float_text
from .issues import Issue
from .parameter_checks import check_offset_scale, check_scope
from .rgb import RGB_CHANNELS, apply_rgb, check_rgb_channels, check_rgb_selection
Expand Down Expand Up @@ -247,7 +248,7 @@ def _apply_order(
return [self.channels.index(channel) for channel in ids]

def to_columns(self) -> dict[str, str]:
"""Return the columns of contract §8.1 as text, numbers in full.
"""Return the columns of contract §8.1 as text, numbers in full (``-0.0`` as ``0.0``).

The five ``normalization_*`` columns (the last the columns' version, ``2``),
then ``Normalization_Offset_<ID>``
Expand All @@ -263,8 +264,8 @@ def to_columns(self) -> dict[str, str]:
VERSION_COLUMN: str(PARAMETERS_VERSION),
}
for channel, offset, scale in zip(self.channels, self.offset, self.scale, strict=True):
columns[offset_column(channel)] = repr(offset)
columns[scale_column(channel)] = repr(scale)
columns[offset_column(channel)] = float_text(offset)
columns[scale_column(channel)] = float_text(scale)
return columns

@classmethod
Expand Down
5 changes: 3 additions & 2 deletions src/morphobricks_normalization/ranges.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

from ._version import __version__
from .channels import check_channel_id
from .float_text import positive_zero
from .issues import NARROW_HISTOGRAM_RANGE, WARNING, Issue

HISTOGRAM_RANGES = ("minmax", "robust")
Expand Down Expand Up @@ -109,11 +110,11 @@ def robust(self) -> bool:
return self.histogram_range == "robust"

def to_dict(self) -> dict[str, Any]:
"""JSON-compatible settings, for the run configuration."""
"""JSON-compatible settings, for the run configuration (``-0.0`` as ``0.0``, #105)."""
return {
"library_version": __version__,
"histogram_range": self.histogram_range,
"robust_quantiles": list(self.robust_quantiles),
"robust_quantiles": [positive_zero(value) for value in self.robust_quantiles],
"min_central_bins": self.min_central_bins,
}

Expand Down
8 changes: 6 additions & 2 deletions src/morphobricks_normalization/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from typing import Any

from ._version import __version__
from .float_text import positive_zero
from .issues import BIOLOGICAL_REPEAT_SCOPE, WARNING, Issue
from .normalization import NORMAL_CONSISTENCY, percentile_name

Expand Down Expand Up @@ -170,14 +171,17 @@ def method_name(self) -> str:
return _METHOD_NAMES[self.method]

def to_dict(self) -> dict[str, Any]:
"""JSON-compatible settings for the run configuration, without options that do not apply."""
"""JSON-compatible settings for the run configuration, without options that do not apply.

A percentile of ``-0.0`` is written ``0.0`` (#105).
"""
data: dict[str, Any] = {
"library_version": __version__,
"image_type": self.image_type,
"method": self.method,
}
if self.method == "percentile":
data["percentile"] = list(self.percentile)
data["percentile"] = [positive_zero(value) for value in self.percentile]
if self.method == "robust_zscore":
data["consistency"] = self.consistency
data["scope"] = self.scope
Expand Down
17 changes: 9 additions & 8 deletions src/morphobricks_normalization/summaries.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from .channels import check_channel_ids
from .csv_io import channel_column
from .dtypes import is_integer
from .float_text import positive_zero
from .pooling import NoValidPixelsError, PooledHistogram
from .records import PlaneRecord, duplicate_planes, same_channels_per_image
from .settings import DEFAULT_PERCENTILE
Expand Down Expand Up @@ -140,10 +141,10 @@ def to_row(self) -> dict[str, Any]:

The shared columns as text, then for each channel of the image, in sorted ID
order, the median, low and high percentiles and saturated fraction as floats
(None for a blank) and ``Histogram_Exact_<ID>`` as a bool (None for a channel
without finite pixels). Channels the image does not have are not in the row; a
table of the experiment (:func:`summary_columns`) leaves them blank, for
example ``csv.DictWriter(..., restval="")``. A list of rows can be passed to
(None for a blank; ``-0.0`` as ``0.0``, #105) and ``Histogram_Exact_<ID>`` as a
bool (None for a channel without finite pixels). Channels the image does not have
are not in the row; a table of the experiment (:func:`summary_columns`) leaves them
blank, for example ``csv.DictWriter(..., restval="")``. A list of rows can be passed to
``pandas.DataFrame`` or ``csv.DictWriter``.
"""
row: dict[str, Any] = {
Expand All @@ -155,10 +156,10 @@ def to_row(self) -> dict[str, Any]:
}
for k, channel in enumerate(self.channels):
values = (
self.median[k],
self.p_low[k],
self.p_high[k],
self.saturated_fraction[k],
positive_zero(self.median[k]),
positive_zero(self.p_low[k]),
positive_zero(self.p_high[k]),
positive_zero(self.saturated_fraction[k]),
self.exact[k],
)
for feature, value in zip(SUMMARY_FEATURES, values, strict=True):
Expand Down
Loading
Loading