Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
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
134 changes: 12 additions & 122 deletions src/stickler/structured_object_evaluator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ The Structured Object Evaluator is designed to compare complex, nested data stru
Key components:
- **StructuredModel**: Base class for defining structured data models
- **ComparableField**: Field descriptor for configuring comparison behavior
- **ANLSTree**: Tree-based representation for structured objects
- **ANLSTree** (in `trees/`): an alternate, parallel evaluation path — see [#135](https://github.com/awslabs/stickler/issues/135)
- **Utility functions**: For calculating ANLS scores and handling key scores

## Installation
Expand Down Expand Up @@ -389,131 +389,20 @@ Available comparators:

## API Reference

### StructuredModel

```python
class StructuredModel(BaseModel):
"""Base class for structured data models with comparison capabilities."""

def compare_with(self, other: 'StructuredModel') -> Dict[str, Any]:
"""
Compare this model with another model.

Args:
other: Another StructuredModel to compare with

Returns:
Dictionary with comparison results
"""

@classmethod
def from_json(cls, json_obj: Dict[str, Any]) -> 'StructuredModel':
"""
Create a model instance from a JSON object.

Args:
json_obj: JSON object to convert

Returns:
StructuredModel instance
"""

@classmethod
def from_json_schema(cls, schema: Dict[str, Any]) -> Type['StructuredModel']:
"""
Create a StructuredModel subclass from a JSON Schema document.

Args:
schema: JSON Schema document (Draft 7 compatible)

Returns:
New StructuredModel subclass

Example:
>>> schema = {
... "type": "object",
... "title": "Product",
... "properties": {
... "name": {"type": "string"},
... "price": {"type": "number"}
... },
... "required": ["name", "price"]
... }
>>> Product = StructuredModel.from_json_schema(schema)
>>> product = Product(name="Widget", price=9.99)
"""
```

### Utility Functions

```python
def anls_score(
gt: Any,
pred: Any,
return_gt: bool = False,
return_key_scores: bool = False
) -> Union[float, Tuple[float, Any], Tuple[float, Any, Dict[str, Any]]]:
"""
Calculate ANLS score between two objects.

Args:
gt: Ground truth object
pred: Prediction object
return_gt: Whether to return the closest ground truth
return_key_scores: Whether to return detailed key scores

Returns:
Either just the overall score (float), or a tuple with the score and
closest ground truth, or a tuple with the score, closest ground truth,
and key scores.
"""

def compare_json(
gt_json: Dict[str, Any],
pred_json: Dict[str, Any],
model_cls: Type[StructuredModel]
) -> Dict[str, Any]:
"""
Compare JSON objects using a StructuredModel.

Args:
gt_json: Ground truth JSON
pred_json: Prediction JSON
model_cls: StructuredModel class to use for comparison

Returns:
Dictionary with comparison results
"""
```
See the generated API reference for full signatures and options:
[Models](https://awslabs.github.io/stickler/API-Reference/models/) for `StructuredModel`
(including `compare_with`), and [API](https://awslabs.github.io/stickler/API-Reference/api/)
for `anls_score` and `compare_json`.

## Performance Optimizations

### Hungarian Matching Optimization (2025)

The Structured Object Evaluator has been optimized to eliminate redundant Hungarian matching operations for list comparisons. Previously, the system performed 4-5 separate Hungarian matching calculations per list field, leading to O(n²) complexity for list-heavy comparisons.

**Optimization Details:**
- **Problem**: Multiple calls to `get_matched_pairs_with_scores()`, `get_assignments()`, and `get_unmatched_indices()` for the same list pairs
- **Solution**: Consolidated to single `get_complete_matching_info()` call that returns all required information
- **Performance Impact**: 60-75% improvement for comparisons with multiple list fields
- **Backward Compatibility**: All existing APIs maintained, optimization is transparent to users

**Files Modified:**
- `hungarian_helper.py`: Added unified `get_complete_matching_info()` method
- `structured_model.py`: Updated to use single Hungarian matching call
- `structured_list_comparator.py`: Optimized list comparison logic
- `comparison_helper.py`: Updated helper methods
- `evaluator_format_helper.py`: Updated evaluator formatting

**Testing**: All 374 existing tests pass, ensuring no regression in functionality.

### Post-Processing Architecture

The comparison pipeline uses a constructive building approach in `compare_recursive()` followed by lightweight post-processing transformations:

1. **Primary Traversal**: `compare_recursive()` builds the comparison tree structure efficiently
2. **Aggregate Metrics**: `AggregateMetricsCalculator.calculate_aggregate_metrics()` adds Universal Aggregate Field data
3. **Derived Metrics**: `_add_derived_metrics_to_result()` adds precision, recall, F1 scores
3. **Derived Metrics**: `DerivedMetricsCalculator.add_derived_metrics_to_result` adds precision, recall, F1 scores

This architecture prioritizes correctness of the core comparison logic while keeping post-processing transformations simple and maintainable. The post-processing steps operate on already-computed confusion matrix data and represent a small fraction of total computation time.

Expand All @@ -524,13 +413,16 @@ See the [examples](../../../examples/key_information_evaluation/structured_objec
## Known Limitations

### Dictionary Fields
Dictionary fields (`Dict[str, Any]`) with text-based comparators like `LevenshteinComparator` are not supported as they would produce unpredictable results.
A `Dict[str, Any]` field given a text comparator like `LevenshteinComparator` warns once and
scores 0.0 rather than comparing meaningfully (see [#297](https://github.com/awslabs/stickler/issues/297)).
A dict field with no comparator named gets `ANLSStarComparator` instead.

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.

Required. This new text is right, but the example 7 lines below still says # ❌ Not supported - will raise an error (:425). #521 names that exact claim as wrong, and the PR says Closes #521.

Measured on dev 0a4820f4 (PYTHONPATH=<dev>/src), with a field attributes: Dict[str, Any] = ComparableField(comparator=LevenshteinComparator(), threshold=0.7):

class def: ok, warnings at def: 0
score identical dicts: 0.0 {'attributes': 0.0}
warnings total: 1 ["Field 'attributes' holds a mapping, but its comparator (LevenshteinComparator) scores scal..."]

Please change :425 to something like # ⚠️ Warns once and scores 0.0 -- not a meaningful comparison. :440 ("This limitation ensures reliable, predictable comparison results.") also no longer fits, because no error is raised. Drop it or reword it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in ac57e13


**Solution**: Create proper StructuredModel subclasses instead of using raw dictionaries.
**Recommended**: define a `StructuredModel` subclass instead of a raw dict, so each key gets
its own configured comparator.

**Example**:
```python
# ❌ Not supported - will raise an error
# ⚠️ Warns once and scores 0.0 -- not a meaningful comparison
attributes: Dict[str, Any] = ComparableField(
comparator=LevenshteinComparator(),
threshold=0.7
Expand All @@ -544,5 +436,3 @@ class CustomerAttributes(StructuredModel):
class Customer(StructuredModel):
attributes: CustomerAttributes = ComparableField(...)
```

This limitation ensures reliable, predictable comparison results.
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def calculate_aggregate_metrics(self, result: dict) -> dict:
processed_field = self.calculate_aggregate_metrics(field_result)
fields_copy[field_name] = processed_field

# CRITICAL FIX: Sum child's aggregate metrics to parent
# Sum child's aggregate metrics to parent
if "aggregate" in processed_field and self._has_basic_metrics(
processed_field["aggregate"]
):
Expand All @@ -141,7 +141,6 @@ def calculate_aggregate_metrics(self, result: dict) -> dict:
fields_copy[field_name] = field_result
result_copy["fields"] = fields_copy

# CRITICAL FIX: Enhanced leaf node detection for deep nesting
# Handle both empty fields dict and missing fields key as leaf indicators
is_leaf_node = (
"fields" not in result_copy
Expand All @@ -162,7 +161,7 @@ def calculate_aggregate_metrics(self, result: dict) -> dict:
for metric in ["tp", "fa", "fd", "fp", "tn", "fn"]:
aggregate_metrics[metric] = overall.get(metric, 0)
elif self._has_basic_metrics(result_copy):
# CRITICAL FIX: Legacy primitive leaf node - wrap in "overall" structure
# Legacy primitive leaf node - wrap in "overall" structure
# This preserves Universal Aggregate Field structure compliance
legacy_metrics = {}
for metric in ["tp", "fa", "fd", "fp", "tn", "fn"]:
Expand All @@ -179,7 +178,7 @@ def calculate_aggregate_metrics(self, result: dict) -> dict:
del result_copy[metric]
# Preserve other keys like derived, raw_similarity_score, etc.

# CRITICAL FIX: Always sum child field metrics if no child aggregates were found
# Always sum child field metrics if no child aggregates were found
# This handles the deep nesting case where leaf nodes have overall metrics but empty fields
if (
aggregate_metrics["tp"] == 0
Expand All @@ -193,7 +192,7 @@ def calculate_aggregate_metrics(self, result: dict) -> dict:
if "fields" in result_copy and isinstance(result_copy["fields"], dict):
for field_name, field_result in result_copy["fields"].items():
if isinstance(field_result, dict):
# ENHANCED: Check for both direct metrics and overall metrics
# Check for both direct metrics and overall metrics
if "overall" in field_result and self._has_basic_metrics(
field_result["overall"]
):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,8 @@ class MyModel(StructuredModel):
def json_schema_extra_func(schema: Dict[str, Any]) -> None:
schema["x-comparison"] = serializable_metadata

# HYBRID APPROACH: Store runtime instances as function attributes
# This works around FieldInfo's __slots__ restriction
# Store runtime instances as function attributes: FieldInfo's __slots__
# cannot hold them directly.
json_schema_extra_func._comparator_instance = actual_comparator
json_schema_extra_func._comparator_explicit = comparator_was_explicit
json_schema_extra_func._clip_explicit = clip_was_explicit
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def compare_recursive(
total_score += threshold_applied_score * weight
total_weight += weight

# CRITICAL FIX: Handle hallucinated fields (extra fields) as False Alarms
# Handle hallucinated fields (extra fields) as False Alarms
extra_fields_fa = self._count_extra_fields_as_false_alarms(other)
result["overall"]["fa"] += extra_fields_fa
result["overall"]["fp"] += extra_fields_fa
Expand Down Expand Up @@ -332,12 +332,10 @@ def compare_with(

from .confidence import ConfidenceCalculator

# Auto-enable field_comparisons when the caller asked for
# confidence. Previously forgetting document_field_comparisons=True
# raised `ValueError: No field comparisons found` from deep inside
# the calculator. The calculator is a lower-level API and still
# raises, but at the compare_with level we know the user wants
# confidence and can wire the data through themselves.
# add_confidence_metrics implies field_comparisons: compute it here if the
# caller didn't already request it via document_field_comparisons. The
# lower-level ConfidenceCalculator still raises ValueError on its own if
# field_comparisons is missing; that guard is deliberate, not duplicated here.
if "field_comparisons" not in result:
field_comparisons = (
self.field_comparison_collector.collect_field_comparisons(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,63 +31,20 @@ class _ClassGatedComparator(BaseComparator):
"""Applies the object-pair gate to a list element, else delegates.

List elements reach a comparator through the Hungarian cost matrix, which
sees values and knows nothing about the field. Wrapping the comparator is
what makes a list element obey the same rules as the singular form: both
then read the same configured comparator, with the same gate in front of it.
Without this, `Single(pet=Cat('rex'))` against `Dog('rev')` scored 0.0 while
`Listed(pets=[Cat('rex')])` against `[Dog('rex')]` scored 1.0 -- the parity
#319 exists to establish, broken in the opposite direction. See #321 for
whether a refused element should pair at all.

The gate itself is `ConfigurationHelper.can_compare_object_pair`, the same
call `ComparisonDispatcher` CASE 4/CASE 5 and both `compare_field_raw`
readers make, so an element and a singular value are judged by one rule.

Installed when at least one element of EITHER list is a plain model, so the
ordinary primitive-list path keeps its cost-matrix hot loop unwrapped. The
LIST is what qualifies for wrapping; which PAIRS are then judged is
`_judges`, and it is a pair with a plain model on at least one side. A pair
with a plain model on neither -- dict against dict, `StructuredModel` against
`StructuredModel` -- is delegated untouched.

That narrowing is the whole correctness of this wrapper, and it was wrong in
both directions before. Judging every pair because the list qualified made an
element's verdict depend on what ELSE the list happened to hold:

f: Optional[List[Any]] dev list-wide gate
[{'a':1},{'b':2},{'c':3}] 1.0 1.0
[{'a':1},{'b':2},{'c':3}, Plain('p')] 1.0 0.0 <- fd on all four
[NoteSM] vs [Note2SM] 1.0 1.0
[Plain, NoteSM] vs [Plain, Note2SM] 1.0 0.0
same, with a comparator declared on `f` 1.0 0.5

The dict row zeroed three elements that score 1.0 on their own, in the same
list, on `dev`, and here the moment the plain model is removed -- and it drew
a "holds a mapping" warning on a field whose annotation says nothing about
mappings. The two `[Plain, NoteSM]` rows are worse than wrong-looking: both
enforce the cross-class rule that #327 is explicitly holding open (the bare
row's 0.0 is fd=2, the refused `Plain` pair plus `NoteSM`/`Note2SM`; with
`[Plain, NoteSM]` on both sides it scores 0.5), so a user got the #327 answer
or the documented one according to whether an unrelated plain model shared
the list. Both rules now apply to exactly the population the wrapper was
installed for. The declared row now scores 1.0; the bare row scores 0.5,
because the bare annotation still refuses the `Plain` pair on its own
(`[Plain]` vs `[Plain]` scores 0.0), not because of the cross-class rule.

A dict element does not reach the gate -- neither because
`_holds_a_plain_model` does not look for one, which was the old and only
conditionally true reason, nor by accident: `_is_plain_model` is asked of both
sides here.

WARNING TIMING. The matcher asks this comparator for every cell of the cost
matrix and keeps one per row, so warning from inside `_compare` announced an
outcome that never happened -- an identical `[Plain('aaa'), Note('bbb')]` pair
scored 1.0 with `tp=2` and still warned that a `Plain` had been compared
against a `Note`, from the cross cell the matcher discarded. Worse, `warn_once`
spends one message per field for the life of the process, so that probe cell
silenced the genuine wrong-class prediction later in the same corpus. Probing
is therefore silent, and `warn_for_selected` replays the gate on the pairs the
matcher actually chose.
sees values, not the field, so without this wrapper a list element skips
the gate that a singular field value goes through (#319). Installed when
at least one element of EITHER list is a plain model; `_judges` below
then judges only a pair with a plain model on at least one side. A pair
with neither (dict against dict, `StructuredModel` against
`StructuredModel`) is delegated untouched, so #327's open cross-class
rule is not applied to it. See #321 for whether a refused element should
pair at all.

Warnings are replayed against the matcher's chosen pairs rather than raised from
inside `_compare`: the matcher probes every cell of the cost matrix, including pairs
it never selects, and `warn_once` only fires once per field for the process's life
so warning from a probe-and-discarded cell could silence the real warning for a pair
the matcher actually picks.
"""

def __init__(self, inner: BaseComparator, model_cls=None, field_name: str = ""):
Expand Down Expand Up @@ -454,13 +411,13 @@ def compare_unordered_lists(
isinstance(item, StructuredModel) for item in gt_list[:1] + pred_list[:1]
):
# For StructuredModel lists, we need to use individual comparison scoring for consistency
# Use HungarianHelper to get optimal pairings - OPTIMIZED: Single call gets all info
# Use HungarianHelper to get optimal pairings: a single call returns matched pairs and scores
hungarian_info = hungarian_helper.get_complete_matching_info(
gt_list, pred_list
)
matched_pairs = hungarian_info["matched_pairs"]

# CRITICAL FIX: Replace raw scores with threshold-applied scores from individual comparison
# Replace raw scores with threshold-applied scores from individual comparison
# This ensures consistency between individual and list comparison results
threshold_corrected_pairs = []
for gt_idx, pred_idx, raw_score in matched_pairs:
Expand All @@ -487,7 +444,7 @@ def compare_unordered_lists(
)
else:
# Use the provided comparator for other types
# CRITICAL FIX: Use match_threshold=0.0 to capture ALL matches, not just those above threshold
# Use match_threshold=0.0 to capture ALL matches, not just those above threshold
# This allows us to keep track of partial matches for scoring.
#
# `0.0` is a capture-all sentinel: only `matched_pairs` is read
Expand Down Expand Up @@ -586,7 +543,7 @@ def unordered_list_metrics(
# Total false positives include both false discoveries and false alarms
fp = fd + fa

# CRITICAL FIX: Use threshold-applied scores for consistency with individual comparison
# Use threshold-applied scores for consistency with individual comparison
# This ensures list comparison matches the same scoring logic as individual comparison
if not matched_pairs:
# Two empty lists agree perfectly: there is nothing to find and
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -726,13 +726,14 @@ def get_comparison_info(cls, field_name: str) -> "ComparableFieldConfig":
"""
field_info = cls.model_fields[field_name]

# NEW HYBRID APPROACH: Try function attribute access first (fixes custom comparators)
# The comparator instance lives as an attribute on the json_schema_extra
# function (set by ComparableField), not on FieldInfo, which cannot hold it.
if hasattr(field_info, "json_schema_extra") and callable(
field_info.json_schema_extra
):
json_func = field_info.json_schema_extra
if hasattr(json_func, "_comparator_instance"):
# Direct instance storage on function - this is the new, reliable approach
# Read the comparator instance directly off the function.
comparator = getattr(json_func, "_comparator_instance")
threshold = getattr(
json_func, "_threshold", _LEGACY_DEFAULT_THRESHOLD
Expand Down
Loading