diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d52b8e1..ab45a0bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,13 @@ Each release links to full notes on the ### Fixed +- **A float `NaN` is now absent, the same as `None`.** Two identical `NaN`s + scored `0.0` and counted as a false discovery, because `NaN` equals nothing + under IEEE 754. `NaN` vs `NaN` or `None` is now a true negative scoring `1.0`, + `NaN` vs a number is a false alarm or false negative, and comparators apply + the same rule. This changes confusion counts for any field holding `NaN` + ([#367](https://github.com/awslabs/stickler/issues/367)) + - **An unrecognized key in a model config is now reported instead of dropped.** `model_from_json` read a closed set of keys and ignored everything else, so `"threshhold": 0.99` built at the fallback 0.5 with no exception and no warning, diff --git a/docs/docs/Advanced/classification-logic.md b/docs/docs/Advanced/classification-logic.md index 24085b4f..9a959816 100644 --- a/docs/docs/Advanced/classification-logic.md +++ b/docs/docs/Advanced/classification-logic.md @@ -32,6 +32,7 @@ False Alarm (FA) and False Discovery (FD) together make up the broader False Pos | `null` | `"value"` | FA | Spurious prediction | | `null` | `null` | TN | Correctly absent | | `""` | `null` | TN | Empty string treated as null | +| `NaN` | `NaN` | TN | Float NaN treated as null | ### Lists @@ -171,7 +172,7 @@ These are computed at every node of the result tree, from that node's own counts ## Edge Cases -**Null vs. empty equivalence** -- Empty strings (`""`), empty lists (`[]`), and empty objects (`{}`) are treated as null. Comparing any of these with `null` yields TN. +**Null vs. empty equivalence** -- Empty strings (`""`), empty lists (`[]`), empty objects (`{}`), and float `NaN` are treated as null. Comparing any of these with `null` yields TN. **TN in object matching** -- A TN is absence of evidence, not evidence of a match. Fields absent on both sides are excluded from the weighted object similarity used by Hungarian matching. If every field is absent, the similarity is defined as `1.0`. diff --git a/src/stickler/comparators/base.py b/src/stickler/comparators/base.py index 75657a4f..69cfd481 100644 --- a/src/stickler/comparators/base.py +++ b/src/stickler/comparators/base.py @@ -1,6 +1,7 @@ """Base class for comparators.""" import inspect +import math from abc import ABC, abstractmethod from typing import Any, Optional, Tuple @@ -58,6 +59,11 @@ def __init__(self, threshold: float = 1.0): return threshold != declared.default +def _is_missing(value: Any) -> bool: + """``None`` or a float NaN, the two values the shared policy reads as absent.""" + return value is None or (isinstance(value, float) and math.isnan(value)) + + class BaseComparator(ABC): """Base class for all comparators. @@ -180,7 +186,8 @@ def compare(self, str1: Any, str2: Any) -> float: Applies the shared ``None`` policy -- two missing values are an exact match, a missing value against a present one is a non-match, regardless of what "present" means for a particular comparator -- - then delegates to :meth:`_compare`. + then delegates to :meth:`_compare`. A float NaN counts as missing, + matching ``NullHelper.is_nan`` on the field path (#367). Args: str1: First value @@ -189,10 +196,12 @@ def compare(self, str1: Any, str2: Any) -> float: Returns: Similarity score between 0.0 and 1.0 """ - if str1 is None and str2 is None: + missing1 = _is_missing(str1) + missing2 = _is_missing(str2) + if missing1 and missing2: return 1.0 - if str1 is None or str2 is None: + if missing1 or missing2: return 0.0 return self._compare(str1, str2) diff --git a/src/stickler/comparators/numeric.py b/src/stickler/comparators/numeric.py index 31060d02..1fa19c4c 100644 --- a/src/stickler/comparators/numeric.py +++ b/src/stickler/comparators/numeric.py @@ -139,9 +139,10 @@ def _numbers_equal(self, num1: Decimal, num2: Decimal) -> bool: True if numbers are equal within tolerance, False otherwise """ # Guard non-finite values before tolerance arithmetic: Decimal - # NaN/Infinity subtraction raises InvalidOperation. Semantics match - # the tolerance=0 path: NaN equals nothing (including NaN), infinite - # values match only exactly. + # NaN/Infinity subtraction raises InvalidOperation. A float NaN never + # gets here -- ``compare()`` reads it as missing (#367) -- so this only + # sees a Decimal NaN, which equals nothing. Infinite values match only + # exactly. if num1.is_nan() or num2.is_nan(): return False if num1.is_infinite() or num2.is_infinite(): diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper.py b/src/stickler/structured_object_evaluator/models/comparison_helper.py index a447041c..14ba37bd 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper.py @@ -165,7 +165,11 @@ def _maybe_absent(val: Any) -> bool: ``test_maybe_absent_is_a_superset_of_both_null_rules`` pins that property so adding a case to either predicate without widening this one fails loudly. """ - return val is None or (isinstance(val, (str, list, dict)) and len(val) == 0) + return ( + val is None + or NullHelper.is_nan(val) + or (isinstance(val, (str, list, dict)) and len(val) == 0) + ) class ComparisonHelper: diff --git a/src/stickler/structured_object_evaluator/models/field_helper.py b/src/stickler/structured_object_evaluator/models/field_helper.py index fbba15e4..96e02ff2 100644 --- a/src/stickler/structured_object_evaluator/models/field_helper.py +++ b/src/stickler/structured_object_evaluator/models/field_helper.py @@ -2,6 +2,8 @@ from typing import Any, List, Type +from .null_helper import NullHelper + class FieldHelper: """Helper class for field iteration and classification patterns.""" @@ -32,7 +34,7 @@ def is_null_value(value: Any) -> bool: Returns: True if the value is null/empty, False otherwise """ - if value is None: + if value is None or NullHelper.is_nan(value): return True elif hasattr(value, "__len__") and not isinstance( value, (str, bytes, bytearray) diff --git a/src/stickler/structured_object_evaluator/models/null_helper.py b/src/stickler/structured_object_evaluator/models/null_helper.py index 04284694..060ff3a6 100644 --- a/src/stickler/structured_object_evaluator/models/null_helper.py +++ b/src/stickler/structured_object_evaluator/models/null_helper.py @@ -4,6 +4,7 @@ used throughout the comparison process. """ +import math from typing import Any @@ -22,6 +23,24 @@ def is_truly_null(val: Any) -> bool: """ return val is None + @staticmethod + def is_nan(val: Any) -> bool: + """Check if a value is a float NaN. + + NaN is read as absent, the same as ``None``: it is how pandas and numpy + spell a missing number, and it is not valid JSON, so it is never a value + an extractor was asked to produce. Reading it as a value scored two + identical NaNs 0.0, because NaN equals nothing under IEEE 754 + (`#367 `_). + + Args: + val: Value to check + + Returns: + True if the value is a float (including ``numpy.float64``) NaN + """ + return isinstance(val, float) and math.isnan(val) + @staticmethod def is_effectively_null_for_lists(val: Any) -> bool: """Check if a list value is effectively null (None or empty list). @@ -38,8 +57,8 @@ def is_effectively_null_for_lists(val: Any) -> bool: def is_effectively_null_for_primitives(val: Any) -> bool: """Check if a non-list value is effectively null. - Treats ``None``, an empty string and an empty dict as equivalent, which - is the rule the docs state: "Empty strings (``""``), empty lists + Treats ``None``, a float NaN (see :meth:`is_nan`), an empty string and + an empty dict as equivalent, which is the rule the docs state: "Empty strings (``""``), empty lists (``[]``), and empty objects (``{}``) are treated as null." Empty lists are the one case this does *not* answer, because list-ness is decided from the annotation rather than the value -- see @@ -60,6 +79,11 @@ def is_effectively_null_for_primitives(val: Any) -> bool: val: Value to check Returns: - True if the value is None, an empty string or an empty dict + True if the value is None, a float NaN, an empty string or an + empty dict """ - return val is None or (isinstance(val, (str, dict)) and len(val) == 0) + return ( + val is None + or NullHelper.is_nan(val) + or (isinstance(val, (str, dict)) and len(val) == 0) + ) diff --git a/tests/auto/test_risk_surface.py b/tests/auto/test_risk_surface.py index 18232b26..160212a1 100644 --- a/tests/auto/test_risk_surface.py +++ b/tests/auto/test_risk_surface.py @@ -820,13 +820,16 @@ class M(BaseModel): class TestNumericEdgeCases: """Numeric fields must not crash on non-finite values or mis-score Decimal.""" - def test_nan_does_not_crash(self): + def test_nan_reads_as_absent(self): class M(BaseModel): x: float - # Must not raise decimal.InvalidOperation. NaN never equals NaN. - r = stickler.evaluate(M(x=float("nan")), M(x=float("nan"))) - assert r.field_scores["x"] == pytest.approx(0.0) + # Must not raise decimal.InvalidOperation. NaN is absent, like None, + # so two NaNs match and NaN against a number does not (#367). + nan = float("nan") + assert stickler.evaluate(M(x=nan), M(x=nan)).field_scores["x"] == 1.0 + assert stickler.evaluate(M(x=nan), M(x=1.5)).field_scores["x"] == 0.0 + assert stickler.evaluate(M(x=1.5), M(x=nan)).field_scores["x"] == 0.0 def test_infinity_matches_exactly(self): class M(BaseModel): diff --git a/tests/structured_object_evaluator/test_nan_as_absent.py b/tests/structured_object_evaluator/test_nan_as_absent.py new file mode 100644 index 00000000..1ee3b558 --- /dev/null +++ b/tests/structured_object_evaluator/test_nan_as_absent.py @@ -0,0 +1,97 @@ +"""A float NaN is absent, the same as ``None`` (#367). + +NaN is how pandas and numpy spell a missing number. Read as a value it scored +two identical NaNs 0.0, because NaN equals nothing under IEEE 754. Read as +absent it takes ``None``'s place in every confusion-matrix cell. +""" + +from decimal import Decimal +from typing import List, Optional + +import numpy as np +import pytest + +from stickler.comparators.levenshtein import LevenshteinComparator +from stickler.comparators.numeric import NumericComparator +from stickler.structured_object_evaluator.models.comparable_field import ComparableField +from stickler.structured_object_evaluator.models.field_helper import FieldHelper +from stickler.structured_object_evaluator.models.null_helper import NullHelper +from stickler.structured_object_evaluator.models.structured_model import StructuredModel + +NAN = float("nan") + + +class Reading(StructuredModel): + value: Optional[float] = ComparableField( + comparator=NumericComparator(relative_tolerance=0.001), default=None + ) + + +class Item(StructuredModel): + sku: str = ComparableField(comparator=LevenshteinComparator(), default="a") + value: Optional[float] = ComparableField( + comparator=NumericComparator(), default=None + ) + + +class Order(StructuredModel): + items: Optional[List[Item]] = ComparableField(default=None) + + +def _counts(gt, pred): + result = Reading(value=gt).compare_with( + Reading(value=pred), include_confusion_matrix=True + ) + overall = result["confusion_matrix"]["fields"]["value"]["overall"] + counts = {k: overall[k] for k in ("tp", "tn", "fa", "fd", "fn") if overall[k]} + return result["field_scores"]["value"], counts + + +@pytest.mark.parametrize( + "gt, pred, score, counts", + [ + (NAN, NAN, 1.0, {"tn": 1}), + (NAN, None, 1.0, {"tn": 1}), + (None, NAN, 1.0, {"tn": 1}), + (NAN, 5.0, 0.0, {"fa": 1}), + (5.0, NAN, 0.0, {"fn": 1}), + ], +) +def test_nan_classifies_like_none(gt, pred, score, counts): + assert _counts(gt, pred) == (score, counts) + + +def test_numpy_nan_is_absent(): + assert _counts(np.float64("nan"), np.float64("nan")) == (1.0, {"tn": 1}) + + +def test_comparator_reads_nan_as_missing(): + cmp = NumericComparator(relative_tolerance=0.001) + assert cmp.compare(NAN, NAN) == 1.0 + assert cmp.compare(NAN, None) == 1.0 + assert cmp.compare(NAN, 1.0) == 0.0 + assert cmp.compare(1.0, NAN) == 0.0 + + +def test_decimal_nan_is_still_a_non_match(): + # Only a float NaN is absent; a Decimal NaN still reaches the guard. + assert NumericComparator().compare(Decimal("NaN"), Decimal("NaN")) == 0.0 + + +def test_nan_in_a_list_element_field_is_absent(): + gt = Order(items=[Item(sku="a", value=NAN)]) + pred = Order(items=[Item(sku="a", value=NAN)]) + result = gt.compare_with(pred, include_confusion_matrix=True) + + assert result["field_scores"]["items"] == 1.0 + leaf = result["confusion_matrix"]["fields"]["items"]["fields"]["value"] + assert leaf["overall"]["tn"] == 1 + assert leaf["overall"]["fd"] == 0 + + +def test_null_predicates_agree_on_nan(): + assert NullHelper.is_nan(NAN) + assert not NullHelper.is_nan(0.0) + assert not NullHelper.is_nan("nan") + assert NullHelper.is_effectively_null_for_primitives(NAN) + assert FieldHelper.is_null_value(NAN) diff --git a/tests/structured_object_evaluator/test_simple_list_in_structured_list.py b/tests/structured_object_evaluator/test_simple_list_in_structured_list.py index c49a8b0a..85950694 100644 --- a/tests/structured_object_evaluator/test_simple_list_in_structured_list.py +++ b/tests/structured_object_evaluator/test_simple_list_in_structured_list.py @@ -843,6 +843,7 @@ def test_maybe_absent_is_a_superset_of_both_null_rules(): {"k": "v"}, 0, 0.0, + float("nan"), False, set(), (),