Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ Each release links to full notes on the

### Added

- `AngleComparator`, which compares angles such as heading or yaw by their
shortest difference around the circle, so `359` and `1` are 2 degrees apart.
It scores 1.0 within `max_angular_difference` and 0.0 beyond it, in
`angle_unit` `"degrees"` (default) or `"radians"`. Invalid configuration
raises `ValueError`; a non-numeric or infinite angle scores 0.0.
- `PointDistanceComparator` scores two 2D or 3D points by Euclidean distance,
`max(0.0, 1.0 - distance / max_distance)`. Positions scored as separate `x`,
`y` and `z` fields under `NumericComparator(absolute_tolerance=...)` gate on
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@ Omitting it is safe but blunt. The fallback reads structure and never field name
| `"LevenshteinComparator"` | Names, addresses, text with typos | Calculates edit distance between strings. Score = 1 - (edits / max_length) |
| `"ExactComparator"` | IDs, codes, booleans, exact matches | Returns 1.0 for exact match, 0.0 otherwise |
| `"NumericComparator"` | Prices, quantities, measurements | Compares numbers with configurable tolerance |
| `"AngleComparator"` | Heading, yaw, orientation | Matches when the shortest difference around the circle is within `max_angular_difference` |
| `"FuzzyComparator"` | Flexible text, descriptions | Token-based fuzzy matching (order-independent) |
| `"SemanticComparator"` | Semantic similarity | Embedding-based comparison for meaning |
| `"BERTComparator"` | Deep semantic understanding | BERT model for contextual similarity. Needs the `[bert]` extra |
Expand Down
4 changes: 4 additions & 0 deletions docs/docs/API-Reference/comparators.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@
options:
heading_level: 2

::: stickler.comparators.AngleComparator
options:
heading_level: 2

