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
Prev Previous commit
Next Next commit
docs(matching): describe the exclusion step and the required_match rules
- add the exclusion phase and the FN plus FA rule for a vetoed pair
- state that export drops the flag and that aggregate omits vetoed objects
- add an example and the rule to mark every identifying field as required
  • Loading branch information
digalaviz committed Nov 18, 2026
commit 8d60ce53ab29bfeb03013357ed23f7d321c43357
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@ Each release links to full notes on the
objects are paired in a list: a pair whose required field is not at or above
its threshold is excluded before the assignment and counts as one false
negative and one false alarm, never a false discovery. Off by default; scores
and counts do not change unless a field sets it.
and counts do not change unless a field sets it. Only `str`, `int`, `float`
and `bool` fields may be required, and a class may not hold a single nested
model that has required fields (`ValueError` when the class is defined). When
the two objects have different classes, a field required by either one vetoes
the pair. The vetoed objects are not counted in `aggregate`; read the list's
`overall` for them. Python only: `to_json_schema()` and `to_stickler_config()`
do not write it, and `model_from_json()` and `from_json_schema()` do not read
it.

## [1.0.1] - 2026-11-02

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 @@ -41,7 +41,8 @@ Lists use the [Hungarian algorithm](hungarian-matching.md) for optimal element p
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. 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).
4. **Vetoed pairs**: a pair a `required_match` field vetoes is never matched, so its two elements are one FN and one FA, not an FD. Neither object appears in `aggregate`, as with any unmatched element.
5. **`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).

#### `None` elements in a list {: #none-elements-in-a-list }

Expand Down
20 changes: 13 additions & 7 deletions docs/docs/Advanced/hungarian-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,28 @@ When Stickler compares `List[StructuredModel]` fields, it uses the Hungarian alg

## Overview

The algorithm has three phases:
The algorithm has four phases:

1. **Pairwise similarity** -- Compute a similarity score for every GT/Pred combination.
2. **Optimal assignment** -- Use the Hungarian algorithm to find the pairing that maximizes total similarity.
3. **Threshold-gated classification** -- Classify each pair as TP or FD based on `match_threshold`, then handle unmatched items.
2. **Exclusion** -- Remove every pair that a `required_match` field vetoes. A no-op when no field sets it.
3. **Optimal assignment** -- Use the Hungarian algorithm to find the pairing that maximizes total similarity among the allowed pairs.
4. **Threshold-gated classification** -- Classify each pair as TP or FD based on `match_threshold`, then handle unmatched items.

## Algorithm Steps

### 1. Pairwise Similarity

For each (GT[i], Pred[j]) pair, Stickler calls `GT[i].compare(Pred[j])` to obtain a raw weighted similarity score. Fields absent on both sides are excluded because a true negative is not match evidence. If every field is absent, the score is `1.0`. The result is an N x M cost matrix.

### 2. Hungarian Assignment
### 2. Exclusion

The Hungarian algorithm solves the assignment problem in O(n^3) time, producing a one-to-one mapping that maximizes total similarity. When lists differ in length, some items remain unmatched.
A pair is excluded when a field marked `required_match` is null on one side only, or scores below its threshold, on either object's class. The assignment then keeps as many allowed pairs as it can, even at lower similarity. See `required_match` in [Evaluation](../Guides/Evaluation/README.md).

### 3. Threshold-Gated Classification
### 3. Hungarian Assignment

The Hungarian algorithm solves the assignment problem in O(n^3) time, producing a one-to-one mapping that maximizes total similarity over the allowed pairs. When lists differ in length, or pairs were excluded, some items remain unmatched.

### 4. Threshold-Gated Classification

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):

Expand All @@ -39,7 +44,8 @@ The threshold splits matched pairs into TP and FD; it does not un-match them.
A pair the algorithm assigned is a match, so **similarity magnitude never
changes the classification** -- a pair at similarity `0.0` is still an assigned
pair and is therefore FD, not FN + FA. Only items with no partner at all
become FN or FA. This holds identically for a one-item list and a hundred-item
become FN or FA. An excluded pair is never assigned, so its two items each
have no partner: one FN and one FA, never an FD. This holds identically for a one-item list and a hundred-item

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
become FN or FA. An excluded pair is never assigned, so its two items each
have no partner: one FN and one FA, never an FD. This holds identically for a one-item list and a hundred-item
become FN or FA. An excluded pair is never assigned, so an item left with no
allowed partner is an FN or an FA, never an FD. Both items of an excluded pair
can still be paired with someone else. This holds identically for a one-item list and a hundred-item

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 as suggested.

one; see `tests/common/algorithms/test_hungarian_path_parity.py`.

`HungarianMatcher.calculate_metrics` returns these same four counts if you call
Expand Down
4 changes: 3 additions & 1 deletion docs/docs/Advanced/model-export.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,9 +266,11 @@ assert r1["overall_score"] == r2["overall_score"]
config = Product.to_stickler_config()
Reconstructed = StructuredModel.model_from_json(config)

# Comparison behavior is identical
# Comparison behavior is identical, except for `required_match`
```

