diff --git a/CHANGELOG.md b/CHANGELOG.md index 96952ca..1f824e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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_` 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. diff --git a/docs/contract.md b/docs/contract.md index 19e0ba0..759a0ca 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -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) @@ -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_` 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_` 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 @@ -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_` and `Normalization_Scale_` columns (N47, token by HV2), taking every `` that follows the Token rule, once `normalization_parameters_version` is `2`. A column of the version-4 naming, diff --git a/docs/plan.md b/docs/plan.md index 9d112e3..262835c 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -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 diff --git a/pyproject.toml b/pyproject.toml index 9e3af86..29da8db 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/src/morphobricks_normalization/checks.py b/src/morphobricks_normalization/checks.py index 5c9a506..489960b 100644 --- a/src/morphobricks_normalization/checks.py +++ b/src/morphobricks_normalization/checks.py @@ -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, @@ -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, } diff --git a/src/morphobricks_normalization/csv_io.py b/src/morphobricks_normalization/csv_io.py index 9e1efb8..b794415 100644 --- a/src/morphobricks_normalization/csv_io.py +++ b/src/morphobricks_normalization/csv_io.py @@ -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 @@ -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, @@ -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: @@ -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) diff --git a/src/morphobricks_normalization/float_text.py b/src/morphobricks_normalization/float_text.py new file mode 100644 index 0000000..97402b6 --- /dev/null +++ b/src/morphobricks_normalization/float_text.py @@ -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)) diff --git a/src/morphobricks_normalization/normalization.py b/src/morphobricks_normalization/normalization.py index dd15666..328d2b0 100644 --- a/src/morphobricks_normalization/normalization.py +++ b/src/morphobricks_normalization/normalization.py @@ -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 @@ -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: diff --git a/src/morphobricks_normalization/parameters.py b/src/morphobricks_normalization/parameters.py index 7a41334..5e29138 100644 --- a/src/morphobricks_normalization/parameters.py +++ b/src/morphobricks_normalization/parameters.py @@ -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 @@ -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_`` @@ -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 diff --git a/src/morphobricks_normalization/ranges.py b/src/morphobricks_normalization/ranges.py index d620975..f8b48eb 100644 --- a/src/morphobricks_normalization/ranges.py +++ b/src/morphobricks_normalization/ranges.py @@ -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") @@ -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, } diff --git a/src/morphobricks_normalization/settings.py b/src/morphobricks_normalization/settings.py index 99eb86f..10a1d69 100644 --- a/src/morphobricks_normalization/settings.py +++ b/src/morphobricks_normalization/settings.py @@ -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 @@ -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 diff --git a/src/morphobricks_normalization/summaries.py b/src/morphobricks_normalization/summaries.py index af6ed0f..3d2a489 100644 --- a/src/morphobricks_normalization/summaries.py +++ b/src/morphobricks_normalization/summaries.py @@ -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 @@ -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_`` 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_`` 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] = { @@ -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): diff --git a/tests/test_signed_zero.py b/tests/test_signed_zero.py new file mode 100644 index 0000000..5c6c6ed --- /dev/null +++ b/tests/test_signed_zero.py @@ -0,0 +1,266 @@ +"""Issue #105: every float the package writes as text writes ``-0.0`` as ``0.0``. + +A float plane holding both zeros gets a ``pixel_min`` or ``pixel_max`` of ``-0.0`` or +``+0.0`` depending on NumPy's ``min``/``max``, which depends on the element order and the +platform. Owner decision (17 November 2026): the written files canonicalise signed zero to +``0.0``, so the same pixels write the same bytes on every platform. Nothing else changes: the +in-memory values keep their sign, and only zeros are touched. +""" + +import csv +import io +import itertools +import json +import math + +import numpy as np +import pytest + +from morphobricks_normalization import ( + HistogramSettings, + IntensityCheckSettings, + NormalizationSettings, + PlaneRecord, + compute_plane_histogram, + fit, + read_plane_histograms, + write_plane_histograms, +) +from morphobricks_normalization.float_text import canonical_zero, float_text, positive_zero +from morphobricks_normalization.histogram import HistogramTail, PlaneHistogram +from morphobricks_normalization.normalization import percentile_name +from morphobricks_normalization.summaries import ImageSummary + +FLOAT_COLUMNS = ( + "Intensity_MinIntensity_DNA", + "Intensity_MaxIntensity_DNA", + "Histogram_BinningMin_DNA", + "Histogram_BinningMax_DNA", +) + + +def _record(histogram): + return PlaneRecord( + "c/b/t/i.tif", "c", "b", "t", histograms=[histogram], channels=("DNA",), position_id="p" + ) + + +def _rows(path): + with open(path, newline="", encoding="utf-8") as fh: + return list(csv.DictReader(fh)) + + +def test_float_text_canonicalises_only_the_zero_sign(): + assert float_text(-0.0) == "0.0" + assert float_text(0.0) == "0.0" + assert math.copysign(1.0, canonical_zero(-0.0)) == 1.0 + for value in (1.5, -1.5, 5e-324, -5e-324, 1e308, -1e308, math.inf, -math.inf, 0.1 + 0.2): + assert float_text(value) == repr(value) + assert canonical_zero(value) == value + assert float_text(math.nan) == "nan" + assert float_text(np.float64(-0.0)) == "0.0" + assert float_text(np.float32(-0.0)) == "0.0" + + +def test_a_computed_negative_zero_plane_writes_0_0(tmp_path): + histogram = compute_plane_histogram(np.full((4, 4), -0.0, dtype=np.float32)) + # The computed values keep their sign: no numeric algorithm changes. + assert math.copysign(1.0, histogram.pixel_min) == -1.0 + assert math.copysign(1.0, histogram.binning_max) == -1.0 + path = write_plane_histograms([_record(histogram)], tmp_path / "t.csv", channel_ids=["DNA"]) + text = path.read_text(encoding="utf-8") + assert "-0.0" not in text + (row,) = _rows(path) + assert [row[column] for column in FLOAT_COLUMNS] == ["0.0"] * 4 + (back,) = read_plane_histograms(path) + assert back.histograms[0].pixel_min == 0.0 + + +@pytest.mark.parametrize( + "pixels", + [list(order) for order in itertools.permutations([-0.0, 0.0, -0.0, 0.0])] + + [[-0.0, 0.0, 1.0, -1.0], [1.0, 0.0, -0.0, -1.0], [-1.0, -0.0, 0.0]], +) +def test_planes_mixing_signed_zeros_write_the_same_bytes_in_every_order(tmp_path, pixels): + expected = sorted(pixels, key=lambda value: (value, math.copysign(1.0, value))) + files = [] + for k, order in enumerate((pixels, expected, expected[::-1])): + plane = np.asarray(order, dtype=np.float32).reshape(1, -1) + record = _record(compute_plane_histogram(plane, 4)) + files.append(write_plane_histograms([record], tmp_path / f"{k}.csv", channel_ids=["DNA"])) + data = [path.read_bytes() for path in files] + assert data[0] == data[1] == data[2] + assert b"-0.0," not in data[0] + + +def test_tail_mean_and_std_write_0_0(tmp_path): + base = compute_plane_histogram(np.array([[1.0, 2.0]], dtype=np.float32), 2) + tail = HistogramTail(1, -0.0, -0.0) + histogram = PlaneHistogram( + dtype=base.dtype, + bin_count=base.bin_count, + binning_min=base.binning_min, + binning_max=base.binning_max, + counts=base.counts, + total_pixel_count=base.total_pixel_count + 1, + valid_pixel_count=base.valid_pixel_count + 1, + pixel_min=-0.0, + pixel_max=base.pixel_max, + underflow=tail, + overflow=base.overflow, + ) + path = write_plane_histograms([_record(histogram)], tmp_path / "t.csv", channel_ids=["DNA"]) + (row,) = _rows(path) + assert row["Intensity_MinIntensity_DNA"] == "0.0" + assert row["Histogram_UnderflowMean_DNA"] == "0.0" + assert row["Histogram_UnderflowStd_DNA"] == "0.0" + assert "-0.0" not in path.read_text(encoding="utf-8") + + +def test_parameter_columns_write_0_0(): + pixels = np.array([[-0.0, 1.0], [-0.0, 2.0]], dtype=np.float32) + settings = NormalizationSettings(method="minmax", scope="image") + parameters = fit(pixels, settings, channels=["DNA"]) + assert math.copysign(1.0, parameters.offset[0]) == -1.0 # fitted value unchanged + columns = parameters.to_columns() + assert columns["Normalization_Offset_DNA"] == "0.0" + assert columns["Normalization_Scale_DNA"] == "2.0" + assert type(parameters).from_columns(columns, settings) == parameters + + +SUMMARY_VALUE_COLUMNS = ( + "Intensity_MedianIntensity_DNA", + "Intensity_LowPercentile_DNA", + "Intensity_HighPercentile_DNA", + "Intensity_SaturatedFraction_DNA", +) + + +def _summary(median, p_low, p_high, saturated): + return ImageSummary( + source_relative_path="c/b/t/i.tif", + condition="c", + biological_repeat="b", + technical_repeat="t", + dtype=np.dtype(np.float32), + percentile=(1.0, 99.8), + channels=("DNA",), + median=(median,), + p_low=(p_low,), + p_high=(p_high,), + saturated_fraction=(saturated,), + exact=(True,), + ) + + +def _written(row): + out = io.StringIO() + writer = csv.DictWriter(out, fieldnames=list(row)) + writer.writerow(row) + return out.getvalue() + + +@pytest.mark.parametrize("zero", [-0.0, np.float64(-0.0), np.float32(-0.0), 0.0, np.float32(0.0)]) +def test_summary_rows_hold_0_0(zero): + row = _summary(zero, zero, zero, None).to_row() + for column in SUMMARY_VALUE_COLUMNS[:3]: + assert type(row[column]) is float and math.copysign(1.0, row[column]) == 1.0 + assert str(row[column]) == "0.0" + assert row["Intensity_SaturatedFraction_DNA"] is None + assert row["Histogram_Exact_DNA"] is True + + +def test_summary_rows_keep_every_other_value_as_given(): + # Review of #110: only zeros change; other values keep their type and written text, so a + # row of caller-built values writes the bytes it wrote on v0.7.0 (values passed through). + values = (np.float32(0.1), 5, np.float64(0.25), 0.5) + row = _summary(*values).to_row() + for column, value in zip(SUMMARY_VALUE_COLUMNS, values, strict=True): + assert row[column] is value + old = dict(row, **dict(zip(SUMMARY_VALUE_COLUMNS, values, strict=True))) + assert _written(row) == _written(old) + assert "0.1,5,0.25,0.5" in _written(row) + + +def test_positive_zero_changes_only_float_zeros(): + for value in (0, 5, True, False, None, "0", np.int64(0), np.float32(0.1), math.nan, -math.inf): + assert positive_zero(value) is value + for zero in (-0.0, 0.0, np.float32(-0.0), np.float64(-0.0), np.float16(-0.0)): + result = positive_zero(zero) + assert type(result) is float and math.copysign(1.0, result) == 1.0 + + +def test_percentile_name_keeps_writing_zero_as_0(): + assert percentile_name(-0.0, 99.8) == percentile_name(0.0, 99.8) == "percentile 0-99.8" + + +def _with_limits(convert, low, high): + base = compute_plane_histogram(np.array([[low, high]], dtype=np.float32), 2) + return PlaneHistogram( + dtype=base.dtype, + bin_count=base.bin_count, + binning_min=convert(base.binning_min), + binning_max=convert(base.binning_max), + counts=base.counts, + total_pixel_count=base.total_pixel_count, + valid_pixel_count=base.valid_pixel_count, + pixel_min=convert(base.pixel_min), + pixel_max=convert(base.pixel_max), + ) + + +@pytest.mark.parametrize("convert", [np.float32, np.float64]) +def test_numpy_negative_zero_limits_write_0_0(tmp_path, convert): + # Review of #110: a PlaneHistogram built with NumPy float limits, not by compute_*. + histogram = _with_limits(convert, -0.0, 1.0) + assert type(histogram.pixel_min) is convert + assert math.copysign(1.0, histogram.pixel_min) == -1.0 + path = write_plane_histograms([_record(histogram)], tmp_path / "t.csv", channel_ids=["DNA"]) + (row,) = _rows(path) + assert [row[column] for column in FLOAT_COLUMNS] == ["0.0", "1.0", "0.0", "1.0"] + assert "-0.0" not in path.read_text(encoding="utf-8") + + +def test_numpy_non_zero_limits_write_readable_text(tmp_path): + # np.float64 limits were written as np.float64(0.25) before, which no reader can read; + # they are now written as the Python float's repr. np.float32 limits keep their str text. + written = {} + for convert in (np.float64, np.float32): + path = tmp_path / f"{convert.__name__}.csv" + write_plane_histograms( + [_record(_with_limits(convert, 0.25, 1.5))], path, channel_ids=["DNA"] + ) + (row,) = _rows(path) + written[convert] = [row[column] for column in FLOAT_COLUMNS] + (back,) = read_plane_histograms(path) + assert (back.histograms[0].pixel_min, back.histograms[0].pixel_max) == (0.25, 1.5) + assert written[np.float64] == written[np.float32] == ["0.25", "1.5", "0.25", "1.5"] + + +@pytest.mark.parametrize("zero", [-0.0, np.float64(-0.0), np.float32(-0.0)]) +def test_settings_dictionaries_write_0_0(zero): + # Review of #110: the run-configuration dictionaries are written as JSON by the caller. + cases = ( + (NormalizationSettings(method="percentile", percentile=(zero, 99.8)), "percentile", 0), + ( + HistogramSettings(histogram_range="robust", robust_quantiles=(zero, 99.9)), + "robust_quantiles", + 0, + ), + (IntensityCheckSettings(saturation_limit=zero), "saturation_limit", None), + ) + for settings, key, index in cases: + data = settings.to_dict() + value = data[key] if index is None else data[key][index] + assert type(value) is float and math.copysign(1.0, value) == 1.0 + assert "-0.0" not in json.dumps(data) + assert type(settings).from_dict(data) == settings + + +def test_settings_dictionaries_keep_non_zero_values(): + assert NormalizationSettings(method="percentile", percentile=(1.0, 99.8)).to_dict()[ + "percentile" + ] == [1.0, 99.8] + data = HistogramSettings(histogram_range="robust", robust_quantiles=(0.5, 99.5)).to_dict() + assert data["robust_quantiles"] == [0.5, 99.5] + assert IntensityCheckSettings(saturation_limit=0.25).to_dict()["saturation_limit"] == 0.25