From 89e176d3dba64e724191700aeeb4242a27e34d83 Mon Sep 17 00:00:00 2001 From: Yashvardhan Thanvi Date: Sun, 18 Oct 2026 10:40:54 +0530 Subject: [PATCH 1/3] fix(417)!: use one threshold tolerance at every classification gate A primitive list element was classified with ThresholdHelper.is_above_threshold, which accepts a score up to 1e-10 under the threshold. The field and nested-model gates in FieldComparator, the List[StructuredModel] pair count and recursion gate, the non_matches and field_comparisons collectors, the list item sub-field classifier, EvalResult.matched, HungarianMatcher.calculate_metrics and the evaluator_format fallback metrics all used a bare >=. A score of 0.7 + 0.1 (0.7999999999999999) against 0.8, such as the Laptop pair in threshold-gated-evaluation.md, was an FD at those gates and a TP on a List[str] element. Route every gate through ThresholdHelper.is_above_threshold. A score inside the tolerance now counts as a TP, keeps its score instead of being clipped to 0.0, and opens a list pair for field-by-field evaluation. Scores further under the threshold are unchanged. HungarianMatcher imports the helper inside calculate_metrics, so stickler.algorithms does not load the evaluator package at import time. Fixes #417 --- CHANGELOG.md | 22 ++ docs/docs/Advanced/classification-logic.md | 2 +- .../Advanced/threshold-gated-evaluation.md | 2 +- src/stickler/algorithms/README.md | 23 +- src/stickler/algorithms/hungarian.py | 19 +- src/stickler/auto/facade.py | 10 +- .../models/comparison_helper_base.py | 7 +- .../models/confusion_matrix_calculator.py | 3 +- .../models/field_comparator.py | 6 +- .../models/field_comparison_collector.py | 5 +- .../models/field_comparison_helper.py | 5 +- .../models/metrics_helper.py | 4 +- .../models/structured_list_comparator.py | 5 +- .../test_threshold_tolerance.py | 308 ++++++++++++++++++ 14 files changed, 392 insertions(+), 29 deletions(-) create mode 100644 tests/structured_object_evaluator/test_threshold_tolerance.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a93f689..6b058351 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,28 @@ Each release links to full notes on the ([#322](https://github.com/awslabs/stickler/issues/322)). See [`None` elements in a list](https://awslabs.github.io/stickler/Advanced/classification-logic/#none-elements-in-a-list) +- **Breaking:** a score that floating-point arithmetic leaves just under its + threshold now gets the same verdict at every gate. A primitive list element + allowed a `1e-10` tolerance, but a field, a nested model, a + `List[StructuredModel]` pair and `EvalResult.matched` used a bare `>=`. The + Laptop pair in the threshold-gating docs scores `0.7999999999999999` against + `match_threshold = 0.8`, so it was an FD and was not descended into, while the + same score on a `List[str]` element was a TP. Every gate now uses + `ThresholdHelper.is_above_threshold`. A score up to `1e-10` under its + threshold: + - counts as a TP instead of an FD, in the confusion matrix, `non_matches` and + `field_comparisons`, for a field, a nested model, a list item's sub-field and + a list pair; + - keeps its score instead of being clipped to `0.0`, so `field_scores` and + `overall_score` can rise; + - opens a list pair for field-by-field evaluation; + - sets `EvalResult.matched`, and counts as a TP in + `HungarianMatcher.calculate_metrics` and the `evaluator_format=True` + fallback metrics. + + A score further under the threshold is unchanged, and so is a primitive list + element ([#417](https://github.com/awslabs/stickler/issues/417)) + ### Fixed - **A `RootModel` is now refused when the evaluator is built, instead of failing diff --git a/docs/docs/Advanced/classification-logic.md b/docs/docs/Advanced/classification-logic.md index d26993e4..9c20c407 100644 --- a/docs/docs/Advanced/classification-logic.md +++ b/docs/docs/Advanced/classification-logic.md @@ -194,7 +194,7 @@ These are computed at every node of the result tree, from that node's own counts **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`. -**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP). +**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP). So does a score up to `1e-10` under it, at every gate, so a rounding error such as `0.7 + 0.1` (`0.7999999999999999`) against `0.8` does not turn a TP into an FD. **List order** -- Order does not matter. The Hungarian algorithm finds the optimal pairing regardless of element position. diff --git a/docs/docs/Advanced/threshold-gated-evaluation.md b/docs/docs/Advanced/threshold-gated-evaluation.md index 7c2e4675..f32e2d0c 100644 --- a/docs/docs/Advanced/threshold-gated-evaluation.md +++ b/docs/docs/Advanced/threshold-gated-evaluation.md @@ -211,7 +211,7 @@ For the raw object similarity used by Hungarian matching, fields absent on both **Empty lists** -- `[] vs []` is TN. `[] vs [items]` generates one FA per item. `[items] vs []` generates one FN per item. -**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches. +**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches, and so are values up to `1e-10` under it, so a rounding error does not flip the verdict. **Different thresholds per model** -- Each `StructuredModel` subclass can define its own `match_threshold`. A `Product` with `match_threshold = 0.8` and an `Address` with `match_threshold = 0.6` are each evaluated independently. diff --git a/src/stickler/algorithms/README.md b/src/stickler/algorithms/README.md index dd4aeceb..a93b19ad 100644 --- a/src/stickler/algorithms/README.md +++ b/src/stickler/algorithms/README.md @@ -63,17 +63,18 @@ the method was returning that same pair inside `matched_pairs`. The fix reaches only this class, so it says nothing about how `anls_score` treats a low score pair; that runs through `trees/list_tree.py`. -## Two traps worth knowing before reading `tp` - -**`match_threshold=0.0` is a capture all sentinel, not a threshold.** The test -is a bare `>=`, so every score satisfies zero and `tp` counts pairs rather than -true positives. `ComparisonHelper.compare_unordered_lists` builds a matcher -this way on purpose and reads only `matched_pairs`. Nothing should read `tp` -from a matcher built with `0.0`. - -**The threshold test here is exact.** `ThresholdHelper` and `ComparisonHelper` -accept a score up to `1e-10` under the threshold, so a score inside that window -is a TP there and an FD here. +## Before reading `tp` + +**`match_threshold=0.0` is a capture all sentinel, not a threshold.** Every +score satisfies zero, so `tp` counts pairs rather than true positives. +`ComparisonHelper.compare_unordered_lists` builds a matcher this way on +purpose and reads only `matched_pairs`. Nothing should read `tp` from a +matcher built with `0.0`. + +**The threshold test is `ThresholdHelper.is_above_threshold`**, the one every +evaluator gate uses. It accepts a score up to `1e-10` under the threshold, so a +float rounding error does not turn a TP into an FD +([#417](https://github.com/awslabs/stickler/issues/417)). ## How the evaluator uses it diff --git a/src/stickler/algorithms/hungarian.py b/src/stickler/algorithms/hungarian.py index 1f68d98d..beec2919 100644 --- a/src/stickler/algorithms/hungarian.py +++ b/src/stickler/algorithms/hungarian.py @@ -289,15 +289,20 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict: other convention, so the same counts read lower here than they do as ``cm_recall`` there. - The threshold test here is a bare ``>=``. ``ThresholdHelper`` and - ``ComparisonHelper`` use a tolerant test that accepts a score up - to ``1e-10`` under the threshold, so a score inside that window is - a TP there and an FD here. + The threshold test is ``ThresholdHelper.is_above_threshold``, the + one every evaluator gate uses. It accepts a score up to ``1e-10`` + under the threshold, so ``0.7 + 0.1`` against ``0.8`` is a TP. ``match_threshold=0.0`` is used elsewhere as a capture all sentinel. Every score satisfies ``>= 0.0``, so ``tp`` then counts pairs rather than true positives and must not be read. """ + # Imported here so stickler.algorithms does not load the evaluator + # package at import time; the evaluator imports this module. + from stickler.structured_object_evaluator.models.threshold_helper import ( + ThresholdHelper, + ) + prepared_list1, prepared_list2 = self._prepare_lists(list1, list2) m, n = len(prepared_list1), len(prepared_list2) @@ -322,7 +327,11 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict: # cover max(m, n) items once each. The threshold splits the pairs into # tp and fd. It does not un-match them, which is why a paired item # never reaches fn or fa. - tp = sum(1 for _, _, score in matched_pairs if score >= self.match_threshold) + tp = sum( + 1 + for _, _, score in matched_pairs + if ThresholdHelper.is_above_threshold(score, self.match_threshold) + ) k = len(matched_pairs) fd, fn, fa = k - tp, m - k, n - k fp = fd + fa diff --git a/src/stickler/auto/facade.py b/src/stickler/auto/facade.py index 164f79de..38ac4172 100644 --- a/src/stickler/auto/facade.py +++ b/src/stickler/auto/facade.py @@ -23,6 +23,7 @@ from pydantic import BaseModel from ..structured_object_evaluator.models.structured_model import StructuredModel +from ..structured_object_evaluator.models.threshold_helper import ThresholdHelper from .builder import specs_for, structured_model_for #: Object-level match threshold applied when neither the caller nor the model @@ -76,8 +77,13 @@ def __init__( # it against `match_threshold` gives one definition that cannot disagree # with the score sitting beside it. The threshold is whatever the spec # resolved: the caller's argument, else a StructuredModel's own declared - # `match_threshold`, else DEFAULT_MATCH_THRESHOLD. See `eval_for`. - self.matched: bool = bool(self.overall_score >= spec._match_threshold) + # `match_threshold`, else DEFAULT_MATCH_THRESHOLD. See `eval_for`. The + # test is the one list pairing uses for the same threshold (#417). + self.matched: bool = bool( + ThresholdHelper.is_above_threshold( + self.overall_score, spec._match_threshold + ) + ) @property def non_matches(self) -> List[Dict[str, Any]]: diff --git a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py index b70626b4..e01721de 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_helper_base.py +++ b/src/stickler/structured_object_evaluator/models/comparison_helper_base.py @@ -6,6 +6,7 @@ from .hungarian_helper import HungarianHelper from .null_helper import NullHelper +from .threshold_helper import ThresholdHelper DEFAULT_MATCH_THRESHOLD = 0.7 @@ -117,7 +118,11 @@ def process_matched_pairs( pred_item = pred_list[pred_idx] # Determine if this is a match - is_match = bool(similarity_score >= match_threshold) + is_match = bool( + ThresholdHelper.is_above_threshold( + similarity_score, match_threshold + ) + ) # Create reason reason = self.generate_comparison_reason(is_match, similarity_score, match_threshold) diff --git a/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py b/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py index a1d0254b..2c186657 100644 --- a/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py +++ b/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py @@ -9,6 +9,7 @@ from .field_helper import FieldHelper from .metrics_helper import MetricsHelper from .null_helper import NullHelper +from .threshold_helper import ThresholdHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -95,7 +96,7 @@ def classify_field_for_confusion_matrix( pred_value = NullHelper.present(pred_value) # Use the field's configured comparator for primitive comparison similarity = comparator.compare(gt_value, pred_value) - values_match = similarity >= threshold + values_match = ThresholdHelper.is_above_threshold(similarity, threshold) else: values_match = False diff --git a/src/stickler/structured_object_evaluator/models/field_comparator.py b/src/stickler/structured_object_evaluator/models/field_comparator.py index 25502f52..f1aa39ee 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparator.py +++ b/src/stickler/structured_object_evaluator/models/field_comparator.py @@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, Any, Dict +from .threshold_helper import ThresholdHelper + if TYPE_CHECKING: from .structured_model import StructuredModel @@ -65,7 +67,7 @@ def compare_primitive_with_scores( threshold = info.threshold # For binary classification metrics, always use threshold - if raw_similarity >= threshold: + if ThresholdHelper.is_above_threshold(raw_similarity, threshold): metrics = {"tp": 1, "fa": 0, "fd": 0, "fp": 0, "tn": 0, "fn": 0} threshold_applied_score = raw_similarity else: @@ -131,7 +133,7 @@ def compare_structured_field( raw_score = gt_val.compare(pred_val) # Overall object similarity # Apply object-level binary classification based on threshold - if raw_score >= threshold: + if ThresholdHelper.is_above_threshold(raw_score, threshold): # Object matches threshold -> True Positive object_metrics = {"tp": 1, "fa": 0, "fd": 0, "fp": 0, "tn": 0, "fn": 0} threshold_applied_score = raw_score diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py index e2acfeff..56c3ab38 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_collector.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_collector.py @@ -9,6 +9,7 @@ from .field_comparison_helper import FieldComparisonHelper from .null_helper import NullHelper +from .threshold_helper import ThresholdHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -137,7 +138,9 @@ def collect_field_comparisons( # Determine if this is a match based on threshold info = self.model._get_comparison_info(field_name) - is_match = bool(raw_score >= info.threshold) + is_match = bool( + ThresholdHelper.is_above_threshold(raw_score, info.threshold) + ) # Determine reason if is_match: diff --git a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py index d0e5844a..be0c27a3 100644 --- a/src/stickler/structured_object_evaluator/models/field_comparison_helper.py +++ b/src/stickler/structured_object_evaluator/models/field_comparison_helper.py @@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional from .comparison_helper_base import ComparisonHelperBase +from .threshold_helper import ThresholdHelper class FieldComparisonHelper(ComparisonHelperBase): @@ -133,7 +134,9 @@ def _extract_entries_from_objects( # Get field configuration for threshold info = gt_object._get_comparison_info(nested_field_name) - field_is_match = field_score >= info.threshold + field_is_match = ThresholdHelper.is_above_threshold( + field_score, info.threshold + ) # Create field paths with indices expected_key = f"{field_name}[{gt_index}].{nested_field_name}" if gt_index is not None else f"{field_name}[].{nested_field_name}" diff --git a/src/stickler/structured_object_evaluator/models/metrics_helper.py b/src/stickler/structured_object_evaluator/models/metrics_helper.py index c90c631d..b7c21d42 100644 --- a/src/stickler/structured_object_evaluator/models/metrics_helper.py +++ b/src/stickler/structured_object_evaluator/models/metrics_helper.py @@ -3,6 +3,8 @@ from collections import OrderedDict from typing import Any, Dict +from .threshold_helper import ThresholdHelper + class MetricsHelper: """Helper class for calculating and aggregating confusion matrix metrics.""" @@ -142,7 +144,7 @@ def convert_score_to_binary_metrics( Dictionary with TP, FP, FN, TN counts converted to metrics """ # For single field comparison: if score >= threshold, it's TP, otherwise FP/FN - if score >= threshold: + if ThresholdHelper.is_above_threshold(score, threshold): tp = score # Proportional TP credit fp = 1 - score if score < 1.0 else 0 # Small FP for imperfect matches fn = 0 diff --git a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py index b50dd0d8..60777672 100644 --- a/src/stickler/structured_object_evaluator/models/structured_list_comparator.py +++ b/src/stickler/structured_object_evaluator/models/structured_list_comparator.py @@ -14,6 +14,7 @@ from .hungarian_helper import HungarianHelper from .metrics_helper import MetricsHelper from .null_helper import NullHelper +from .threshold_helper import ThresholdHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -133,7 +134,7 @@ def _calculate_object_level_metrics( tp_objects = 0 # Objects with similarity >= match_threshold fd_objects = 0 # Objects with similarity < match_threshold for gt_idx, pred_idx, similarity in matched_pairs: - if similarity >= match_threshold: + if ThresholdHelper.is_above_threshold(similarity, match_threshold): tp_objects += 1 else: fd_objects += 1 @@ -244,7 +245,7 @@ def _calculate_nested_field_metrics( good_matched_pairs = [ (gt_idx, pred_idx, similarity) for gt_idx, pred_idx, similarity in matched_pairs - if similarity >= match_threshold + if ThresholdHelper.is_above_threshold(similarity, match_threshold) ] if good_matched_pairs: diff --git a/tests/structured_object_evaluator/test_threshold_tolerance.py b/tests/structured_object_evaluator/test_threshold_tolerance.py new file mode 100644 index 00000000..5dffce23 --- /dev/null +++ b/tests/structured_object_evaluator/test_threshold_tolerance.py @@ -0,0 +1,308 @@ +"""One threshold test at every classification gate (#417). + +Similarity scores are floats, so a score can print as its threshold and still +sit just under it: ``0.7 + 0.1`` is ``0.7999999999999999``. A primitive list +element was classified with ``ThresholdHelper.is_above_threshold``, which +accepts a score up to ``1e-10`` under the threshold, while a field, a nested +model and a ``List[StructuredModel]`` pair were classified with a bare ``>=``. +The same score was then a TP in one place and an FD in another. + +Each gate below is checked at four scores: one float rounding error under the +threshold, exactly at it, just outside the tolerance, and clearly under it. +""" + +from typing import List + +import pytest + +import stickler +from stickler import ( + ComparableField, + ExactComparator, + LevenshteinComparator, + StructuredModel, +) +from stickler.algorithms.hungarian import HungarianMatcher +from stickler.comparators.base import BaseComparator +from stickler.structured_object_evaluator.models.metrics_helper import MetricsHelper +from stickler.structured_object_evaluator.models.threshold_helper import ( + ThresholdHelper, +) + +THRESHOLD = 0.8 + +# 0.7 + 0.1 is 0.7999999999999999 in IEEE 754 doubles, 1.1e-16 under 0.8. +NEAR = 0.7 + 0.1 + +# Just outside the 1e-10 tolerance, so still under the threshold. +OUTSIDE = THRESHOLD - 1e-9 + +# (score, whether it meets THRESHOLD) +CASES = [ + pytest.param(NEAR, True, id="float-error-under"), + pytest.param(THRESHOLD, True, id="at-threshold"), + pytest.param(OUTSIDE, False, id="outside-tolerance"), + pytest.param(0.79, False, id="clearly-under"), +] + + +class _FixedScore(BaseComparator): + """Scores equal values 1.0 and every other pair at ``score``.""" + + def __init__(self, score: float): + super().__init__() + self.score = score + + def _compare(self, str1, str2) -> float: + return 1.0 if str1 == str2 else self.score + + +def _counts(node: dict) -> tuple: + overall = node["overall"] + return overall["tp"], overall["fd"] + + +def _expected_counts(matches: bool) -> tuple: + return (1, 0) if matches else (0, 1) + + +def _full_result(gt: StructuredModel, pred: StructuredModel) -> dict: + return gt.compare_with( + pred, + include_confusion_matrix=True, + document_non_matches=True, + document_field_comparisons=True, + ) + + +def _non_match_paths(result: dict) -> list: + return [entry["field_path"] for entry in result["non_matches"]] + + +def _comparison_rows(result: dict) -> dict: + return {row["expected_key"]: row["match"] for row in result["field_comparisons"]} + + +def _flat_model(score: float): + class Flat(StructuredModel): + name: str = ComparableField(comparator=_FixedScore(score), threshold=THRESHOLD) + + return Flat + + +def _list_item_models(score: float): + """A list item whose ``name`` sub-field scores ``score``. + + ``key`` matches exactly and ``match_threshold`` is low, so the pair always + matches as an object and only the sub-field sits at the boundary. + """ + + class Item(StructuredModel): + key: str = ComparableField(comparator=ExactComparator(), threshold=1.0) + name: str = ComparableField(comparator=_FixedScore(score), threshold=THRESHOLD) + match_threshold = 0.5 + + class Holder(StructuredModel): + items: List[Item] = ComparableField() + + return Item, Holder + + +def test_the_premise(): + """Guard the inputs, so the tests below mean what they say.""" + assert NEAR < THRESHOLD + assert ThresholdHelper.is_above_threshold(NEAR, THRESHOLD) + assert not ThresholdHelper.is_above_threshold(OUTSIDE, THRESHOLD) + + +class TestFieldGate: + """A top-level primitive field, scored by ``FieldComparator``.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts(self, score, matches): + Flat = _flat_model(score) + result = _full_result(Flat(name="a"), Flat(name="b")) + assert _counts(result["confusion_matrix"]["fields"]["name"]) == ( + _expected_counts(matches) + ) + + @pytest.mark.parametrize("score,matches", CASES) + def test_only_a_miss_is_clipped(self, score, matches): + Flat = _flat_model(score) + result = _full_result(Flat(name="a"), Flat(name="b")) + assert result["field_scores"]["name"] == (score if matches else 0.0) + + @pytest.mark.parametrize("score,matches", CASES) + def test_reports_agree_with_the_counts(self, score, matches): + Flat = _flat_model(score) + result = _full_result(Flat(name="a"), Flat(name="b")) + assert _non_match_paths(result) == ([] if matches else ["name"]) + assert _comparison_rows(result) == {"name": matches} + + +class TestNestedModelGate: + """A nested ``StructuredModel`` field, classified on its object score.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts_and_score(self, score, matches): + Inner = _flat_model(score) + + class Outer(StructuredModel): + inner: Inner = ComparableField(threshold=THRESHOLD) + + gt, pred = Outer(inner=Inner(name="a")), Outer(inner=Inner(name="b")) + assert gt.inner.compare(pred.inner) == score + + result = _full_result(gt, pred) + assert _counts(result["confusion_matrix"]["fields"]["inner"]) == ( + _expected_counts(matches) + ) + assert result["field_scores"]["inner"] == (score if matches else 0.0) + + +class TestListObjectGate: + """A ``List[StructuredModel]`` pair against the element's ``match_threshold``.""" + + @staticmethod + def _models(score: float): + class Item(StructuredModel): + name: str = ComparableField(comparator=_FixedScore(score), threshold=0.5) + match_threshold = THRESHOLD + + class Holder(StructuredModel): + items: List[Item] = ComparableField() + + return Item, Holder + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts_and_recursion(self, score, matches): + Item, Holder = self._models(score) + result = _full_result( + Holder(items=[Item(name="a")]), Holder(items=[Item(name="b")]) + ) + items = result["confusion_matrix"]["fields"]["items"] + assert _counts(items) == _expected_counts(matches) + # A matched pair is descended into; a pair below the gate is not. + assert ("name" in items["fields"]) is matches + + @pytest.mark.parametrize("score,matches", CASES) + def test_reports_agree_with_the_counts(self, score, matches): + Item, Holder = self._models(score) + result = _full_result( + Holder(items=[Item(name="a")]), Holder(items=[Item(name="b")]) + ) + assert _non_match_paths(result) == ([] if matches else ["items[0]"]) + if matches: + assert _comparison_rows(result) == {"items[0].name": True} + else: + assert _comparison_rows(result) == {"items[0]": False} + + def test_the_documented_laptop_pair_is_a_true_positive(self): + """The Good Match scenario in ``threshold-gated-evaluation.md``.""" + + class Product(StructuredModel): + product_id: str = ComparableField( + comparator=ExactComparator(), threshold=1.0, weight=3.0 + ) + name: str = ComparableField( + comparator=LevenshteinComparator(), threshold=0.7, weight=2.0 + ) + price: float = ComparableField(threshold=0.9, weight=1.0) + match_threshold = 0.8 + + class Order(StructuredModel): + products: List[Product] = ComparableField(weight=3.0) + + gt = Product(product_id="PROD-001", name="Laptop", price=999.99) + pred = Product(product_id="PROD-001", name="Laptop Computer", price=999.99) + assert gt.compare(pred) == NEAR + + result = _full_result(Order(products=[gt]), Order(products=[pred])) + products = result["confusion_matrix"]["fields"]["products"] + assert _counts(products) == (1, 0) + assert _counts(products["fields"]["product_id"]) == (1, 0) + assert _counts(products["fields"]["name"]) == (0, 1) + assert _counts(products["fields"]["price"]) == (1, 0) + assert _non_match_paths(result) == ["products[0].name"] + + +class TestListSubFieldGate: + """A primitive sub-field of a matched ``List[StructuredModel]`` pair.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_counts(self, score, matches): + Item, Holder = _list_item_models(score) + result = _full_result( + Holder(items=[Item(key="k", name="a")]), + Holder(items=[Item(key="k", name="b")]), + ) + name = result["confusion_matrix"]["fields"]["items"]["fields"]["name"] + assert _counts(name) == _expected_counts(matches) + + @pytest.mark.parametrize("score,matches", CASES) + def test_reports_agree_with_the_counts(self, score, matches): + Item, Holder = _list_item_models(score) + result = _full_result( + Holder(items=[Item(key="k", name="a")]), + Holder(items=[Item(key="k", name="b")]), + ) + assert _non_match_paths(result) == ([] if matches else ["items[0].name"]) + assert _comparison_rows(result) == { + "items[0].key": True, + "items[0].name": matches, + } + + @pytest.mark.parametrize("score,matches", CASES) + def test_agrees_with_a_field_and_a_list_element(self, score, matches): + """The same score and threshold give one verdict wherever they meet.""" + Item, Holder = _list_item_models(score) + sub_field = _full_result( + Holder(items=[Item(key="k", name="a")]), + Holder(items=[Item(key="k", name="b")]), + )["confusion_matrix"]["fields"]["items"]["fields"]["name"] + + Flat = _flat_model(score) + field = _full_result(Flat(name="a"), Flat(name="b"))["confusion_matrix"][ + "fields" + ]["name"] + + class Names(StructuredModel): + names: List[str] = ComparableField( + comparator=_FixedScore(score), threshold=THRESHOLD + ) + + element = _full_result(Names(names=["a"]), Names(names=["b"]))[ + "confusion_matrix" + ]["fields"]["names"] + + expected = _expected_counts(matches) + assert _counts(sub_field) == _counts(field) == _counts(element) == expected + + +class TestObjectVerdict: + """``EvalResult.matched`` reads the same ``match_threshold`` as list pairing.""" + + @pytest.mark.parametrize("score,matches", CASES) + def test_matched(self, score, matches): + class Flat(StructuredModel): + name: str = ComparableField(comparator=_FixedScore(score), threshold=0.5) + + result = stickler.evaluate( + Flat(name="a"), Flat(name="b"), match_threshold=THRESHOLD + ) + assert result.overall_score == score + assert result.matched is matches + + +class TestStandaloneGates: + @pytest.mark.parametrize("score,matches", CASES) + def test_hungarian_matcher_counts(self, score, matches): + matcher = HungarianMatcher(_FixedScore(score), match_threshold=THRESHOLD) + metrics = matcher.calculate_metrics(["a"], ["b"]) + assert (metrics["tp"], metrics["fd"]) == _expected_counts(matches) + + @pytest.mark.parametrize("score,matches", CASES) + def test_binary_metrics(self, score, matches): + """The fallback ``evaluator_format=True`` uses without a confusion matrix.""" + metrics = MetricsHelper().convert_score_to_binary_metrics(score, THRESHOLD) + assert metrics["recall"] == (1.0 if matches else 0.0) From bd338aa3393f6fdb692d9a76f2a2a863d063aa06 Mon Sep 17 00:00:00 2001 From: Yashvardhan Thanvi Date: Tue, 20 Oct 2026 00:46:17 +0530 Subject: [PATCH 2/3] fix(417): use the tolerant test in binary_compare and the field configs BaseComparator.binary_compare, ComparisonInfo.compare and ComparableFieldConfig.compare still used a bare comparison, so 0.7 + 0.1 against 0.8 was (0, 1) from binary_compare and was clipped to 0.0 by the field configs. They now go through ThresholdHelper, as does the unused StructuredModel._calculate_object_level_metrics. binary_compare imports the helper inside the method, like HungarianMatcher.calculate_metrics. Add a Meeting a Threshold section to thresholds-and-metrics.md and link it from each page that states the >= rule. Correct the Good Match Laptop scenario, where name scores 0.4 and is an FD inside a TP pair, and the algorithms README note on unordered_list_metrics. The CHANGELOG entry names the new gates and the two thresholds that keep an exact comparison. --- CHANGELOG.md | 30 +++++++++++-------- docs/docs/API-Reference/auto.md | 2 +- docs/docs/Advanced/classification-logic.md | 6 ++-- docs/docs/Advanced/hungarian-matching.md | 4 +-- .../Advanced/threshold-gated-evaluation.md | 19 +++++++----- .../Contributing/architecture.md | 6 ++-- .../Getting-Started/thresholds-and-metrics.md | 6 +++- docs/docs/Guides/Evaluation/README.md | 2 +- .../Evaluation/understanding-results.md | 2 +- src/stickler/algorithms/README.md | 6 ++-- src/stickler/comparators/base.py | 17 ++++++++--- .../models/comparison_info.py | 12 ++++++-- .../models/confidence/README.md | 2 +- .../models/structured_model.py | 4 +-- .../test_threshold_tolerance.py | 21 +++++++++++-- 15 files changed, 91 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b058351..102ae19c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,26 +86,30 @@ Each release links to full notes on the [`None` elements in a list](https://awslabs.github.io/stickler/Advanced/classification-logic/#none-elements-in-a-list) - **Breaking:** a score that floating-point arithmetic leaves just under its - threshold now gets the same verdict at every gate. A primitive list element - allowed a `1e-10` tolerance, but a field, a nested model, a - `List[StructuredModel]` pair and `EvalResult.matched` used a bare `>=`. The - Laptop pair in the threshold-gating docs scores `0.7999999999999999` against - `match_threshold = 0.8`, so it was an FD and was not descended into, while the - same score on a `List[str]` element was a TP. Every gate now uses - `ThresholdHelper.is_above_threshold`. A score up to `1e-10` under its - threshold: + threshold now gets the same verdict at every classification gate. A + primitive list element allowed a `1e-10` tolerance, but a field, a nested + model, a `List[StructuredModel]` pair, `EvalResult.matched` and + `binary_compare()` used a bare `>=`. The Laptop pair in the threshold-gating + docs scores `0.7999999999999999` against `match_threshold = 0.8`, so it was an + FD and was not descended into, while the same score on a `List[str]` element + was a TP. Each of these now uses `ThresholdHelper.is_above_threshold`. A score + up to `1e-10` under its threshold: - counts as a TP instead of an FD, in the confusion matrix, `non_matches` and `field_comparisons`, for a field, a nested model, a list item's sub-field and a list pair; - keeps its score instead of being clipped to `0.0`, so `field_scores` and - `overall_score` can rise; + `overall_score` can rise, and `ComparisonInfo.compare()` and + `ComparableFieldConfig.compare()` return it; - opens a list pair for field-by-field evaluation; - - sets `EvalResult.matched`, and counts as a TP in - `HungarianMatcher.calculate_metrics` and the `evaluator_format=True` - fallback metrics. + - sets `EvalResult.matched`, makes `BaseComparator.binary_compare()` return + `(1, 0)`, and counts as a TP in `HungarianMatcher.calculate_metrics` and the + `evaluator_format=True` fallback metrics. A score further under the threshold is unchanged, and so is a primitive list - element ([#417](https://github.com/awslabs/stickler/issues/417)) + element. `ANLSStarComparator`'s `leaf_threshold` and the bounding-box + `iou_thresholds` are separate metrics and keep their exact comparison + ([#417](https://github.com/awslabs/stickler/issues/417)). See + [Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold) ### Fixed diff --git a/docs/docs/API-Reference/auto.md b/docs/docs/API-Reference/auto.md index 5645647d..ec8f5530 100644 --- a/docs/docs/API-Reference/auto.md +++ b/docs/docs/API-Reference/auto.md @@ -49,7 +49,7 @@ above: | `recall` | `float` | `cm_recall` | | `f1` | `float` | `cm_f1` | | `accuracy` | `float` | `cm_accuracy` | -| `matched` | `bool` | `overall_score >= match_threshold`. A convenience roll-up, not a per-field guarantee: individual fields can be below their thresholds while `matched` is `True`. Read `field_scores` or the confusion matrix for that. | +| `matched` | `bool` | `overall_score >= match_threshold` (see [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)). A convenience roll-up, not a per-field guarantee: individual fields can be below their thresholds while `matched` is `True`. Read `field_scores` or the confusion matrix for that. | | `confusion_matrix` | `dict` | The full confusion-matrix subtree | | `raw` | `dict` | The unmodified `compare_with()` result | diff --git a/docs/docs/Advanced/classification-logic.md b/docs/docs/Advanced/classification-logic.md index 9c20c407..81df4a69 100644 --- a/docs/docs/Advanced/classification-logic.md +++ b/docs/docs/Advanced/classification-logic.md @@ -39,7 +39,7 @@ False Alarm (FA) and False Discovery (FD) together make up the broader False Pos Lists use the [Hungarian algorithm](hungarian-matching.md) for optimal element pairing. 1. **Empty lists**: `[] vs []` is TN; `[] vs [items]` produces one FA per item; `[items] vs []` produces one FN per item. -2. **Matched elements**: similarity >= threshold is TP; below threshold is FD. +2. **Matched elements**: similarity >= threshold is TP; below threshold is FD. See [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). 3. **Unmatched elements**: leftover GT elements are FN; leftover EST elements are FA. 4. **`None` elements**: absent, so they are not matched or counted. A list of only `None` is an empty list. See [`None` elements in a list](#none-elements-in-a-list). @@ -97,7 +97,7 @@ Result: TP=0, FA=0, FN=0, FD=3 ### Nested Objects -Nested objects are evaluated recursively, field by field. +Nested objects are evaluated recursively, field by field, with `>=` as described in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). | Condition | Classification | |-----------|---------------| @@ -194,7 +194,7 @@ These are computed at every node of the result tree, from that node's own counts **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`. -**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP). So does a score up to `1e-10` under it, at every gate, so a rounding error such as `0.7 + 0.1` (`0.7999999999999999`) against `0.8` does not turn a TP into an FD. +**Threshold boundary** -- A similarity score exactly equal to the threshold counts as a match (TP). So does a score less than `1e-10` under it, at every gate listed in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold), so a rounding error such as `0.7 + 0.1` (`0.7999999999999999`) against `0.8` does not turn a TP into an FD. **List order** -- Order does not matter. The Hungarian algorithm finds the optimal pairing regardless of element position. diff --git a/docs/docs/Advanced/hungarian-matching.md b/docs/docs/Advanced/hungarian-matching.md index 0ee42eb7..61116ef0 100644 --- a/docs/docs/Advanced/hungarian-matching.md +++ b/docs/docs/Advanced/hungarian-matching.md @@ -26,7 +26,7 @@ The Hungarian algorithm solves the assignment problem in O(n^3) time, producing ### 3. Threshold-Gated Classification -Each matched pair is classified using `StructuredModel.match_threshold`: +Each matched pair is classified using `StructuredModel.match_threshold`, with `>=` as described in [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold): | Condition | Classification | Nested analysis? | |-----------|---------------|-----------------| @@ -195,7 +195,7 @@ The threshold for Hungarian classification comes from the element model's `match ### Recursion Gating ``` -IF object_similarity >= match_threshold: +IF object_similarity meets match_threshold: classification = TP recurse into nested field analysis ELSE: diff --git a/docs/docs/Advanced/threshold-gated-evaluation.md b/docs/docs/Advanced/threshold-gated-evaluation.md index f32e2d0c..4d63d874 100644 --- a/docs/docs/Advanced/threshold-gated-evaluation.md +++ b/docs/docs/Advanced/threshold-gated-evaluation.md @@ -95,10 +95,11 @@ Given three GT products and three Pred products: **GT:** `Product("PROD-001", "Laptop", 999.99)` **Pred:** `Product("PROD-001", "Laptop Computer", 999.99)` +- Similarity: `(3 * 1.0 + 2 * 0.4 + 1 * 1.0) / 6`, which floating point evaluates to `0.7999999999999999`. It meets `0.8` through the [rounding tolerance](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). - Classification: **TP** - Nested field analysis is performed: - `product_id`: TP (exact match) - - `name`: TP (similarity ~0.9) + - `name`: FD (Levenshtein similarity 0.4, under its 0.7 threshold) - `price`: TP (exact match) ### Poor Match (similarity < 0.8) @@ -127,10 +128,11 @@ No nested analysis for either. }, "fields": { "product_id": { "tp": 1 }, - "name": { "tp": 1 }, + "name": { "fd": 1 }, "price": { "tp": 1 } }, "non_matches": [ + { "type": "FD", "field_path": "products[0].name", "similarity": 0.4 }, { "type": "FD", "gt_object": "Product(PROD-002, Mouse, 29.99)", @@ -144,10 +146,10 @@ No nested analysis for either. } ``` -Field-level metrics appear only for the single TP pair. The `non_matches` list -documents each FD, FN, and FA once at object level; `field_comparisons` uses the -same boundary. Neither report expands a rejected or unmatched object into -leaves. +Field-level metrics appear only for the single TP pair, and its `name` is the +only leaf in `non_matches`. That list documents every other FD, FN, and FA once +at object level; `field_comparisons` uses the same boundary. Neither report +expands a rejected or unmatched object into leaves. ## Delegation Pattern @@ -203,7 +205,8 @@ field's own `threshold` decides that verdict. See `overall_score` is the scalar summary, and `EvalResult.matched` from `stickler.evaluate()` is the object-level verdict -(`overall_score >= match_threshold`). +(`overall_score >= match_threshold`, see +[Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)). For the raw object similarity used by Hungarian matching, fields absent on both sides are omitted from both totals. They remain TNs in the confusion matrix, but do not help a pair clear `match_threshold`. If no fields remain, the similarity is defined as `1.0`, because nothing disagreed. @@ -211,7 +214,7 @@ For the raw object similarity used by Hungarian matching, fields absent on both **Empty lists** -- `[] vs []` is TN. `[] vs [items]` generates one FA per item. `[items] vs []` generates one FN per item. -**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches, and so are values up to `1e-10` under it, so a rounding error does not flip the verdict. +**Threshold boundary** -- `similarity >= threshold` counts as TP and triggers recursion. Values exactly at the boundary are matches, and so are values less than `1e-10` under it, so a rounding error does not flip the verdict. See [Meeting a Threshold](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). **Different thresholds per model** -- Each `StructuredModel` subclass can define its own `match_threshold`. A `Product` with `match_threshold = 0.8` and an `Address` with `match_threshold = 0.6` are each evaluated independently. diff --git a/docs/docs/Getting-Started/Contributing/architecture.md b/docs/docs/Getting-Started/Contributing/architecture.md index 29227e9a..de9336f7 100644 --- a/docs/docs/Getting-Started/Contributing/architecture.md +++ b/docs/docs/Getting-Started/Contributing/architecture.md @@ -211,14 +211,14 @@ The source header documents preserved behavioral bugs: #### Threshold-Gated Recursion Internals -Field-level detail is only generated for object pairs with `similarity >= match_threshold`. Poor matches are treated as atomic failures without recursive field analysis. This is both a correctness decision (poor matches don't have meaningful field-level breakdowns) and a performance optimization. +Field-level detail is only generated for object pairs with `similarity >= match_threshold` (see [Meeting a Threshold](../thresholds-and-metrics.md#meeting-a-threshold)). Poor matches are treated as atomic failures without recursive field analysis. This is both a correctness decision (poor matches don't have meaningful field-level breakdowns) and a performance optimization. ```python -# See: structured_list_comparator.py:243-249 +# See: structured_list_comparator.py:245-249 good_matched_pairs = [ (gt_idx, pred_idx, similarity) for gt_idx, pred_idx, similarity in matched_pairs - if similarity >= match_threshold + if ThresholdHelper.is_above_threshold(similarity, match_threshold) ] ``` diff --git a/docs/docs/Getting-Started/thresholds-and-metrics.md b/docs/docs/Getting-Started/thresholds-and-metrics.md index 985ff168..7e144e39 100644 --- a/docs/docs/Getting-Started/thresholds-and-metrics.md +++ b/docs/docs/Getting-Started/thresholds-and-metrics.md @@ -38,7 +38,7 @@ class Invoice(StructuredModel): **What it gates:** -- **TP vs FD classification:** If `similarity >= threshold`, the field is a True Positive. Otherwise, it's a False Discovery. +- **TP vs FD classification:** If `similarity >= threshold` (see [Meeting a Threshold](#meeting-a-threshold)), the field is a True Positive. Otherwise, it's a False Discovery. - **Score clipping:** When `clip_under_threshold=True` (the default), scores below the threshold are zeroed out in the weighted average. **Default:** `0.5` @@ -129,6 +129,10 @@ Field threshold → threshold named on the comparator → `0.5`. A comparator's *default* threshold is not part of that chain. `LevenshteinComparator()` does not contribute its 0.7, because those defaults were chosen for `binary_compare()` and were never audited as classification cutoffs. `DateComparator` is the clearest case: it defaults to `1.0` while awarding `0.7` partial credit for a match with no year, so adopting its default would clip its own feature to zero. +## Meeting a Threshold + +A score meets its threshold when it is at or above it, or less than `1e-10` under it. The allowance absorbs floating-point rounding: `0.7 + 0.1` is `0.7999999999999999`, which meets `0.8`, while `0.8 - 1e-9` does not. Field, list element and list pair classification, score clipping, recursion into a list pair, `EvalResult.matched` and `binary_compare()` all use this one test, `ThresholdHelper.is_above_threshold`, so wherever these docs write `similarity >= threshold` they mean it. `ANLSStarComparator`'s `leaf_threshold` and the bounding-box `iou_thresholds` are separate metrics and keep their exact comparison. + --- ## Metrics Glossary diff --git a/docs/docs/Guides/Evaluation/README.md b/docs/docs/Guides/Evaluation/README.md index 583a479e..a4738a2e 100644 --- a/docs/docs/Guides/Evaluation/README.md +++ b/docs/docs/Guides/Evaluation/README.md @@ -64,7 +64,7 @@ When defining a `StructuredModel` subclass in Python, each field is declared wit See the [Comparators](../Comparators/README.md) section for the complete list and detailed descriptions. -**`threshold`** -- Acts as a binary classification cutoff. A similarity score at or above the threshold counts as a True Positive; below it counts as a False Discovery. Choose stricter thresholds (0.9--1.0) for critical fields and looser thresholds (0.5--0.7) for flexible fields. +**`threshold`** -- Acts as a binary classification cutoff. A similarity score at or above the threshold counts as a True Positive; below it counts as a False Discovery. See [Meeting a Threshold](../../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold). Choose stricter thresholds (0.9--1.0) for critical fields and looser thresholds (0.5--0.7) for flexible fields. **`weight`** -- Controls how much a field contributes to the overall score. The overall score is computed as: diff --git a/docs/docs/Guides/Evaluation/understanding-results.md b/docs/docs/Guides/Evaluation/understanding-results.md index 1969e535..a3d89bc9 100644 --- a/docs/docs/Guides/Evaluation/understanding-results.md +++ b/docs/docs/Guides/Evaluation/understanding-results.md @@ -46,7 +46,7 @@ Maps each field name to its similarity score (0.0 to 1.0). For nested objects, t ### Asking whether anything failed -`overall_score` is the scalar summary, and for a single object-level verdict `stickler.evaluate()` returns an `EvalResult` whose `matched` attribute is `overall_score >= match_threshold`. +`overall_score` is the scalar summary, and for a single object-level verdict `stickler.evaluate()` returns an `EvalResult` whose `matched` attribute is `overall_score >= match_threshold` (see [Meeting a Threshold](../../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold)). To ask whether anything at all went wrong, read **both** rollup nodes, because they scope different things: diff --git a/src/stickler/algorithms/README.md b/src/stickler/algorithms/README.md index a93b19ad..8dd906ee 100644 --- a/src/stickler/algorithms/README.md +++ b/src/stickler/algorithms/README.md @@ -86,9 +86,9 @@ themselves: | `HungarianHelper.get_complete_matching_info` | derives the matched and unmatched index sets for object matching over `List[StructuredModel]` | | `ComparisonHelper.compare_unordered_lists` | hands them to `unordered_list_metrics`, which counts against its own `classification_threshold` | -`unordered_list_metrics` uses the same derivation as `calculate_metrics`, so the -two agree on what a count means. The remaining difference is the tolerant -threshold test noted above. +`unordered_list_metrics` uses the same derivation and the same threshold test as +`calculate_metrics`, so for the same pairs and threshold the two return the same +counts. Because neither caller reads the counts, a change to how `calculate_metrics` classifies cannot move an evaluator score. It is a public API in its own right diff --git a/src/stickler/comparators/base.py b/src/stickler/comparators/base.py index 69cfd481..a800180a 100644 --- a/src/stickler/comparators/base.py +++ b/src/stickler/comparators/base.py @@ -238,9 +238,11 @@ def binary_compare(self, str1: Any, str2: Any) -> Tuple[int, int]: """Compare two values and return a binary result as (tp, fp) tuple. This method converts the continuous similarity score to a binary decision - based on the threshold. If the similarity is greater than or equal to the - threshold, it returns (1, 0) indicating true positive. Otherwise, it returns - (0, 1) indicating false positive. + based on the threshold. If the similarity meets the threshold, it returns + (1, 0) indicating true positive. Otherwise, it returns (0, 1) indicating + false positive. The test is ``ThresholdHelper.is_above_threshold``, the + one every evaluator gate uses, so a score less than ``1e-10`` under the + threshold meets it. Args: str1: First value @@ -250,8 +252,15 @@ def binary_compare(self, str1: Any, str2: Any) -> Tuple[int, int]: Tuple of (tp, fp) where tp is 1 if similar, 0 otherwise, and fp is the opposite """ + # Imported here, as in HungarianMatcher.calculate_metrics, so this + # module has no import-time dependency on the evaluator package, which + # imports it. + from stickler.structured_object_evaluator.models.threshold_helper import ( + ThresholdHelper, + ) + score = self.compare(str1, str2) - if score >= self.threshold: + if ThresholdHelper.is_above_threshold(score, self.threshold): return (1, 0) # True positive else: return (0, 1) # False positive diff --git a/src/stickler/structured_object_evaluator/models/comparison_info.py b/src/stickler/structured_object_evaluator/models/comparison_info.py index 16935582..bd5f653d 100644 --- a/src/stickler/structured_object_evaluator/models/comparison_info.py +++ b/src/stickler/structured_object_evaluator/models/comparison_info.py @@ -7,6 +7,8 @@ from stickler.comparators.base import BaseComparator from stickler.comparators.levenshtein import LevenshteinComparator +from .threshold_helper import ThresholdHelper + class ComparisonInfo: """Container for comparison configuration. @@ -56,7 +58,11 @@ def compare(self, value1: Any, value2: Any) -> float: similarity = self.comparator.compare(value1, value2) # Apply threshold (if below threshold, return 0) - return 0.0 if similarity < self.threshold else similarity + return ( + 0.0 + if ThresholdHelper.is_below_threshold(similarity, self.threshold) + else similarity + ) def __repr__(self) -> str: """Return string representation.""" @@ -130,7 +136,9 @@ def compare(self, value1: Any, value2: Any) -> float: similarity = self.comparator.compare(value1, value2) # Apply threshold if clip_under_threshold is enabled - if self.clip_under_threshold and similarity < self.threshold: + if self.clip_under_threshold and ThresholdHelper.is_below_threshold( + similarity, self.threshold + ): return 0.0 return similarity diff --git a/src/stickler/structured_object_evaluator/models/confidence/README.md b/src/stickler/structured_object_evaluator/models/confidence/README.md index 08c3f1b0..f44811d0 100644 --- a/src/stickler/structured_object_evaluator/models/confidence/README.md +++ b/src/stickler/structured_object_evaluator/models/confidence/README.md @@ -25,7 +25,7 @@ class ConfidencePair(BaseModel): similarity: float # Raw comparator similarity score (0.0–1.0) ``` -`is_match` is threshold-gated: `raw_score >= ComparableField.threshold`. This means a field with similarity 0.65 and threshold 0.7 is `is_match=False`, even though it's partially correct. The `similarity` field preserves the continuous score for future metrics that want to correlate confidence with degree of correctness rather than binary match. +`is_match` is threshold-gated: `raw_score >= ComparableField.threshold`, with the rounding tolerance described in [Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold). This means a field with similarity 0.65 and threshold 0.7 is `is_match=False`, even though it's partially correct. The `similarity` field preserves the continuous score for future metrics that want to correlate confidence with degree of correctness rather than binary match. ## Adding a New Metric diff --git a/src/stickler/structured_object_evaluator/models/structured_model.py b/src/stickler/structured_object_evaluator/models/structured_model.py index efdf5349..8645ab30 100644 --- a/src/stickler/structured_object_evaluator/models/structured_model.py +++ b/src/stickler/structured_object_evaluator/models/structured_model.py @@ -33,7 +33,7 @@ from .null_helper import NullHelper from .optional_annotation import union_args, unwrap_annotated, unwrap_optional from .rich_value_helper import RichValueHelper -from .threshold_helper import THRESHOLD_DOCS_URL +from .threshold_helper import THRESHOLD_DOCS_URL, ThresholdHelper from .threshold_helper import model_identity as _model_identity from .threshold_helper import warn_if_threshold_is_zero as _warn_if_threshold_is_zero @@ -1306,7 +1306,7 @@ def _calculate_object_level_metrics( tp_objects = 0 # Objects with similarity >= match_threshold fd_objects = 0 # Objects with similarity < match_threshold for gt_idx, pred_idx, similarity in matched_pairs: - if similarity >= match_threshold: + if ThresholdHelper.is_above_threshold(similarity, match_threshold): tp_objects += 1 else: fd_objects += 1 diff --git a/tests/structured_object_evaluator/test_threshold_tolerance.py b/tests/structured_object_evaluator/test_threshold_tolerance.py index 5dffce23..810f8e0b 100644 --- a/tests/structured_object_evaluator/test_threshold_tolerance.py +++ b/tests/structured_object_evaluator/test_threshold_tolerance.py @@ -11,7 +11,7 @@ threshold, exactly at it, just outside the tolerance, and clearly under it. """ -from typing import List +from typing import List, Optional import pytest @@ -24,6 +24,10 @@ ) from stickler.algorithms.hungarian import HungarianMatcher from stickler.comparators.base import BaseComparator +from stickler.structured_object_evaluator.models.comparison_info import ( + ComparableFieldConfig, + ComparisonInfo, +) from stickler.structured_object_evaluator.models.metrics_helper import MetricsHelper from stickler.structured_object_evaluator.models.threshold_helper import ( ThresholdHelper, @@ -49,8 +53,8 @@ class _FixedScore(BaseComparator): """Scores equal values 1.0 and every other pair at ``score``.""" - def __init__(self, score: float): - super().__init__() + def __init__(self, score: float, threshold: Optional[float] = None): + super().__init__(threshold=threshold) self.score = score def _compare(self, str1, str2) -> float: @@ -306,3 +310,14 @@ def test_binary_metrics(self, score, matches): """The fallback ``evaluator_format=True`` uses without a confusion matrix.""" metrics = MetricsHelper().convert_score_to_binary_metrics(score, THRESHOLD) assert metrics["recall"] == (1.0 if matches else 0.0) + + @pytest.mark.parametrize("score,matches", CASES) + def test_comparator_and_field_config(self, score, matches): + """``binary_compare`` and the field configs' clipping ``compare``.""" + comparator = _FixedScore(score, threshold=THRESHOLD) + assert comparator.binary_compare("a", "b") == ((1, 0) if matches else (0, 1)) + + kept = score if matches else 0.0 + for config_cls in (ComparisonInfo, ComparableFieldConfig): + config = config_cls(_FixedScore(score), threshold=THRESHOLD) + assert config.compare("a", "b") == kept From 0d971cab6739174a8de6581808872c50636339bd Mon Sep 17 00:00:00 2001 From: Yashvardhan Thanvi Date: Wed, 21 Oct 2026 00:30:56 +0530 Subject: [PATCH 3/3] docs(417): regenerate the threshold gating example from a real run The Result Structure block and the Unmatched Items scenario in threshold-gated-evaluation.md did not match what the page's own example produces. With three products on each side, Hungarian matching pairs Cable with New Product as an FD at 0.133, so there is no FN or FA, and the Mouse pair scores 0.6725. Show the example inputs, replace the block with the real counts and non_matches, retitle the heading over the 0.7999999999999999 pair, and say when an item is left unmatched. The Laptop test now runs the whole example, plus the FN and FA cases. Scope the docstrings in hungarian.py, base.py and the algorithms README to the gates listed in Meeting a Threshold, and use ThresholdHelper.is_below_threshold for the explain() verdict. --- .../Advanced/threshold-gated-evaluation.md | 73 ++++++++++++------- src/stickler/algorithms/README.md | 6 +- src/stickler/algorithms/hungarian.py | 5 +- src/stickler/auto/facade.py | 2 +- src/stickler/comparators/base.py | 4 +- .../test_threshold_tolerance.py | 55 ++++++++++++-- 6 files changed, 103 insertions(+), 42 deletions(-) diff --git a/docs/docs/Advanced/threshold-gated-evaluation.md b/docs/docs/Advanced/threshold-gated-evaluation.md index 4d63d874..a55f4c71 100644 --- a/docs/docs/Advanced/threshold-gated-evaluation.md +++ b/docs/docs/Advanced/threshold-gated-evaluation.md @@ -90,7 +90,21 @@ class Order(StructuredModel): Given three GT products and three Pred products: -### Good Match (similarity >= 0.8) +```python +gt = Order(order_id="ORD-1", products=[ + Product(product_id="PROD-001", name="Laptop", price=999.99), + Product(product_id="PROD-002", name="Mouse", price=29.99), + Product(product_id="PROD-003", name="Cable", price=14.99), +]) +pred = Order(order_id="ORD-1", products=[ + Product(product_id="PROD-001", name="Laptop Computer", price=999.99), + Product(product_id="PROD-002", name="Different Product", price=99.99), + Product(product_id="PROD-004", name="New Product", price=19.99), +]) +result = gt.compare_with(pred, include_confusion_matrix=True, document_non_matches=True) +``` + +### Good Match (meets 0.8) **GT:** `Product("PROD-001", "Laptop", 999.99)` **Pred:** `Product("PROD-001", "Laptop Computer", 999.99)` @@ -107,49 +121,54 @@ Given three GT products and three Pred products: **GT:** `Product("PROD-002", "Mouse", 29.99)` **Pred:** `Product("PROD-002", "Different Product", 99.99)` +- Similarity: `(3 * 1.0 + 2 * 0.118 + 1 * 0.8) / 6`, about `0.6725` - Classification: **FD** - No nested field analysis -- the objects are too dissimilar for field-level breakdown to be useful. -### Unmatched Items +### Weak Pairing -**GT:** `Product("PROD-003", "Cable", 14.99)` -- **FN** (no counterpart in Pred) -**Pred:** `Product("PROD-004", "New Product", 19.99)` -- **FA** (no counterpart in GT) +**GT:** `Product("PROD-003", "Cable", 14.99)` +**Pred:** `Product("PROD-004", "New Product", 19.99)` -No nested analysis for either. +- Similarity: `0.1333` +- Classification: **FD**, with no nested analysis + +Hungarian matching pairs every item when both lists have the same length, so +these two are paired even though they share almost nothing. An item is left +unmatched only when one list is longer: without `New Product` in Pred, `Cable` +would be an **FN**, and without `Cable` in GT, `New Product` would be an **FA**. +Neither is broken down into fields. ## Result Structure +The `products` counts and the `non_matches` from the run above, with other keys +left out and scores rounded to four places: + ```json { - "products": { + "confusion_matrix": { "fields": { "products": { "overall": { - "tp": 1, "fd": 1, "fn": 1, "fa": 1, - "derived": { "cm_precision": 0.5, "cm_recall": 0.5, "cm_f1": 0.5 } + "tp": 1, "fd": 2, "fn": 0, "fa": 0, + "derived": { "cm_precision": 0.3333, "cm_recall": 1.0, "cm_f1": 0.5 } }, "fields": { - "product_id": { "tp": 1 }, - "name": { "fd": 1 }, - "price": { "tp": 1 } - }, - "non_matches": [ - { "type": "FD", "field_path": "products[0].name", "similarity": 0.4 }, - { - "type": "FD", - "gt_object": "Product(PROD-002, Mouse, 29.99)", - "pred_object": "Product(PROD-002, Different Product, 99.99)", - "similarity": 0.3 - }, - { "type": "FN", "gt_object": "Product(PROD-003, Cable, 14.99)" }, - { "type": "FA", "pred_object": "Product(PROD-004, New Product, 19.99)" } - ] - } + "product_id": { "overall": { "tp": 1 } }, + "name": { "overall": { "fd": 1 } }, + "price": { "overall": { "tp": 1 } } + } + } } }, + "non_matches": [ + { "field_path": "products[0].name", "non_match_type": "false_discovery", "similarity_score": 0.4 }, + { "field_path": "products[1]", "non_match_type": "false_discovery", "similarity_score": 0.6725 }, + { "field_path": "products[2]", "non_match_type": "false_discovery", "similarity_score": 0.1333 } + ] } ``` Field-level metrics appear only for the single TP pair, and its `name` is the -only leaf in `non_matches`. That list documents every other FD, FN, and FA once -at object level; `field_comparisons` uses the same boundary. Neither report -expands a rejected or unmatched object into leaves. +only leaf in `non_matches`. That list documents each rejected pair once at +object level, as it would an FN or FA; `field_comparisons` uses the same +boundary. Neither report expands a rejected or unmatched object into leaves. ## Delegation Pattern diff --git a/src/stickler/algorithms/README.md b/src/stickler/algorithms/README.md index 9c2fa8cd..dfeef16b 100644 --- a/src/stickler/algorithms/README.md +++ b/src/stickler/algorithms/README.md @@ -72,8 +72,10 @@ purpose and reads only `matched_pairs`. Nothing should read `tp` from a matcher built with `0.0`. **The threshold test is `ThresholdHelper.is_above_threshold`**, the one every -evaluator gate uses. It accepts a score up to `1e-10` under the threshold, so a -float rounding error does not turn a TP into an FD +classification gate listed in +[Meeting a Threshold](https://awslabs.github.io/stickler/Getting-Started/thresholds-and-metrics/#meeting-a-threshold) +uses. It accepts a score up to `1e-10` under the threshold, so a float rounding +error does not turn a TP into an FD ([#417](https://github.com/awslabs/stickler/issues/417)). ## How the evaluator uses it diff --git a/src/stickler/algorithms/hungarian.py b/src/stickler/algorithms/hungarian.py index beec2919..fa4f3d97 100644 --- a/src/stickler/algorithms/hungarian.py +++ b/src/stickler/algorithms/hungarian.py @@ -290,8 +290,9 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict: as ``cm_recall`` there. The threshold test is ``ThresholdHelper.is_above_threshold``, the - one every evaluator gate uses. It accepts a score up to ``1e-10`` - under the threshold, so ``0.7 + 0.1`` against ``0.8`` is a TP. + one every classification gate listed in Meeting a Threshold uses. + It accepts a score up to ``1e-10`` under the threshold, so + ``0.7 + 0.1`` against ``0.8`` is a TP. ``match_threshold=0.0`` is used elsewhere as a capture all sentinel. Every score satisfies ``>= 0.0``, so ``tp`` then counts diff --git a/src/stickler/auto/facade.py b/src/stickler/auto/facade.py index 38ac4172..beaaf3ac 100644 --- a/src/stickler/auto/facade.py +++ b/src/stickler/auto/facade.py @@ -141,7 +141,7 @@ def explain(self) -> Dict[str, Dict[str, Any]]: score == 0.0 and raw_sim and threshold is not None - and raw_sim < threshold + and ThresholdHelper.is_below_threshold(raw_sim, threshold) ): entry["verdict"] = ( f"raw {raw_sim:.2f} < threshold {threshold} -> clipped to 0.0" diff --git a/src/stickler/comparators/base.py b/src/stickler/comparators/base.py index a800180a..9d319575 100644 --- a/src/stickler/comparators/base.py +++ b/src/stickler/comparators/base.py @@ -241,8 +241,8 @@ def binary_compare(self, str1: Any, str2: Any) -> Tuple[int, int]: based on the threshold. If the similarity meets the threshold, it returns (1, 0) indicating true positive. Otherwise, it returns (0, 1) indicating false positive. The test is ``ThresholdHelper.is_above_threshold``, the - one every evaluator gate uses, so a score less than ``1e-10`` under the - threshold meets it. + one every classification gate listed in Meeting a Threshold uses, so a + score less than ``1e-10`` under the threshold meets it. Args: str1: First value diff --git a/tests/structured_object_evaluator/test_threshold_tolerance.py b/tests/structured_object_evaluator/test_threshold_tolerance.py index 810f8e0b..7dee3ccb 100644 --- a/tests/structured_object_evaluator/test_threshold_tolerance.py +++ b/tests/structured_object_evaluator/test_threshold_tolerance.py @@ -201,8 +201,8 @@ def test_reports_agree_with_the_counts(self, score, matches): else: assert _comparison_rows(result) == {"items[0]": False} - def test_the_documented_laptop_pair_is_a_true_positive(self): - """The Good Match scenario in ``threshold-gated-evaluation.md``.""" + def test_the_documented_worked_example(self): + """The scenarios and result block in ``threshold-gated-evaluation.md``.""" class Product(StructuredModel): product_id: str = ComparableField( @@ -215,19 +215,58 @@ class Product(StructuredModel): match_threshold = 0.8 class Order(StructuredModel): + order_id: str = ComparableField( + comparator=ExactComparator(), threshold=1.0, weight=2.0 + ) products: List[Product] = ComparableField(weight=3.0) - gt = Product(product_id="PROD-001", name="Laptop", price=999.99) - pred = Product(product_id="PROD-001", name="Laptop Computer", price=999.99) - assert gt.compare(pred) == NEAR + gt = [ + Product(product_id="PROD-001", name="Laptop", price=999.99), + Product(product_id="PROD-002", name="Mouse", price=29.99), + Product(product_id="PROD-003", name="Cable", price=14.99), + ] + pred = [ + Product(product_id="PROD-001", name="Laptop Computer", price=999.99), + Product(product_id="PROD-002", name="Different Product", price=99.99), + Product(product_id="PROD-004", name="New Product", price=19.99), + ] + assert gt[0].compare(pred[0]) == NEAR + + def run(gt_items, pred_items): + return _full_result( + Order(order_id="ORD-1", products=gt_items), + Order(order_id="ORD-1", products=pred_items), + ) - result = _full_result(Order(products=[gt]), Order(products=[pred])) + result = run(gt, pred) products = result["confusion_matrix"]["fields"]["products"] - assert _counts(products) == (1, 0) + overall = products["overall"] + assert [overall[key] for key in ("tp", "fd", "fn", "fa")] == [1, 2, 0, 0] + assert overall["derived"]["cm_precision"] == pytest.approx(1 / 3) + assert overall["derived"]["cm_recall"] == 1.0 + assert overall["derived"]["cm_f1"] == pytest.approx(0.5) assert _counts(products["fields"]["product_id"]) == (1, 0) assert _counts(products["fields"]["name"]) == (0, 1) assert _counts(products["fields"]["price"]) == (1, 0) - assert _non_match_paths(result) == ["products[0].name"] + assert [ + (entry["field_path"], entry["non_match_type"], round(entry["similarity_score"], 4)) + for entry in result["non_matches"] + ] == [ + ("products[0].name", "false_discovery", 0.4), + ("products[1]", "false_discovery", 0.6725), + ("products[2]", "false_discovery", 0.1333), + ] + + # Only lists of different lengths leave an item unmatched. + for gt_items, pred_items, kind, counts in ( + (gt, pred[:2], "false_negative", [1, 1, 1, 0]), + (gt[:2], pred, "false_alarm", [1, 1, 0, 1]), + ): + result = run(gt_items, pred_items) + overall = result["confusion_matrix"]["fields"]["products"]["overall"] + assert [overall[key] for key in ("tp", "fd", "fn", "fa")] == counts + last = result["non_matches"][-1] + assert (last["field_path"], last["non_match_type"]) == ("products[2]", kind) class TestListSubFieldGate: