Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
docs(hungarian): document the five counts and fix a worked example
The worked list example in classification logic reported TP=2, FA=2,
FN=1, FD=0 for a three item ground truth against a four item prediction.
The assignment pairs three of them, so "green" is paired with "orange"
at 0.17 and is an FD, and only one prediction is left over. The correct
counts are TP=2, FD=1, FA=1, FN=0. The FP total was right either way,
which is why the error went unnoticed. The example now shows the pairing
it is describing, since which items get paired is the part a reader
cannot infer.

The hungarian matching page already stated the rule correctly, so it
gains only a note that calculate_metrics follows it too, and did not
before #231.

Two new README files, one for src/stickler/algorithms and one for
tests/common/algorithms, as AGENTS.md asks for. The source one records
what each count means with its closed form, the two traps that make tp
unreadable, and the fact that both internal callers read only
matched_pairs. The test one says what each of the three files is for,
since they overlap on purpose and the reason is not obvious from their
names.

The changelog entry carries the migration note for a direct caller of
calculate_metrics. The old fn is fn plus fd.

Refs #231
  • Loading branch information
digalaviz committed Aug 27, 2026
commit 3abe427c71956f78f2f09e0829d42515c54e1a72
41 changes: 41 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,47 @@ Each release links to full notes on the

## [Unreleased]

### Fixed

- **Breaking:** `HungarianMatcher.calculate_metrics` no longer reports a paired
item as missing. It derived `fn` and `fp` as `len(list) - tp`, so a pair the
algorithm produced, and that the method returns inside `matched_pairs`, was
also counted as a false negative when its score fell below `match_threshold`.
The same pair was reported as matched and as missing at once, which fixes
[#231](https://github.com/awslabs/stickler/issues/231).

The assignment now decides what is paired and the threshold only splits the
paired items into `tp` and `fd`. Two keys join the returned dict: `fd` counts
pairs below the threshold and `fa` counts predictions with no partner. `fn`
keeps its name and counts only ground truth items with no partner.

**What moves:** `fn` is lower by `fd` for any input with a pair below the
threshold. If you read `fn` from this method directly, the old value is
`fn + fd`:

```python
metrics = matcher.calculate_metrics(gt, pred)
old_fn = metrics["fn"] + metrics["fd"]
```

**What does not move:** `fp` is still the rollup `fd + fa`, which still equals
the number of predictions that are not true positives, and `precision`,
`recall`, `f1` and `matched_pairs` are unchanged for every input. No evaluator
score changes either, because both internal callers
(`HungarianHelper.match_lists` and `ComparisonHelper.compare_unordered_lists`)
read only `matched_pairs` and classify the scores themselves. The counts now
agree with what `ComparisonHelper.unordered_list_metrics` already produced and
with the rule that
[Hungarian Matching](https://awslabs.github.io/stickler/Advanced/hungarian-matching/)
documents.

- The worked list example in
[Classification Logic](https://awslabs.github.io/stickler/Advanced/classification-logic/)
reported `TP=2, FA=2, FN=1, FD=0` for a three item ground truth against a four
item prediction. The assignment pairs three of them, so the correct counts are
`TP=2, FD=1, FA=1, FN=0`. The `FP` total was right, which is why the error went
unnoticed.

## [0.7.0] - 2026-08-18

### Added
Expand Down
23 changes: 16 additions & 7 deletions docs/docs/Advanced/classification-logic.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,22 @@ GT = ["red", "blue", "green"]
EST = ["red", "yellow", "orange", "blue"]
```

- "red" matches "red" -- TP
- "blue" matches "blue" -- TP
- "green" unmatched -- FN
- "yellow" unmatched -- FA
- "orange" unmatched -- FA

Result: TP=2, FA=2, FN=1, FD=0
The assignment pairs as many elements as the shorter list allows, so it makes
three pairs here and leaves one prediction over:

| GT | EST | Score | Classification |
|----|-----|-------|----------------|
| `"red"` | `"red"` | 1.00 | TP |
| `"blue"` | `"blue"` | 1.00 | TP |
| `"green"` | `"orange"` | 0.17 | FD |
| | `"yellow"` | | FA |

Result: TP=2, FD=1, FA=1, FN=0, and so FP=2

Note that `"green"` is an FD and not an FN. It did get a partner, and a low
score is what the FD category is for. Only an element the assignment could not
pair at all is FN or FA, which is why FN is zero whenever GT is the shorter
list.

#### Example: Below-Threshold Matches

Expand Down
7 changes: 7 additions & 0 deletions docs/docs/Advanced/hungarian-matching.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ 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
one; see `tests/common/algorithms/test_hungarian_path_parity.py`.

`HungarianMatcher.calculate_metrics` returns these same four counts if you call
it directly. Before
[#231](https://github.com/awslabs/stickler/issues/231) it did not have an `fd`
key and reported every low score pair in `fn` as well, which contradicted the
rule above. `tests/common/algorithms/test_hungarian_fd_contract.py` now pins the
agreement.

### FD and recall

Whether an FD counts against recall is a separate decision, controlled by
Expand Down
103 changes: 103 additions & 0 deletions src/stickler/algorithms/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# `stickler.algorithms`: optimal assignment between two lists

One module, one public class. `HungarianMatcher` pairs the items of two lists so
that the total similarity is as high as it can be, which is what lets a list
field be scored without caring about order. It is shared by the traditional and
the ANLS Star evaluation paths.

```python
from stickler.algorithms import HungarianMatcher
from stickler.comparators import LevenshteinComparator

matcher = HungarianMatcher(LevenshteinComparator(), match_threshold=0.7)
matcher.calculate_metrics(["apple", "banana"], ["banana", "aple"])
```

## The two methods, and which one to call

| Method | Returns | Use it when |
|---|---|---|
| `match(list1, list2)` | `(matched_indices, similarity_matrix)` | you want the assignment and the raw scores, and you will classify them yourself |
| `calculate_metrics(list1, list2)` | nine keys, described below | you want the assignment already classified against `match_threshold` |

`__call__` and `binary_compare` are legacy wrappers that return only
`(tp, fp)`.

## What the counts mean

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

| Key | Meaning | Closed form |
|---|---|---|
| `tp` | pair scoring at or above the threshold | |
| `fd` | pair scoring below the threshold, a false discovery | `k` minus `tp` |
| `fn` | ground truth item with no partner | `m` minus `k` |
| `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.
`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.

A paired item is never also reported as missing. That was the defect in
[#231](https://github.com/awslabs/stickler/issues/231), where `fn` was derived
as `m` minus `tp` and so counted every low score pair as a missing item while
the method was returning that same pair inside `matched_pairs`.

## 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`, `ComparisonHelper` and
`ConfusionMatrixCalculator` accept a score up to `1e-10` under the threshold, so
a score inside that window is a TP there and an FD here.

## How the evaluator uses it

Both internal callers read **only** `matched_pairs` and classify the scores
themselves:

| Caller | What it does with the pairs |
|---|---|
| `HungarianHelper.match_lists` | 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.

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
though, so a change there is still breaking for a direct caller.

## Design notes

**One derivation, one return.** The method used to return from five places, one
per input shape, three of which carried their own hardcoded rate values. Those
copies are what let the single item shortcut drift away from the general path in
[#224](https://github.com/awslabs/stickler/issues/224). The shortcut now
produces the pair and stops, and the counting below it is shared.

**Why the shortcut exists.** One item on each side has only one possible
assignment, so calling the solver is pure overhead on the most common list
shape. It is a performance branch, not a semantic one, and
`test_hungarian_path_parity.py` exists to keep it that way.

**`normalize_values` defaults to `True` and should usually be `False`.** It
lowercases and `str()` coerces every item before the comparator sees it, which
overrides the comparator a field declared and makes `List[bbox]` unscoreable.
See the note in `HungarianMatcher.__init__` for which call sites opt out and
why the default cannot change yet.

## Tests

`tests/common/algorithms/`. See the README there for what each file pins.
54 changes: 54 additions & 0 deletions tests/common/algorithms/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# algorithms Tests

Tests for `src/stickler/algorithms/`, which is `HungarianMatcher`. The README
there describes the contract these files hold it to.

Three files, three jobs. They overlap on purpose, because each one exists to
catch a different kind of regression.

## test_hungarian.py

The behaviour of the class as a whole. Construction, the comparator variants,
list preparation including a scalar and a JSON string of a list, the size
warning, and the legacy `__call__` and `binary_compare` wrappers. Start here
when adding a feature.

## test_hungarian_path_parity.py

That the single item shortcut classifies exactly like the general path
([#224](https://github.com/awslabs/stickler/issues/224)). The shortcut skips the
solver, so it is a second implementation of the same rule and it did drift once.
The property under test is length independence: a one item list must not
classify differently from a two item list in the same situation.

## test_hungarian_fd_contract.py

That a paired item is never also reported as missing
([#231](https://github.com/awslabs/stickler/issues/231)). This is the executable
form of the five category rule, written as invariants rather than as expected
values, so it holds for every shape instead of for the shapes someone thought
of.

Two classes in it are worth knowing about:

- `TestTheCountsPartitionTheInputs` is the cheapest full statement of the rule.
If those five assertions hold, no item is counted twice and none is dropped.
- `TestTheValuesThatMustNotChange` is a guard, not a specification. It pins the
values that #231 did **not** change. A failure there means the scope of a
change grew beyond one key, so read it as a question about the change and not
as a test to update.

`TestTheOldFnValueIsRecoverable` pins `old fn == fn + fd`, which is the
migration note for callers who read `fn` before #231. If that identity ever
stops holding, the changelog entry has gone stale.

## Fixtures

`_gt` and `_pred` build values with zero pairwise similarity, so a pair exists
without any score to reason about. They assert their own length rather than
slicing and hoping, because a fixture that quietly truncates leaves a test
passing while checking something weaker than its name claims.

```bash
uv run pytest tests/common/algorithms/ -v
```