::: stickler.comparators.DateComparator
options:
heading_level: 2
Expand Down
27 changes: 27 additions & 0 deletions docs/docs/Guides/Comparators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ See [Thresholds and Metrics](../../Getting-Started/thresholds-and-metrics.md) fo
| [**NormalizedComparator**](#normalizedcomparator) | Text where formatting differences are noise | Instant | No | Binary (0.0 or 1.0) |
| [**LevenshteinComparator**](#levenshteincomparator) | Names, addresses, text with typos | Instant | No | Continuous (0.0--1.0) |
| [**NumericComparator**](#numericcomparator) | Prices, quantities, measurements | Instant | No | Binary (0.0 or 1.0) |
| [**AngleComparator**](#anglecomparator) | Heading, yaw, orientation | Instant | No | Binary (0.0 or 1.0) |
| [**DateComparator**](date-comparator.md) | Date fields with mixed formats, partial dates, ranges | Instant | No | Continuous (0.0--1.0) |
| [**FuzzyComparator**](#fuzzycomparator) | Flexible text, descriptions, reordered tokens | Fast | No | Continuous (0.0--1.0) |
| [**BBoxIoUComparator**](#bboxioucomparator) | Bounding boxes, spatial localization | Instant | No | Continuous (0.0--1.0) |
Expand Down Expand Up @@ -169,6 +170,32 @@ class Invoice(StructuredModel):

---

### AngleComparator

Compares two angles by their shortest difference around the circle, so `359` and `1` are 2 degrees apart. Returns 1.0 if that difference is at most `max_angular_difference`, 0.0 otherwise. Strings, booleans, `Decimal` and infinite values score 0.0.

**When to use:** Heading, yaw or any orientation field, alone or in a `List[float]`.

```python
from stickler import StructuredModel, ComparableField
from stickler import AngleComparator

class Pose(StructuredModel):
yaw: float = ComparableField(
comparator=AngleComparator(max_angular_difference=5)
)
```

**Key parameters:**

| Parameter | Default | Description |
|---|---|---|
| `threshold` | `1.0` | Similarity threshold for binary classification |
| `max_angular_difference` | `0.0` | Largest difference that matches, in `angle_unit`; must be less than half a turn |
| `angle_unit` | `"degrees"` | `"degrees"` or `"radians"`, for inputs and tolerance |

---

### DateComparator

Parses both sides as dates (or date ranges) using `python-dateutil`, then scores the comparison on a tier system: same calendar day after surface-form normalization is `1.0`, partial information (year-less, range-vs-single) is configurable, anything else is `0.0`. Handles ISO/named-month/slash formats, two-digit years, day-of-week prefixes, and timezone-aware datetimes.
Expand Down
2 changes: 2 additions & 0 deletions src/stickler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# Zero-config evaluation of vanilla pydantic models (no StructuredModel
# subclass or schema required). See stickler/auto/README.md.
from .auto import EvalResult, EvalSpec, eval_for, evaluate
from .comparators.angle import AngleComparator
from .comparators.anls import ANLSStarComparator

# Always-available comparators (core deps)
Expand Down Expand Up @@ -159,6 +160,7 @@ def __dir__() -> list:
# Comparators (always available)
"BaseComparator",
"ANLSStarComparator",
"AngleComparator",
"ExactComparator",
"PhoneComparator",
"DateComparator",
Expand Down
9 changes: 9 additions & 0 deletions src/stickler/comparators/Comparators.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ comparator = NumericComparator()
- Reads decimal digits in other scripts in string values (`١٢٥٠` equals `1250`)
- Ideal for financial data or measurement comparisons

#### Angle Comparator
```python
comparator = AngleComparator(max_angular_difference=5, angle_unit="degrees")
```
- Compares angles by the shortest difference around the circle (`359` vs `1` is 2)
- Binary: 1.0 within `max_angular_difference`, 0.0 beyond it
- Invalid unit or a tolerance outside `[0, half turn)` raises `ValueError`

#### Date Comparator
```python
comparator = DateComparator()
Expand Down Expand Up @@ -163,6 +171,7 @@ comparator = PointDistanceComparator(max_distance=10.0, threshold=0.5)
- Use semantic comparators (BERT/Semantic) for meaning-based comparison
- Use LevenshteinComparator for simple edit distance-based matching
- Use NumericComparator for number comparisons
- Use AngleComparator for headings and other angles that wrap around
- Use BBoxIoUComparator for bounding-box / spatial localization comparisons
- Use PointDistanceComparator for 2D or 3D positions

Expand Down
3 changes: 3 additions & 0 deletions src/stickler/comparators/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,6 @@ field annotation names sequence elements (`List[List[float]]`).
`PointDistanceComparator` requires `max_distance` and has no default for it, so its `config`
always carries `max_distance`. That lets an exported list-of-points field import again. A
single `Tuple` point field still exports as a string type and does not round-trip.

`AngleComparator` scores two angles by their shortest difference around the
circle, using `math.remainder` over a full turn in the configured unit.
2 changes: 2 additions & 0 deletions src/stickler/comparators/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import importlib.util as _ilu
import sys as _sys

from stickler.comparators.angle import AngleComparator
from stickler.comparators.anls import ANLSStarComparator
from stickler.comparators.base import BaseComparator
from stickler.comparators.bbox import BBoxIoUComparator
Expand Down Expand Up @@ -121,6 +122,7 @@ def __dir__() -> list:
"NumericExactC",
"ExactComparator",
"ANLSStarComparator",
"AngleComparator",
"PhoneComparator",
"DateComparator",
"StructuredModelComparator",
Expand Down
126 changes: 126 additions & 0 deletions src/stickler/comparators/angle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""Angle comparator that measures the shortest difference around the circle."""

import math
from numbers import Real
from typing import Any, Dict, Optional

from stickler.comparators.base import BaseComparator

_FULL_TURN = {"degrees": 360.0, "radians": 2 * math.pi}


class AngleComparator(BaseComparator):
"""Comparator for angles such as heading or yaw, with wraparound.

Two angles match when their shortest angular difference is at most
``max_angular_difference``, so ``359`` and ``1`` are 2 degrees apart, not
358. Any multiple of a full turn is the same angle: ``-90``, ``270`` and
``630`` all match. The score is binary, as for ``NumericComparator``:
1.0 within the tolerance, 0.0 beyond it.

Inputs must be finite ``numbers.Real`` values, such as ``int``, ``float``
or a NumPy float. A string, a boolean, a ``Decimal`` or an infinite value
is malformed and scores 0.0. A float NaN counts as missing, as for every
comparator.

Args:
threshold: Similarity threshold (default 1.0).
max_angular_difference: Largest shortest difference that still
matches, in ``angle_unit`` (default 0.0, exact). Must be at least
0 and less than half a turn, because half a turn would match
every pair.
angle_unit: ``"degrees"`` (default) or ``"radians"``, for both the
inputs and ``max_angular_difference``.

Raises:
ValueError: If ``angle_unit`` or ``max_angular_difference`` is
invalid.

Example:
>>> from stickler.comparators import AngleComparator
>>> heading = AngleComparator(max_angular_difference=5)
>>> heading.compare(359, 1)
1.0
>>> heading.compare(0, 180)
0.0
"""

DEFAULT_THRESHOLD = 1.0

def __init__(
self,
threshold: Optional[float] = None,
max_angular_difference: float = 0.0,
angle_unit: str = "degrees",
):
super().__init__(threshold=threshold)
if angle_unit not in _FULL_TURN:
raise ValueError(
f"angle_unit must be 'degrees' or 'radians', got {angle_unit!r}"
)
half_turn = _FULL_TURN[angle_unit] / 2
tolerance = _finite_float(max_angular_difference)
if tolerance is None or not 0 <= tolerance < half_turn:
# A tolerance of half a turn or more matches every pair, which is
# usually a value in degrees passed with angle_unit="radians".
raise ValueError(
f"max_angular_difference must be at least 0 and less than "
f"{half_turn:g} {angle_unit}, got {max_angular_difference!r}"
)
# A float, not a NumPy scalar, so the exported schema stays JSON.
self.max_angular_difference = tolerance
self.angle_unit = angle_unit

@property
def config(self) -> Optional[Dict[str, Any]]:
"""Return the non-default configuration for serialization."""
config: Dict[str, Any] = {}
if self.max_angular_difference != 0.0:
config["max_angular_difference"] = self.max_angular_difference
if self.angle_unit != "degrees":
config["angle_unit"] = self.angle_unit
return config or None

def _compare(self, angle1: Any, angle2: Any) -> float:
"""Return 1.0 if the angles are within tolerance, 0.0 otherwise."""
# Imported here, as in BaseComparator.binary_compare, so this module
# has no import-time dependency on the evaluator package.
from stickler.structured_object_evaluator.models.threshold_helper import (
ThresholdHelper,
)

float1 = _finite_float(angle1)
float2 = _finite_float(angle2)
if float1 is None or float2 is None:
return 0.0
# Reducing each angle to one turn first keeps the subtraction finite
# and exact for large inputs. The outer remainder() maps the
# difference into [-half turn, half turn], so its magnitude is the
# shortest way around the circle.
full_turn = _FULL_TURN[self.angle_unit]
difference = abs(
# requires-python is >=3.10, so math.remainder (3.7+) is always present.
# nosemgrep: python.lang.compatibility.python37.python37-compatibility-math1
math.remainder(
# nosemgrep: python.lang.compatibility.python37.python37-compatibility-math1
math.remainder(float1, full_turn) - math.remainder(float2, full_turn),
full_turn,
)
Comment on lines +104 to +108

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.

Blocker (high): these math.remainder calls make the required security (3.12) check fail.

Semgrep rule python.lang.compatibility.python37.python37-compatibility-math1 reports 3 findings here: the outer call (lines 102-105) and both inner calls (line 103). They are false positives, because pyproject.toml sets requires-python = ">=3.10" and math.remainder exists from 3.7. ASH still fails at its MEDIUM threshold:

semgrep      │ 3 │ 3 │ 0 │ 0 │ 0    │ 0 │ 23.1s │ 3      │ FAILED  │ MED (g) │
ERROR (2) Exiting due to 3 actionable findings found in ASH scan

(run 45744687421). I reproduced it locally: uvx semgrep --metrics=off --config r/python.lang.compatibility.python37.python37-compatibility-math1 angle.py gives Ran 1 rule on 1 file: 3 findings. security (3.12) is in the dev ruleset's required status checks, so this PR cannot merge as it stands.

Fix: suppress it with # nosemgrep: and a reason, as the repo already does for the non-literal-import false positives (comparator_registry.py:114). It needs a comment above line 102 and one above line 103. One comment does not cover the inner calls. With both comments, the same semgrep command gives 0 findings:

            # requires-python is >=3.10, so math.remainder (3.7+) is always present.
            # nosemgrep: python.lang.compatibility.python37.python37-compatibility-math1
            math.remainder(
                # nosemgrep: python.lang.compatibility.python37.python37-compatibility-math1
                math.remainder(float1, full_turn) - math.remainder(float2, full_turn),

Changing the inner calls to math.fmod, as the scanner suggests, does not clear the scan, because the outer remainder is still flagged.

)
# The same float tolerance as a threshold check, so 359.9 against 0.1
# meets a tolerance of 0.2.
within = ThresholdHelper.is_above_threshold(
self.max_angular_difference, difference
)
return 1.0 if within else 0.0


def _finite_float(value: Any) -> Optional[float]:
"""The value as a finite float, or None for a non-real, bool or overflow."""
if not isinstance(value, Real) or isinstance(value, bool):
return None
try:
number = float(value)
except OverflowError:
return None
return number if math.isfinite(number) else None
7 changes: 4 additions & 3 deletions src/stickler/structured_object_evaluator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,9 +273,9 @@ not the rest of the entry.
Comparator names accepted by `x-aws-stickler-comparator` are the registered class names:
`LevenshteinComparator`, `ExactComparator`, `NormalizedComparator`, `PhoneComparator`,
`NumericComparator`, `DateComparator`, `FuzzyComparator`, `StructuredModelComparator`,
`ANLSStarComparator`, `BBoxIoUComparator`, `PointDistanceComparator`, `SemanticComparator`,
plus `BERTComparator` and `LLMComparator`, which need the `[bert]` and `[llm]` extras. Without
the extra those two are not registered, so naming one raises `ValueError: Invalid
`ANLSStarComparator`, `AngleComparator`, `BBoxIoUComparator`, `PointDistanceComparator`,
`SemanticComparator`, plus `BERTComparator` and `LLMComparator`, which need the `[bert]` and `[llm]`
extras. Without the extra those two are not registered, so naming one raises `ValueError: Invalid
x-aws-stickler-comparator 'BERTComparator' ...` and the name is absent from the "Available" list
the message prints.

Expand Down Expand Up @@ -377,6 +377,7 @@ Available comparators:
- `ExactComparator`: Exact match comparison
- `FuzzyComparator`: Token-based fuzzy matching, order-independent
- `NumericComparator`: Numeric comparison with tolerance
- `AngleComparator`: Angle comparison with wraparound, such as heading or yaw
- `DateComparator`: Date comparison across formats
- `PhoneComparator`: Phone-number comparison, normalizing formatting
- `SemanticComparator`: Semantic similarity using embeddings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class ComparatorRegistry:
"FuzzyComparator": ("stickler.comparators.fuzzy", None, None),
"StructuredModelComparator": ("stickler.comparators.structured", None, None),
"ANLSStarComparator": ("stickler.comparators.anls", None, None),
"AngleComparator": ("stickler.comparators.angle", None, None),
"BBoxIoUComparator": ("stickler.comparators.bbox", None, None),
"PointDistanceComparator": ("stickler.comparators.point_distance", None, None),
"SemanticComparator": ("stickler.comparators.semantic", None, None),
Expand Down
Loading