Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
Next Next commit
feat(matching): add required_match to veto failing list pairs
- a required field below its threshold excludes the pair from the
  list assignment, so both objects stay unmatched (fn 1, fa 1, no fd)
- the exclusion is a cost above every allowed total, so a better
  allowed pairing is found and vetoed pairs are minimised first
- only primitive fields may be required, anything else raises when
  the class is defined
- default False leaves counts and scores unchanged
  • Loading branch information
digalaviz committed Nov 18, 2026
commit 25db8d3c8a4406a98725230ce0f87db7047dd61a
40 changes: 33 additions & 7 deletions src/stickler/algorithms/hungarian.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def __init__(
size_threshold: int = HUNGARIAN_SIZE_WARNING_THRESHOLD,
normalize_values: bool = True,
match_threshold: float = 0.7,
is_pair_excluded: Optional[Callable[[Any, Any], bool]] = None,
):
"""Initialize the Hungarian matcher.

Expand Down Expand Up @@ -68,11 +69,15 @@ def __init__(
never sees ``""`` standing in for a missing
element.
match_threshold: Minimum similarity score to consider a match as TP
is_pair_excluded: Tells whether a pair must never be assigned, as
whatever its score. The pair is left unmatched, so it
is neither a TP nor an FD. None excludes nothing.
"""
self.comparator = comparator or (lambda x, y: float(x == y))
self.size_threshold = size_threshold
self.normalize_values = normalize_values
self.match_threshold = match_threshold
self.is_pair_excluded = is_pair_excluded

def _normalize_value(self, value: Any) -> Any:
"""Normalize a value to improve string matching.
Expand Down Expand Up @@ -235,8 +240,25 @@ def match(self, list1: Any, list2: Any) -> Tuple[List[Tuple[int, int]], np.ndarr
# Cost is 1 - similarity (because Hungarian minimizes cost)
cost_matrix = make_cost_matrix(similarity_matrix, lambda x: 1 - x)

# an excluded pair costs more than every allowed assignment can sum
# to, so the solver picks one only when no allowed pairing is left,
# and it is dropped below. Dropping it alone after an unconstrained
# solve would give up the allowed pairing the exclusion makes room for.
excluded_pairs = set()
if self.is_pair_excluded is not None:
excluded_cost = float(max(len(list1), len(list2)) + 1)
for i, item1 in enumerate(list1):
for j, item2 in enumerate(list2):
if self.is_pair_excluded(item1, item2):
cost_matrix[i][j] = excluded_cost
excluded_pairs.add((i, j))

# Compute the optimal assignment
matched_indices = _MUNKRES.compute(cost_matrix)
matched_indices = [
pair
for pair in _MUNKRES.compute(cost_matrix)
if tuple(pair) not in excluded_pairs
]

# Clean up to help with memory usage
del cost_matrix
Expand Down Expand Up @@ -266,7 +288,8 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict:
Returns:
The same nine keys for every input, empty lists included. Below,
``m`` and ``n`` are the two prepared lengths and ``k`` is the pair
count, which is always ``min(m, n)``.
count, which is ``min(m, n)`` unless ``is_pair_excluded`` leaves
pairs out.

matched_pairs: ``k`` tuples of ``(i, j, score)``
tp: pairs scoring at or above ``match_threshold``
Expand Down Expand Up @@ -313,7 +336,10 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict:
# exactly like a longer one, so this branch produces the pair and
# stops. The counting below is then shared, not repeated.
score = self._score(prepared_list1[0], prepared_list2[0])
matched_pairs = [(0, 0, score)]
is_excluded = self.is_pair_excluded is not None and self.is_pair_excluded(
prepared_list1[0], prepared_list2[0]
)
matched_pairs = [] if is_excluded else [(0, 0, score)]
else:
# An empty list needs no branch of its own. match() returns no
# pairs for one, which is what the counting below expects.
Expand All @@ -324,10 +350,10 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict:
(i, j, similarity_matrix[i, j]) for i, j in matched_indices
]

# match() assigns exactly min(m, n) pairs, so the four counts below
# 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.
# match() assigns exactly min(m, n) pairs unless pairs are excluded, so
# the four counts below 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ def ComparableField(
default: Any = _DEFAULT_UNSET,
*,
clip_under_threshold: Optional[bool] = None,
required_match: bool = False,
# Pydantic Field parameters (all optional, just like Field)
alias: Optional[str] = None,
description: Optional[str] = None,
Expand Down Expand Up @@ -120,6 +121,13 @@ def ComparableField(
which lets a dict-annotated field default it to False so
partial credit survives, while an explicit True or False is
always honoured. See StructuredModel.__init_subclass__.
required_match: Whether a score below this field's resolved threshold
vetoes the pair when the owning object is matched inside a
list of objects (default: False). A vetoed pair is excluded
before the assignment, so its two objects are left
unmatched, one false negative and one false alarm. A

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.

Suggested change
list of objects (default: False). A vetoed pair is excluded
before the assignment, so its two objects are left
unmatched, one false negative and one false alarm. A
list of objects (default: False). A vetoed pair is excluded
before the assignment. An object left with no allowed
partner is a false negative or a false alarm, never a false discovery. A

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied, rewrapped to the docstring's width.

field that is null on one side fails, null on both passes.
Only primitive fields may be required.
alias: Pydantic field alias for serialization (default: None)
description: Field description for documentation (default: None)
examples: Example values for the field (default: None)
Expand Down Expand Up @@ -204,6 +212,7 @@ def json_schema_extra_func(schema: Dict[str, Any]) -> None:
json_schema_extra_func._threshold_explicit = threshold_was_explicit
json_schema_extra_func._threshold = threshold
json_schema_extra_func._weight = weight
json_schema_extra_func._required_match = required_match
json_schema_extra_func._clip_under_threshold = clip_under_threshold
json_schema_extra_func._comparison_metadata = serializable_metadata

Expand All @@ -222,6 +231,7 @@ def enhanced_json_schema_extra(schema: Dict[str, Any]) -> None:
enhanced_json_schema_extra._threshold_explicit = threshold_was_explicit
enhanced_json_schema_extra._threshold = threshold
enhanced_json_schema_extra._weight = weight
enhanced_json_schema_extra._required_match = required_match
enhanced_json_schema_extra._clip_under_threshold = clip_under_threshold
enhanced_json_schema_extra._comparison_metadata = serializable_metadata
final_json_schema_extra = enhanced_json_schema_extra
Expand All @@ -238,6 +248,7 @@ def enhanced_json_schema_extra(schema: Dict[str, Any]) -> None:
enhanced_json_schema_extra._threshold_explicit = threshold_was_explicit
enhanced_json_schema_extra._threshold = threshold
enhanced_json_schema_extra._weight = weight
enhanced_json_schema_extra._required_match = required_match
enhanced_json_schema_extra._clip_under_threshold = clip_under_threshold
enhanced_json_schema_extra._comparison_metadata = serializable_metadata
final_json_schema_extra = enhanced_json_schema_extra
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,19 @@ def defer_pair_warnings() -> Iterator[None]:
_DEFER_PAIR_WARNINGS.set(previous)


def _fails_required_match(gt_item: Any, pred_item: Any) -> bool:
"""Whether a required field vetoes this pair; False for a non-model item."""
fails = getattr(gt_item, "fails_required_match", None)
return fails is not None and fails(pred_item)


class HungarianHelper:
"""Helper class for Hungarian matching operations with StructuredModel objects."""

def __init__(self):
self.hungarian = HungarianMatcher(StructuredModelComparator())
self.hungarian = HungarianMatcher(
StructuredModelComparator(), is_pair_excluded=_fails_required_match
)

def get_complete_matching_info(
self, gt_list: List[Any], pred_list: List[Any]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,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

Expand Down Expand Up @@ -420,6 +420,61 @@ class StructuredModel(BaseModel):
# Default match threshold - can be overridden in subclasses
match_threshold: ClassVar[float] = 0.7

# read per cell of a Hungarian cost matrix, so it is resolved once per class
_required_match_fields: ClassVar[tuple] = ()

@classmethod
def _collect_required_match_fields(cls) -> None:
"""Record the fields marked ``required_match`` and refuse non-primitives.

Refused here, when the class is defined, because a required field is
scored by its comparator against a threshold, which has no meaning for
a list or an object whose score is an aggregate.
"""
required = []
for field_name, field_info in cls.model_fields.items():
extra = getattr(field_info, "json_schema_extra", None)
if not getattr(extra, "_required_match", False):
continue
# unwrap until stable: Optional[Annotated[T, ...]] needs both,
# in the order optional then annotated
annotation = field_info.annotation
while True:
inner = unwrap_optional(unwrap_annotated(annotation))[0]
if inner is annotation:
break
annotation = inner
if annotation not in (str, int, float, bool):
raise ValueError(
f"Field '{field_name}' sets required_match=True but is "
f"annotated {field_info.annotation}. Only str, int, float and "
f"bool fields (optionally Optional) may be required."
)
required.append(field_name)
cls._required_match_fields = tuple(required)

def fails_required_match(self, other: Any) -> bool:
"""Whether a required field of this object is not matched by ``other``.

A value null on one side fails and null on both passes. Otherwise the
field fails when its raw score is not at or above its resolved threshold,
by the same test every other classification gate uses.
"""
for field_name in self.__class__._required_match_fields:
mine = getattr(self, field_name)
theirs = getattr(other, field_name, None)
mine_is_null = NullHelper.is_effectively_null_for_primitives(mine)
theirs_is_null = NullHelper.is_effectively_null_for_primitives(theirs)
if mine_is_null or theirs_is_null:
if mine_is_null != theirs_is_null:
return True
continue
threshold = self.__class__._get_comparison_info(field_name).threshold
score = self.compare_field_raw(field_name, theirs)
if not ThresholdHelper.is_above_threshold(score, threshold):
return True
return False

@classmethod
def _install_object_grade_comparators(cls) -> None:
"""Give object-grade fields a comparator that can score a whole object.
Expand Down Expand Up @@ -570,6 +625,7 @@ def __pydantic_init_subclass__(cls, **kwargs):
"""
super().__pydantic_init_subclass__(**kwargs)
cls._install_object_grade_comparators()
cls._collect_required_match_fields()

def __init_subclass__(cls, **kwargs):
"""Validate field configurations when a StructuredModel subclass is defined."""
Expand Down
Loading