Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ Each release links to full notes on the
always scores 0.0. A `Tuple` field exports as a string type, so a single
point field does not round-trip through `to_json_schema()` or
`to_stickler_config()`; a list of points does.
- `ComparableField(required_match=True)` makes a primitive field a veto when
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. 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 follow the `aggregate` rule for any FN or FA
item: left out when a sibling was accepted, in the list's own counts when
none was. 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.

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.

The per-pair clause (Must fix 1), plus the new matcher keyword. Your aggregate sentence stays:

Suggested change
- `ComparableField(required_match=True)` makes a primitive field a veto when
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. 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 follow the `aggregate` rule for any FN or FA
item: left out when a sibling was accepted, in the list's own counts when
none was. 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.
- `ComparableField(required_match=True)` makes a primitive field a veto when
objects are paired in a list: a pair whose required field is not at or above
its threshold is excluded before the assignment, which keeps as many allowed
pairs as it can. An object left with no allowed partner counts as a false
negative or a false alarm, never a false discovery. Off by default; scores
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 unmatched objects follow the `aggregate` rule for any FN or FA
item: left out when a sibling was accepted, in the list's own counts when
none was. `HungarianMatcher` takes a new `is_pair_excluded` keyword for this.
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.

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, with one addition: the nested refusal now says ValueError when the class is defined, or on first use for a nested class defined further down.


### Changed

Expand Down
4 changes: 2 additions & 2 deletions docs/docs/Advanced/classification-logic.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ This table is the single statement of how Stickler treats a list field. Other pa

| Aspect | Rule |
|---|---|
| Pairing | A list field's elements are paired one-to-one by the [Hungarian algorithm](hungarian-matching.md), maximising total similarity, so their order does not matter: `["a", "b"]` vs `["b", "a"]` scores `1.0`. An element that is itself a list (`List[List[str]]`) is compared as one whole value, so order inside it does count. On the zero-config path (`stickler.evaluate()` on a plain pydantic class) that inner list, and a list held in an `Any` field, must match exactly, order included. `None` and `NaN` elements are removed first ([`None` elements in a list](#none-elements-in-a-list)); reports keep original indices. Pair similarity is the field's comparator, or `GT[i].compare(Pred[j])` for `List[StructuredModel]` (fields absent on both sides excluded). A list the field's comparator reads as one value is not paired: under `BBoxIoUComparator`, a box `[x1, y1, x2, y2]` or `[[x1, y1], [x2, y2]]` in a field whose elements are scalars (`List[float]`, `Sequence[float]`) is scored whole, with one count and one report row, so it is one FN or FA against a null list (`None`, `[]`, all `None` or NaN) and one FD against a malformed value. A field whose elements are sequences (`List[List[float]]`, or a union or alias with a sequence arm) stays paired; a bare `list` or `List[Any]` is decided by the ground-truth value. |
| Pairing | A list field's elements are paired one-to-one by the [Hungarian algorithm](hungarian-matching.md), maximising total similarity, so their order does not matter: `["a", "b"]` vs `["b", "a"]` scores `1.0`. An element that is itself a list (`List[List[str]]`) is compared as one whole value, so order inside it does count. On the zero-config path (`stickler.evaluate()` on a plain pydantic class) that inner list, and a list held in an `Any` field, must match exactly, order included. `None` and `NaN` elements are removed first ([`None` elements in a list](#none-elements-in-a-list)); reports keep original indices. Pair similarity is the field's comparator, or `GT[i].compare(Pred[j])` for `List[StructuredModel]` (fields absent on both sides excluded). A list the field's comparator reads as one value is not paired: under `BBoxIoUComparator`, a box `[x1, y1, x2, y2]` or `[[x1, y1], [x2, y2]]` in a field whose elements are scalars (`List[float]`, `Sequence[float]`) is scored whole, with one count and one report row, so it is one FN or FA against a null list (`None`, `[]`, all `None` or NaN) and one FD against a malformed value. A field whose elements are sequences (`List[List[float]]`, or a union or alias with a sequence arm) stays paired; a bare `list` or `List[Any]` is decided by the ground-truth value. A pair that a `required_match` field vetoes is never paired, and the assignment pairs as many allowed pairs as it can before it maximises similarity. |
| Bar | `List[StructuredModel]`: the element class's `match_threshold`; a runtime `match_threshold` does not change it. A field `threshold` there raises `ValueError` in Python, and JSON Schema ignores it. Primitive, dict and plain-model lists on a `StructuredModel` declared in Python: the field's `threshold`, else a threshold named on the comparator, else `0.5` when declared with `ComparableField()`, or the class `match_threshold` (`0.7` unless set) when declared without it (`tags: List[str]`). JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../Getting-Started/thresholds-and-metrics.md#4-runtime-match-threshold)). A pair that [meets](../Getting-Started/thresholds-and-metrics.md#meeting-a-threshold) the bar is a TP. |
| Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). |
| Counts (the list node's `overall`) | Paired element: TP if it meets the bar, else FD. Unpaired GT element: FN. Unpaired prediction: FA. The two elements of a vetoed pair are unpaired, so one FN and one FA, never an FD. An empty, `None` or all-`None` list is null: both null is one TN (score `1.0`); one side null gives one FN or FA per present element (score `0.0`). |

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.

A veto removes a pair, not its two objects: gt [a, b] vs pred [b, a] with label required vetoes (0,0) and (1,1) and gives 2 TP. Maybe replace "The two elements of a vetoed pair are unpaired, so one FN and one FA, never an FD." with:

"A vetoed pair is never paired, so an element left with no allowed partner is unpaired: an FN or an FA, never an FD."

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.

| Recursion | Only TP pairs of `StructuredModel` items are descended into. FD, FN and FA items are atomic. `aggregate` holds the leaves of TP items only, so FD, FN and FA items are left out of it when any sibling was accepted. With no accepted item it falls back to the list node's own counts ([why](aggregate-metrics.md#aggregate-counts-objects-for-an-all-rejected-list)). |
| Score | `sum(pair scores) / max(n_gt, n_pred)`, never clipped as a whole against a field threshold. For primitive, dict and plain-model lists the pair score is the element similarity, zeroed below the bar when `clip_under_threshold` is on. On a `StructuredModel` declared in Python it defaults to on for primitive lists and off for dict and plain-model lists. JSON Schema and the zero-config path have their own defaults ([JSON Schema](../Guides/Evaluation/README.md#extension-reference), [zero-config](../API-Reference/auto.md#inference)). For `List[StructuredModel]` the pair score is `GT[i].compare_with(Pred[j])["overall_score"]`, which applies each field's own threshold and can differ from the pairing similarity. Currently `clip_under_threshold` has no effect there, so an FD pair keeps its score: a known gap. [Worked example](hungarian-matching.md#step-4-list-score). |
| Reports | `field_comparisons`: one row per element of a primitive, dict or plain-model list, whatever its classification (a dict or plain-model element is not expanded into its keys or fields); for `List[StructuredModel]`, one row per leaf of a TP item and one object row per FD, FN or FA item. `non_matches` has the same rows, but only the FD, FN and FA ones. A `field_comparisons` row's `match` is true when its own classification is TP or TN: a value or object row met its bar; a list row had every element paired as a TP, with no FD, FA or FN at the element level. Failures deeper down get their own rows. |
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 @@ -272,9 +272,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
21 changes: 21 additions & 0 deletions docs/docs/Guides/Evaluation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ When defining a `StructuredModel` subclass in Python, each field is declared wit
| `threshold` | `float` (0.0--1.0) | `0.5` | Minimum similarity score required for a field to be classified as a match. |
| `weight` | `float` (> 0.0) | `1.0` | Relative importance of this field when computing aggregate scores. |
| `clip_under_threshold` | `bool` | `True` (`False` on dict and plain-model fields and lists of them) | When `True`, scores below `threshold` are zeroed out before contributing to the weighted average. List fields follow the [Score](../../Advanced/classification-logic.md#list-contract) rule of the list contract. |
| `required_match` | `bool` | `False` | When `True`, a score not at or above `threshold` vetoes the object pair when objects are matched inside a list. |

### How Each Parameter Affects Scoring

Expand Down Expand Up @@ -82,6 +83,26 @@ Fields with higher weights pull the overall score toward their individual result

**`clip_under_threshold`** -- When enabled (the default, except on dict and plain-model fields), 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. A list field follows the [Score](../../Advanced/classification-logic.md#list-contract) rule of the list contract instead.

**`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

```python
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
Loading