`required_match` is not exported. `to_json_schema()` and `to_stickler_config()` drop it, and the reconstructed model pairs list objects without the veto, so scores and counts can differ from the original.

## Saving and Loading

```python
Expand Down
20 changes: 19 additions & 1 deletion docs/docs/Guides/Evaluation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,25 @@ Fields with higher weights pull the overall score toward their individual result

**`clip_under_threshold`** -- When enabled (the default), a field that scores below its threshold contributes 0.0 to the weighted average instead of its partial similarity. This prevents low-confidence matches from inflating the overall score.

**`required_match`** -- Without it, an object with one wrong field still matches when its overall score reaches the element class's `match_threshold`. A required field that is not at or above its resolved threshold (the field's `threshold`, else one named on the comparator, else `0.5`) vetoes the pair before the Hungarian assignment, so a better pairing is found if one exists. A veto takes priority over similarity: the assignment keeps as many allowed pairs as it can, even at lower scores. The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery. A value that is null on one side fails; null on both sides passes. Only `str`, `int`, `float` and `bool` fields (optionally `Optional`) may be required; any other annotation raises `ValueError` when the class is defined. The veto applies where objects are paired in a `List[StructuredModel]`. A single nested object has no pairing step, so it is not vetoed. The setting is Python only: `to_json_schema()` and `to_stickler_config()` do not write it, and `model_from_json()` and `from_json_schema()` do not read it.
**`required_match`** -- Without it, an object with one wrong field still matches when its overall score reaches the element class's `match_threshold`. Use it instead of `weight` when a wrong value must never pair two objects, however well the rest agrees.

```python
class Det(StructuredModel):
match_threshold = 0.5
cls: str = ComparableField(threshold=1.0, required_match=True)
x: float = ComparableField(threshold=0.9)
```

A `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` scores `0.0` and counts as one FN plus one FA. Without `required_match` the same pair scores `0.5` and is a TP.

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
A `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` scores `0.0` and counts as one FN plus one FA. Without `required_match` the same pair scores `0.5` and is a TP.
In a `List[Det]`, a `Det` with `cls="tote"` against one with `cls="pallet"` and the same `x` counts as one FN plus one FA, and the list scores `0.0`. Without `required_match` the pair is a TP and the list scores `0.5`.

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 as suggested. Measured: the pair scores the same either way, and the list scores 0.5 without the flag and 0.0 with it (1 FN, 1 FA).


- A required field that is not at or above its resolved threshold (the field's `threshold`, else one named on the comparator, else `0.5`) vetoes the pair before the Hungarian assignment. A threshold of `0.0` never vetoes a pair whose values are both present.
- A veto takes priority over similarity: the assignment keeps as many allowed pairs as it can, even at lower scores. Mark every field that identifies an object as required. A field that is not required can be traded off by the matcher, so similar objects may be paired with each other.
- The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score.

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
- The two objects left unmatched count as one False Negative (ground truth) and one False Alarm (prediction), never as a False Discovery, and add nothing to the list score.
- An object left with no allowed partner counts as a False Negative (ground truth) or a False Alarm (prediction), never as a False Discovery, and adds nothing to the list score. The two objects of a vetoed pair can still pair with others: with `label` required, `[a, b]` against `[b, a]` is 2 TP.

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 as suggested. Measured: [a, b] against [b, a] is 2 TP, and [a] against [b, a] is 1 TP and 1 FA.

- A value that is null on one side fails; null on both sides passes.
- When the two objects have different classes, a field required by either class can veto the pair, so swapping ground truth and prediction gives the same result.

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.

Since 649ad4a, each field is scored ground truth first, so with an asymmetric comparator swapping can change the result (gt R(x=100) vs pred R2(x=90) is a TP, gt R2(x=90) vs pred R(x=100) is vetoed, with relative_tolerance=0.1). That's right, it's how the field itself scores. Only the sentence needs to change:

Suggested change
- When the two objects have different classes, a field required by either class can veto the pair, so swapping ground truth and prediction gives the same result.
- When the two objects have different classes, a field required by either class can veto the pair, whichever of them is the ground truth. Each required field is scored ground truth first, as the field itself is.

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 as suggested. Measured with NumericComparator(relative_tolerance=0.1) on a required x: gt R(x=100) against pred R2(x=90) is 1 TP, gt R2(x=90) against pred R(x=100) is 1 FN and 1 FA.

- Only `str`, `int`, `float` and `bool` fields (optionally `Optional`) may be required, and a class may not hold a nested `StructuredModel` field whose class has required fields. Both raise `ValueError` when the class is defined. Only a direct, `Optional` or `Annotated` nested field is checked; one reached through a `Dict` or a `Union` is not, and its required fields are ignored.
- The veto applies where objects are paired in a `List[StructuredModel]`. A single nested object has no pairing step, so it is not vetoed.

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.

On your question: document these here for now; a warning at class definition is #678.

Suggested change
- The veto applies where objects are paired in a `List[StructuredModel]`. A single nested object has no pairing step, so it is not vetoed.
- The veto applies where objects are paired in a `List[StructuredModel]`. A single nested object has no pairing step, so it is not vetoed. Neither are the objects in a `List[List[Det]]`, or in a list that mixes objects with primitives.

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 the List[List[Det]] part: the inner lists are compared whole, and the list scores and counts the same with and without the flag. I changed the mixed-list part, because the veto does apply there when the list starts with an object. Which path a list takes is decided by the ground truth list's first element that is not None: comparison_dispatcher.py calls NullHelper.first_present(gt_val, pred_val), which reads the prediction only when the ground truth has no present element, and an all-None ground truth list is already handled as null before that. With cls required, [T, T] against [P, "k"] in a List[Any] goes from 2 TP (0.25) to 2 FN and 2 FA (0.0); ["k", T] against ["k", P] is the same with and without the flag. The bullet now says a mixed list is paired as objects, with the veto, only when the ground truth list's first element that is not None is an object.

For #678: mixed lists already raise AttributeError: 'str' object has no attribute 'compare_with' on dev when a string is paired with a model ([T, "k"] against [T, "k"]). The veto can make that pairing happen where it did not before: [T, "k"] against ["k"] scores 0.0 without the flag and raises with it.

- The setting is Python only: `to_json_schema()` and `to_stickler_config()` do not write it, and `model_from_json()` and `from_json_schema()` do not read it.

### Example Model

Expand Down
9 changes: 5 additions & 4 deletions src/stickler/algorithms/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ matcher.calculate_metrics(["apple", "banana"], ["banana", "aple"])

The assignment decides what is paired. `match_threshold` then splits the paired
items into two groups. It never puts a pair back into the unpaired counts. With
`m` and `n` as the two list lengths and `k` as the pair count, which is always
`min(m, n)`:
`m` and `n` as the two list lengths and `k` as the pair count, which is
`min(m, n)` unless `is_pair_excluded` vetoes pairs:

| Key | Meaning | Closed form |
|---|---|---|
Expand All @@ -44,8 +44,9 @@ items into two groups. It never puts a pair back into the unpaired counts. With
| `fa` | prediction item with no partner, a false alarm | `n` minus `k` |
| `fp` | the rollup, `fd` plus `fa` | `n` minus `tp` |

The four leaf counts cover `max(m, n)` items once each, so nothing is counted
twice and nothing is dropped. Only one of `fn` and `fa` can be non zero.
The four leaf counts cover `m + n - k` items once each, so nothing is counted
twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one
of `fn` and `fa` can be non zero; one vetoed pair leaves `fn` 1 and `fa` 1.

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
twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one
of `fn` and `fa` can be non zero; one vetoed pair leaves `fn` 1 and `fa` 1.
twice and nothing is dropped. Without exclusions `k` is `min(m, n)` and only one
of `fn` and `fa` can be non zero. With exclusions both can be: a 1 x 1 input
whose pair is vetoed gives `fn` 1 and `fa` 1.

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 as suggested. Measured: a 1 x 1 input whose pair is vetoed gives fn 1 and fa 1.

`tp + fp == n` and `tp + fn + fd == m`, which is why `precision` and `recall`
have a denominator in closed form and the method needs no special case per
input shape.
Expand Down