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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion docs/docs/Advanced/classification-logic.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`.

Expand Down
15 changes: 12 additions & 3 deletions src/stickler/comparators/base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Base class for comparators."""

import inspect
import math
from abc import ABC, abstractmethod
from typing import Any, Optional, Tuple

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down
7 changes: 4 additions & 3 deletions src/stickler/comparators/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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)
Expand Down
32 changes: 28 additions & 4 deletions src/stickler/structured_object_evaluator/models/null_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
used throughout the comparison process.
"""

import math
from typing import Any


Expand All @@ -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 <https://github.com/awslabs/stickler/issues/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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking, and you already documented this at L40 ("including numpy.float64"),
so this is a question about intent rather than a defect.

isinstance(val, float) catches a Python float and np.float64 (a float subclass),
but not np.float32, np.float16, or np.longdouble. Measured:

value baseline 1479c3d4 this PR 6a259d80
NumericComparator().compare(v, v), py-float / float64 NaN 0.0 1.0
same, np.float32 / np.float16 NaN 0.0 0.0

So the same missing value scores differently by dtype width, where the baseline was
uniformly 0.0.

Two things keep this low rather than blocking, and I want to be straight about both:

The normal path is fine. On a field annotated Optional[float], pydantic coerces
every numpy width to a Python float, so all four widths score 1.0 with a true
negative on your branch (all 0.0 with a false discovery on dev). A pandas float32
column bound to a typed float field is fully fixed. The split is only reachable via a
direct comparator call or a field annotated Any.

And the unfixed widths sit exactly at the old behaviour, so this is an incomplete fix
rather than a regression. Nothing got worse.

The part I think is worth acting on regardless: test_numpy_nan_is_absent exercises
np.float64 through a typed Optional[float] field, so pydantic coercion carries it
— the test would pass identically with no numpy handling at all. It doesn't currently
pin the numpy support it's named for. A case going through a direct comparator call or
an Any field would.

If you do want to widen it, concrete types read better here than an ABC:

return isinstance(val, (float, np.floating)) and math.isnan(val)

That needs an import numpy as np at the top — this module currently imports only
math and typing, which is why I'm not leaving it as a one-click suggestion.

I tried numbers.Real first and talked myself out of it: it admits int, bool and
Fraction, which can never be NaN, so a reader of a function named is_nan has to
work out why integers are in scope — and it still excludes Decimal('NaN'), since
Decimal isn't registered as numbers.Real. It looks more general than it is, which
is worse to maintain than your explicit float64-only scope. (Cost is not the reason:
I measured ~184ns vs ~38ns per call, which is nothing at field-per-case volume.)

Equally fine to declare float64-only the intended scope and just tighten the test. The
test gap is the part I'd act on; the predicate is your call.

Measured on two isolated clones, baseline dev @ 1479c3d4 and this PR @ 6a259d80,
each importing its own tree — __version__ is 1.0.0 on both, so I keyed off
hasattr(NullHelper, 'is_nan') instead.


@staticmethod
def is_effectively_null_for_lists(val: Any) -> bool:
"""Check if a list value is effectively null (None or empty list).
Expand All @@ -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
Expand All @@ -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)
)
11 changes: 7 additions & 4 deletions tests/auto/test_risk_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
97 changes: 97 additions & 0 deletions tests/structured_object_evaluator/test_nan_as_absent.py
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -843,6 +843,7 @@ def test_maybe_absent_is_a_superset_of_both_null_rules():
{"k": "v"},
0,
0.0,
float("nan"),
False,
set(),
(),
Expand Down
Loading