API Reference
stickler
stickler: Structured object comparison and evaluation library.
This library provides tools for comparing complex structured objects with configurable comparison strategies and detailed evaluation metrics.
stickler.structured_object_evaluator.models.structured_model.StructuredModel
Bases: BaseModel
Base class for models with structured comparison capabilities.
This class extends Pydantic's BaseModel with the ability to compare instances using configurable comparison metrics for each field.
Architecture - Delegation Pattern:
StructuredModel uses a delegation pattern where comparison logic is distributed across specialized helper classes. This refactoring reduced the class from 2584 lines to ~500 lines while maintaining all functionality.
The delegation pattern works as follows: 1. StructuredModel maintains the public API (compare, compare_with, compare_field) 2. All implementation details are delegated to specialized helper classes 3. Each helper class has a single, well-defined responsibility 4. Helpers receive the StructuredModel instance as a parameter (composition) 5. This avoids circular dependencies and keeps the architecture clean
Helper Classes and Their Responsibilities:
Model Creation: - ModelFactory: Creates dynamic StructuredModel subclasses from JSON configuration - Validates configuration structure - Converts field definitions to Pydantic fields - Creates model classes using Pydantic's create_model()
Comparison Orchestration: - ComparisonEngine: Main orchestrator for the comparison process - Coordinates between dispatcher, collectors, and calculators - Implements single-traversal optimization - Manages compare_recursive and compare_with methods
Field Comparison Routing: - ComparisonDispatcher: Routes field comparisons to appropriate handlers - Uses match-statement based dispatch for clarity - Handles null cases and type mismatches - Delegates to specialized comparators based on field type
Field-Level Comparison: - FieldComparator: Compares primitive and structured fields - Handles string, int, float comparisons - Handles nested StructuredModel comparisons - Applies threshold-based binary classification
- PrimitiveListComparator: Compares lists of primitive values
- Uses Hungarian matching for optimal pairing
- Returns hierarchical structure for API consistency
-
Handles empty list cases
-
StructuredListComparator: Compares lists of StructuredModels
- Uses Hungarian matching with object-level similarity
- Performs threshold-gated recursive analysis
- Calculates nested field metrics
Metrics Calculation: - ConfusionMatrixCalculator: Calculates confusion matrix metrics - Computes TP, FP, TN, FN, FD, FA counts - Handles list-level and field-level metrics - Calculates nested field metrics for structured lists
- AggregateMetricsCalculator: Rolls up child metrics to parent nodes
- Performs recursive traversal of result tree
- Sums child aggregate metrics to parent
-
Provides universal field-level granularity
-
DerivedMetricsCalculator: Calculates derived metrics
- Computes precision, recall, F1, accuracy
- Supports both traditional and FD-inclusive recall
-
Delegates to MetricsHelper for calculations
-
ConfusionMatrixBuilder: Orchestrates all metrics calculation
- Coordinates between the three calculator classes
- Ensures correct calculation order
- Builds complete confusion matrices
Non-Match Documentation: - NonMatchCollector: Documents non-matching fields - Collects object-level non-matches for lists - Collects field-level non-matches (legacy format) - Handles nested StructuredModel recursion
Existing Helpers (Pre-Refactoring): - HungarianHelper: Hungarian algorithm for list matching - MetricsHelper: Derived metrics calculation formulas - ConfigurationHelper: Field configuration management - ComparisonHelper: Comparison utility methods - EvaluatorFormatHelper: Output formatting for evaluators - NonMatchesHelper: Non-match collection utilities - FieldHelper: Field type and null checking utilities
Benefits of Delegation Pattern:
- Maintainability: Each class has a single responsibility
- Testability: Components can be tested in isolation
- Extensibility: Easy to add new field types or metrics
- Readability: Clear separation of concerns
- Performance: No overhead - delegation is just function calls
Migration Notes:
- All public APIs remain unchanged (complete backward compatibility)
- All tests pass without modification (80+ test files)
- Performance characteristics maintained (single-traversal optimization)
- No breaking changes for existing users
Features:
- Field-level comparison configuration via ComparableField
- Nested model comparison with recursive evaluation
- Integration with ANLS* comparators
- JSON schema generation with comparison metadata
- Unordered list comparison using Hungarian matching
- Confusion matrix metrics (TP, FP, FN, TN, FA, FD)
- Aggregate metrics rollup from nested fields
- Retention of extra fields not defined in the model
- Dynamic model creation from JSON configuration
- Threshold-gated recursive analysis for performance
Example Usage:
from stickler.structured_object_evaluator.models import StructuredModel from stickler.structured_object_evaluator.models import ComparableField from stickler.comparators import LevenshteinComparator
class Product(StructuredModel): ... name: str = ComparableField( ... comparator=LevenshteinComparator(), ... threshold=0.8, ... weight=2.0 ... ) ... price: float = ComparableField( ... comparator=NumericComparator(), ... threshold=0.9 ... )
gt = Product(name="Widget", price=29.99) pred = Product(name="Widgit", price=29.99) # Typo in name
Simple comparison (returns overall similarity score)
score = gt.compare(pred) print(f"Similarity: {score:.2f}")
Detailed comparison with confusion matrix
result = gt.compare_with(pred, include_confusion_matrix=True) print(f"TP: {result['overall']['tp']}, FD: {result['overall']['fd']}") print(f"F1: {result['aggregate']['derived']['cm_f1']:.2f}")
Source code in stickler/structured_object_evaluator/models/structured_model.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 | |
__init_subclass__(**kwargs)
Validate field configurations when a StructuredModel subclass is defined.
Source code in stickler/structured_object_evaluator/models/structured_model.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
compare(other)
Compare this model with another and return a scalar similarity score.
Returns the overall weighted average score regardless of sufficient/necessary field matching. This provides a more nuanced score for use in comparators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
StructuredModel
|
Another instance of the same model to compare with |
required |
Returns:
| Type | Description |
|---|---|
float
|
Similarity score between 0.0 and 1.0 |
Source code in stickler/structured_object_evaluator/models/structured_model.py
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 | |
compare_field(field_name, other_value)
Compare a single field with a value using the configured comparator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
Name of the field to compare |
required |
other_value
|
Any
|
Value to compare with |
required |
Returns:
| Type | Description |
|---|---|
float
|
Similarity score between 0.0 and 1.0 |
Source code in stickler/structured_object_evaluator/models/structured_model.py
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 | |
compare_field_raw(field_name, other_value)
Compare a single field with a value WITHOUT applying thresholds.
This version is used by the compare method to get raw similarity scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_name
|
str
|
Name of the field to compare |
required |
other_value
|
Any
|
Value to compare with |
required |
Returns:
| Type | Description |
|---|---|
float
|
Raw similarity score between 0.0 and 1.0 without threshold filtering |
Source code in stickler/structured_object_evaluator/models/structured_model.py
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 | |
compare_recursive(other)
The ONE clean recursive function that handles everything.
Enhanced to capture BOTH confusion matrix metrics AND similarity scores in a single traversal to eliminate double traversal inefficiency.
PHASE 2: Delegates to ComparisonEngine while maintaining identical behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
StructuredModel
|
Another instance of the same model to compare with |
required |
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with clean hierarchical structure: |
dict
|
|
dict
|
|
dict
|
|
Source code in stickler/structured_object_evaluator/models/structured_model.py
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 | |
compare_with(other, include_confusion_matrix=False, document_non_matches=False, evaluator_format=False, recall_with_fd=False, add_derived_metrics=True)
Compare this model with another instance using SINGLE TRAVERSAL optimization.
PHASE 2: Delegates to ComparisonEngine while maintaining identical behavior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
StructuredModel
|
Another instance of the same model to compare with |
required |
include_confusion_matrix
|
bool
|
Whether to include confusion matrix calculations |
False
|
document_non_matches
|
bool
|
Whether to document non-matches for analysis |
False
|
evaluator_format
|
bool
|
Whether to format results for the evaluator |
False
|
recall_with_fd
|
bool
|
If True, include FD in recall denominator (TP/(TP+FN+FD)) If False, use traditional recall (TP/(TP+FN)) |
False
|
add_derived_metrics
|
bool
|
Whether to add derived metrics to confusion matrix |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with comparison results including: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Source code in stickler/structured_object_evaluator/models/structured_model.py
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 | |
from_json(json_data)
classmethod
Create a StructuredModel instance from JSON data.
This method handles missing fields gracefully and stores extra fields in the extra_fields attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
json_data
|
Dict[str, Any]
|
Dictionary containing the JSON data |
required |
Returns:
| Type | Description |
|---|---|
StructuredModel
|
StructuredModel instance created from the JSON data |
Source code in stickler/structured_object_evaluator/models/structured_model.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
from_json_schema(schema)
classmethod
Create a StructuredModel subclass from a JSON Schema document.
This method accepts standard JSON Schema documents and creates fully functional StructuredModel classes with comparison capabilities. Supports JSON Schema draft-07+.
Comparison behavior can be customized using x-aws-stickler-* extension fields:
Field-Level Extensions:
- x-aws-stickler-comparator: Comparator algorithm name (built-in or registered custom)
- x-aws-stickler-threshold: Similarity threshold for match/no-match (0.0-1.0, default: 0.5)
- x-aws-stickler-weight: Field importance in overall scoring (>0.0, default: 1.0)
- x-aws-stickler-clip-under-threshold: Clip scores below threshold to 0.0 (bool, default: false)
- x-aws-stickler-aggregate: Include field metrics in parent aggregation (bool, default: false)
Model-Level Extensions:
- x-aws-stickler-model-name: Generated class name (default: "DynamicModel")
- x-aws-stickler-match-threshold: Overall match threshold (default: 0.7)
Supported Features:
- Primitive types: string, number, integer, boolean
- Nested objects and arrays (primitive/object items)
- Required fields, defaults, descriptions
- Schema references ($ref with #/definitions/ and #/$defs/)
Default Type Mappings:
- string → LevenshteinComparator (threshold: 0.5)
- number/integer → NumericComparator (threshold: 0.5)
- boolean → ExactComparator (threshold: 1.0)
- arrays → Hungarian matching with element-appropriate comparators
- objects → Recursive field-by-field comparison
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
Dict[str, Any]
|
JSON Schema document as a dictionary |
required |
Returns:
| Type | Description |
|---|---|
Type[StructuredModel]
|
StructuredModel subclass created from the schema |
Raises:
| Type | Description |
|---|---|
ValueError
|
If schema is invalid or contains unsupported features |
SchemaError
|
If schema doesn't conform to JSON Schema spec |
Examples:
Basic usage with standard JSON Schema:
>>> schema = {
... "type": "object",
... "properties": {
... "name": {"type": "string"},
... "age": {"type": "integer"},
... "email": {"type": "string"}
... },
... "required": ["name", "email"]
... }
>>> PersonModel = StructuredModel.from_json_schema(schema)
>>> person1 = PersonModel(name="Alice", age=30, email="alice@example.com")
>>> person2 = PersonModel(name="Alicia", age=30, email="alice@example.com")
>>> result = person1.compare_with(person2)
>>> # name field uses LevenshteinComparator, age uses NumericComparator
Advanced usage with x-aws-stickler-* extensions:
>>> schema = {
... "type": "object",
... "x-aws-stickler-model-name": "Product",
... "x-aws-stickler-match-threshold": 0.8,
... "properties": {
... "name": {
... "type": "string",
... "x-aws-stickler-comparator": "LevenshteinComparator",
... "x-aws-stickler-threshold": 0.9,
... "x-aws-stickler-weight": 2.0,
... "x-aws-stickler-aggregate": true
... },
... "price": {
... "type": "number",
... "x-aws-stickler-comparator": "NumericComparator",
... "x-aws-stickler-threshold": 0.95,
... "x-aws-stickler-clip-under-threshold": true
... }
... },
... "required": ["name"]
... }
>>> ProductModel = StructuredModel.from_json_schema(schema)
>>> result = product1.compare_with(product2)
>>> # name field has weight=2.0, price field clips scores below 0.95
Source code in stickler/structured_object_evaluator/models/structured_model.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
model_from_json(config)
classmethod
Create a StructuredModel subclass from JSON configuration using Pydantic's create_model().
This method leverages Pydantic's native dynamic model creation capabilities to ensure full compatibility with all Pydantic features while adding structured comparison functionality through inherited StructuredModel methods.
The generated model inherits all StructuredModel capabilities: - compare_with() method for detailed comparisons - Field-level comparison configuration - Hungarian algorithm for list matching - Confusion matrix generation - JSON schema with comparison metadata
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Dict[str, Any]
|
JSON configuration with fields, comparators, and model settings. Required keys: - fields: Dict mapping field names to field configurations Optional keys: - model_name: Name for the generated class (default: "DynamicModel") - match_threshold: Overall matching threshold (default: 0.7) Field configuration format: { "type": "str|int|float|bool|List[str]|etc.", # Required "comparator": "LevenshteinComparator|ExactComparator|etc.", # Optional "threshold": 0.8, # Optional, default 0.5 "weight": 2.0, # Optional, default 1.0 "required": true, # Optional, default false "default": "value", # Optional "description": "Field description", # Optional "alias": "field_alias", # Optional "examples": ["example1", "example2"] # Optional } |
required |
Returns:
| Type | Description |
|---|---|
Type[StructuredModel]
|
A fully functional StructuredModel subclass created with create_model() |
Raises:
| Type | Description |
|---|---|
ValueError
|
If configuration is invalid or contains unsupported types/comparators |
KeyError
|
If required configuration keys are missing |
Examples:
>>> config = {
... "model_name": "Product",
... "match_threshold": 0.8,
... "fields": {
... "name": {
... "type": "str",
... "comparator": "LevenshteinComparator",
... "threshold": 0.8,
... "weight": 2.0,
... "required": True
... },
... "price": {
... "type": "float",
... "comparator": "NumericComparator",
... "default": 0.0
... }
... }
... }
>>> ProductClass = StructuredModel.model_from_json(config)
>>> isinstance(ProductClass.model_fields, dict) # Full Pydantic compatibility
True
>>> product = ProductClass(name="Widget", price=29.99)
>>> product.name
'Widget'
>>> result = product.compare_with(ProductClass(name="Widget", price=29.99))
>>> result["overall_score"]
1.0
Source code in stickler/structured_object_evaluator/models/structured_model.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
model_json_schema(**kwargs)
classmethod
Override to add model-level comparison metadata.
Extends the standard Pydantic JSON schema with comparison metadata at the field level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Arguments to pass to the parent method |
{}
|
Returns:
| Type | Description |
|---|---|
|
JSON schema with added comparison metadata |
Source code in stickler/structured_object_evaluator/models/structured_model.py
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 | |
stickler.structured_object_evaluator.models.comparable_field.ComparableField(comparator=None, threshold=0.5, weight=1.0, default=None, aggregate=False, clip_under_threshold=True, alias=None, description=None, examples=None, **field_kwargs)
Create a Pydantic Field with comparison metadata.
This function creates a proper Pydantic Field with embedded comparison configuration, enabling both comparison functionality and native Pydantic features like aliases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comparator
|
Optional[BaseComparator]
|
Comparator to use for field comparison (default: LevenshteinComparator) |
None
|
threshold
|
float
|
Minimum similarity score to consider a match (default: 0.5) |
0.5
|
weight
|
float
|
Weight of this field in overall score calculation (default: 1.0) |
1.0
|
default
|
Any
|
Default value for the field (default: None) |
None
|
aggregate
|
bool
|
DEPRECATED - This parameter is deprecated and will be removed in a future version. Use the new universal 'aggregate' field in compare_with() output instead. |
False
|
clip_under_threshold
|
bool
|
Whether to zero out scores below threshold (default: True) |
True
|
alias
|
Optional[str]
|
Pydantic field alias for serialization (default: None) |
None
|
description
|
Optional[str]
|
Field description for documentation (default: None) |
None
|
examples
|
Optional[list]
|
Example values for the field (default: None) |
None
|
**field_kwargs
|
Additional Pydantic Field arguments |
{}
|
Returns:
| Type | Description |
|---|---|
|
Pydantic Field with embedded comparison metadata |
Example
class MyModel(StructuredModel): # Basic usage (no alias): name: str = ComparableField(threshold=0.8)
# With alias (new feature):
email: str = ComparableField(
threshold=0.9,
alias="email_address",
description="User's email",
examples=["user@example.com"]
)
Source code in stickler/structured_object_evaluator/models/comparable_field.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
stickler.structured_object_evaluator.models.non_match_field.NonMatchField
Bases: BaseModel
Model for documenting non-matches in structured object evaluation.
This class stores detailed information about each non-match detected during the evaluation process, enabling more thorough analysis and debugging of evaluation results.
Source code in stickler/structured_object_evaluator/models/non_match_field.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
__str__()
Return a string representation of the non-match document.
Source code in stickler/structured_object_evaluator/models/non_match_field.py
47 48 49 50 51 52 53 54 55 56 57 58 59 | |
export_to_dict(documents)
staticmethod
Export a list of non-match documents to a dictionary for serialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
List[NonMatchField]
|
List of NonMatchField instances |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, List[Dict[str, Any]]]
|
Dictionary with categorized non-matches |
Source code in stickler/structured_object_evaluator/models/non_match_field.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
export_to_json(documents, output_path)
staticmethod
Export a list of non-match documents to a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
List[NonMatchField]
|
List of NonMatchField instances |
required |
output_path
|
str
|
Path to save the JSON file |
required |
Source code in stickler/structured_object_evaluator/models/non_match_field.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
filter_by_type(documents, match_type)
staticmethod
Filter non-match documents by their type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
List[NonMatchField]
|
List of NonMatchField instances to filter |
required |
match_type
|
NonMatchType
|
Type of non-match to filter for |
required |
Returns:
| Type | Description |
|---|---|
List[NonMatchField]
|
Filtered list of NonMatchField instances |
Source code in stickler/structured_object_evaluator/models/non_match_field.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
print_summary(documents, detailed=False)
staticmethod
Print a summary of non-match documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
List[NonMatchField]
|
List of NonMatchField instances |
required |
detailed
|
bool
|
Whether to print detailed information for each document |
False
|
Source code in stickler/structured_object_evaluator/models/non_match_field.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | |
stickler.structured_object_evaluator.models.non_match_field.NonMatchType
Bases: str, Enum
Enum defining the types of non-matches.
Source code in stickler/structured_object_evaluator/models/non_match_field.py
15 16 17 18 19 20 | |
stickler.structured_object_evaluator.evaluator.StructuredModelEvaluator
Evaluator for StructuredModel objects.
This evaluator computes comprehensive metrics for StructuredModel objects, leveraging their built-in comparison capabilities. It includes confusion matrix calculations, field-level metrics, non-match documentation, and memory optimization capabilities.
Source code in stickler/structured_object_evaluator/evaluator.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 | |
__init__(model_class=None, threshold=0.5, verbose=False, document_non_matches=True, recall_with_fd=False)
Initialize the evaluator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
Optional[Type[StructuredModel]]
|
Optional StructuredModel class for type checking |
None
|
threshold
|
float
|
Similarity threshold for considering a match |
0.5
|
verbose
|
bool
|
Whether to print detailed progress information |
False
|
document_non_matches
|
bool
|
Whether to document detailed non-match information |
True
|
Source code in stickler/structured_object_evaluator/evaluator.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
add_non_match(field_path, non_match_type, gt_value, pred_value, similarity_score=None, details=None)
Document a non-match with detailed information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field_path
|
str
|
Dot-notation path to the field (e.g., 'address.city') |
required |
non_match_type
|
NonMatchType
|
Type of non-match |
required |
gt_value
|
Any
|
Ground truth value |
required |
pred_value
|
Any
|
Predicted value |
required |
similarity_score
|
Optional[float]
|
Optional similarity score if available |
None
|
details
|
Optional[Dict[str, Any]]
|
Optional additional context or details |
None
|
document_id
|
Optional ID of the document this non-match belongs to |
required |
Source code in stickler/structured_object_evaluator/evaluator.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
calculate_derived_confusion_matrix_metrics(cm_counts)
Calculate derived metrics from confusion matrix counts.
This method uses MetricsHelper to maintain consistency and avoid code duplication.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cm_counts
|
Dict[str, Union[int, float]]
|
Dictionary with confusion matrix counts containing keys: 'tp', 'fp', 'tn', 'fn', and optionally 'fd', 'fa' |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
Dictionary with derived metrics: cm_precision, cm_recall, cm_f1, cm_accuracy |
Source code in stickler/structured_object_evaluator/evaluator.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
clear_non_match_documents()
Clear the stored non-match documents.
Source code in stickler/structured_object_evaluator/evaluator.py
292 293 294 | |
combine_cm_dicts(cm1, cm2)
Combine two confusion matrix dictionaries by adding corresponding values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cm1
|
Dict[str, int]
|
First confusion matrix dictionary |
required |
cm2
|
Dict[str, int]
|
Second confusion matrix dictionary |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, int]
|
Combined confusion matrix dictionary |
Source code in stickler/structured_object_evaluator/evaluator.py
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | |
evaluate(ground_truth, predictions, recall_with_fd=False)
Evaluate predictions against ground truth and return comprehensive metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ground_truth
|
StructuredModel
|
Ground truth data (StructuredModel instance) |
required |
predictions
|
StructuredModel
|
Predicted data (StructuredModel instance) |
required |
recall_with_fd
|
bool
|
If True, include FD in recall denominator (TP/(TP+FN+FD)) If False, use traditional recall (TP/(TP+FN)) |
False
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with the following structure: |
Dict[str, Any]
|
{ "overall": { "precision": float, # Overall precision [0-1] "recall": float, # Overall recall [0-1] "f1": float, # Overall F1 score [0-1] "accuracy": float, # Overall accuracy [0-1] "anls_score": float # Overall ANLS similarity score [0-1] }, "fields": {
" }, "confusion_matrix": {
"fields": {
# AGGREGATED metrics for all field types
" } |
Dict[str, Any]
|
} |
Key Usage Patterns:
-
Individual Item Metrics (per-instance analysis):
# Access metrics for each individual item in a list for i, item_metrics in enumerate(results['fields']['products']['items']): print(f"Product {i}: {item_metrics['overall']['f1']}") -
Aggregated Field Metrics (recommended for field performance analysis):
# Access aggregated metrics across all instances of a field type cm_fields = results['confusion_matrix']['fields'] product_id_performance = cm_fields['products.product_id'] print(f"Product ID field: {product_id_performance['derived']['cm_precision']}") # Get all aggregated product field metrics product_fields = {k: v for k, v in cm_fields.items() if k.startswith('products.')} -
Helper Function for Aggregated Metrics:
def get_aggregated_metrics(results, list_field_name): '''Extract aggregated field metrics for a list field.''' cm_fields = results['confusion_matrix']['fields'] prefix = f"{list_field_name}." return {k.replace(prefix, ''): v for k, v in cm_fields.items() if k.startswith(prefix)} # Usage: product_metrics = get_aggregated_metrics(results, 'products') print(f"Product name precision: {product_metrics['name']['derived']['cm_precision']}")
Note
- Use
results['fields'][field]['items']for per-instance analysis - Use
results['confusion_matrix']['fields'][field.subfield]for aggregated field analysis - Aggregated metrics provide rolled-up performance across all instances of a field type
- Confusion matrix metrics use standard TP/FP/TN/FN/FD classification with derived metrics
Source code in stickler/structured_object_evaluator/evaluator.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 | |
stickler.structured_object_evaluator.utils.anls_score.compare_structured_models(gt, pred)
Compare a ground truth model with a prediction.
This function wraps the compare_with method of StructuredModel for a more explicit API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt
|
StructuredModel
|
Ground truth model |
required |
pred
|
StructuredModel
|
Prediction model |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Comparison result dictionary |
Source code in stickler/structured_object_evaluator/utils/anls_score.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
stickler.structured_object_evaluator.utils.anls_score.anls_score(gt, pred, return_gt=False, return_key_scores=False)
Calculate ANLS* score between two objects.
This function provides a simple API for getting an ANLS* score between any two objects, similar to the original anls_score function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt
|
Any
|
Ground truth object |
required |
pred
|
Any
|
Prediction object |
required |
return_gt
|
bool
|
Whether to return the closest ground truth |
False
|
return_key_scores
|
bool
|
Whether to return detailed key scores |
False
|
Returns:
| Type | Description |
|---|---|
Union[float, Tuple[float, Any], Tuple[float, Any, Dict[str, Any]]]
|
Either just the overall score (float), or a tuple with the score and |
Union[float, Tuple[float, Any], Tuple[float, Any, Dict[str, Any]]]
|
closest ground truth, or a tuple with the score, closest ground truth, |
Union[float, Tuple[float, Any], Tuple[float, Any, Dict[str, Any]]]
|
and key scores. |
Source code in stickler/structured_object_evaluator/utils/anls_score.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | |
stickler.structured_object_evaluator.utils.compare_json.compare_json(gt_json, pred_json, model_cls)
Compare JSON objects using a StructuredModel.
This function is a utility for comparing raw JSON objects using a StructuredModel class. It handles missing fields and extra fields gracefully.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gt_json
|
Dict[str, Any]
|
Ground truth JSON |
required |
pred_json
|
Dict[str, Any]
|
Prediction JSON |
required |
model_cls
|
Type[StructuredModel]
|
StructuredModel class to use for comparison |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with comparison results |
Source code in stickler/structured_object_evaluator/utils/compare_json.py
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |