From ad19ac845dd22c03f151d52000f9e69abff38f52 Mon Sep 17 00:00:00 2001 From: Yashvardhan Thanvi Date: Thu, 15 Oct 2026 12:33:36 +0530 Subject: [PATCH] refactor(296): remove the dead ConfusionMatrixCalculator methods calculate_list_confusion_matrix, calculate_nested_field_metrics and calculate_single_nested_field_metrics only called each other, and their only way in was three StructuredModel wrappers that nothing calls. All six had zero executed lines across the full suite. Remove them, the HungarianHelper, NonMatchesHelper and List imports that only they used, and the refactoring notes that listed the wrappers. StructuredListComparator._calculate_nested_field_metrics is a separate, live method with the same name and is untouched. So are ConfusionMatrixCalculator.__init__, classify_field_for_confusion_matrix and StructuredModel._classify_field_for_confusion_matrix, which StructuredListComparator calls. The 1e-10 threshold window that algorithms/README.md and the HungarianMatcher.calculate_metrics docstring attribute to ConfusionMatrixCalculator lived in the deleted calculate_nested_field_metrics. The method that remains compares with a bare >=, so both now name only ThresholdHelper and ComparisonHelper. Also run ruff format on the calculator file, which only strips the trailing whitespace from 9 blank docstring lines. Closes #296 --- docs/structured_model_REFACTORING.md | 5 +- src/stickler/algorithms/README.md | 6 +- src/stickler/algorithms/hungarian.py | 9 +- .../models/confusion_matrix_calculator.py | 555 +----------------- .../models/structured_model.py | 80 --- 5 files changed, 19 insertions(+), 636 deletions(-) diff --git a/docs/structured_model_REFACTORING.md b/docs/structured_model_REFACTORING.md index fafc08f4..07019f5b 100644 --- a/docs/structured_model_REFACTORING.md +++ b/docs/structured_model_REFACTORING.md @@ -156,7 +156,7 @@ class StructuredModel(BaseModel): ### Legacy private methods are kept as delegating shims -Older callers (and many tests) reach for private methods on `StructuredModel` such as `_dispatch_field_comparison`, `compare_recursive`, `_calculate_list_confusion_matrix`, `_calculate_nested_field_metrics`, `_collect_enhanced_non_matches`, `_add_derived_metrics_to_result`, `_format_for_evaluator`, etc. These were **not removed** — they now exist as one-line wrappers that build the appropriate component and forward the call. They are retained for backward compatibility; new code should call the component directly. +Older callers (and many tests) reach for private methods on `StructuredModel` such as `_dispatch_field_comparison`, `compare_recursive`, `_collect_enhanced_non_matches`, `_add_derived_metrics_to_result`, `_format_for_evaluator`, etc. These were **not removed** — they now exist as one-line wrappers that build the appropriate component and forward the call. They are retained for backward compatibility; new code should call the component directly. ## Component Responsibilities @@ -375,9 +375,6 @@ These methods still exist on `StructuredModel` as thin delegating shims for back | `compare_recursive` | `ComparisonEngine.compare_recursive` | | `compare_with` | `ComparisonEngine.compare_with` | | `_classify_field_for_confusion_matrix`| `ConfusionMatrixCalculator.classify_field_for_confusion_matrix` | -| `_calculate_list_confusion_matrix` | `ConfusionMatrixCalculator.calculate_list_confusion_matrix` | -| `_calculate_nested_field_metrics` | `ConfusionMatrixCalculator.calculate_nested_field_metrics` | -| `_calculate_single_nested_field_metrics` | `ConfusionMatrixCalculator.calculate_single_nested_field_metrics` | | `_add_derived_metrics_to_result` | `DerivedMetricsCalculator.add_derived_metrics_to_result` | | `_collect_enhanced_non_matches` | `NonMatchCollector.collect_enhanced_non_matches` | | `_format_for_evaluator` | `EvaluatorFormatHelper.format_for_evaluator` | diff --git a/src/stickler/algorithms/README.md b/src/stickler/algorithms/README.md index c4e13e4d..dd4aeceb 100644 --- a/src/stickler/algorithms/README.md +++ b/src/stickler/algorithms/README.md @@ -71,9 +71,9 @@ 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. +**The threshold test here is exact.** `ThresholdHelper` and `ComparisonHelper` +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 diff --git a/src/stickler/algorithms/hungarian.py b/src/stickler/algorithms/hungarian.py index d0b93c51..63f81934 100644 --- a/src/stickler/algorithms/hungarian.py +++ b/src/stickler/algorithms/hungarian.py @@ -288,11 +288,10 @@ def calculate_metrics(self, list1: Any, list2: Any) -> dict: other convention, so the same counts read lower here than they do as ``cm_recall`` there. - The threshold test here is a bare ``>=``. ``ThresholdHelper``, - ``ComparisonHelper`` and ``ConfusionMatrixCalculator`` use a - tolerant test that accepts a score up to ``1e-10`` under the - threshold, so a score inside that window is a TP there and an FD - here. + The threshold test here is a bare ``>=``. ``ThresholdHelper`` and + ``ComparisonHelper`` use a tolerant test that accepts a score up + to ``1e-10`` under the threshold, so a score inside that window is + a TP there and an FD here. ``match_threshold=0.0`` is used elsewhere as a capture all sentinel. Every score satisfies ``>= 0.0``, so ``tp`` then counts diff --git a/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py b/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py index fa5a1ad1..09765c3a 100644 --- a/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py +++ b/src/stickler/structured_object_evaluator/models/confusion_matrix_calculator.py @@ -4,12 +4,10 @@ confusion matrix metrics (TP, FP, TN, FN, FD, FA) for field comparisons. """ -from typing import TYPE_CHECKING, Any, Dict, List +from typing import TYPE_CHECKING, Any, Dict from .field_helper import FieldHelper -from .hungarian_helper import HungarianHelper from .metrics_helper import MetricsHelper -from .non_matches_helper import NonMatchesHelper if TYPE_CHECKING: from .structured_model import StructuredModel @@ -17,169 +15,46 @@ class ConfusionMatrixCalculator: """Calculates confusion matrix metrics for field comparisons. - + This class is responsible for computing confusion matrix statistics (True Positives, False Positives, True Negatives, False Negatives, - False Discoveries, False Alarms) for individual fields and lists of - structured models. - + False Discoveries, False Alarms) for individual fields. + Attributes: model: The ground truth StructuredModel instance used for comparison """ def __init__(self, model: "StructuredModel"): """Initialize calculator with the ground truth model. - + Args: model: The ground truth StructuredModel instance """ self.model = model - def calculate_list_confusion_matrix( - self, field_name: str, other_list: List[Any] - ) -> Dict[str, Any]: - """Calculate confusion matrix for a list field. - - This method computes confusion matrix metrics for a list field, - including nested field metrics for List[StructuredModel] fields. - It uses Hungarian matching for optimal pairing of list elements. - - Args: - field_name: Name of the list field being compared - other_list: Predicted list to compare with - - Returns: - Dictionary with: - - Top-level TP, FP, TN, FN, FD, FA counts and derived metrics - - nested_fields: Dict with metrics for individual fields within list items - - non_matches: List of individual object-level non-matches - - Example: - >>> calculator = ConfusionMatrixCalculator(gt_model) - >>> result = calculator.calculate_list_confusion_matrix("items", pred_list) - >>> print(result["tp"], result["fn"]) - """ - # Import here to avoid circular imports - from .structured_model import StructuredModel - - gt_list = getattr(self.model, field_name) - pred_list = other_list - - # Initialize result structure - result = { - "tp": 0, - "fa": 0, - "fd": 0, - "fp": 0, - "tn": 0, - "fn": 0, - "nested_fields": {}, # Store nested field metrics here - "non_matches": [], # Store individual object-level non-matches here - } - - # Handle null cases first - if FieldHelper.is_null_value(gt_list) and FieldHelper.is_null_value(pred_list): - result.update({"tp": 0, "fa": 0, "fd": 0, "fp": 0, "tn": 1, "fn": 0}) - elif FieldHelper.is_null_value(gt_list): - result.update( - { - "tp": 0, - "fa": len(pred_list), - "fd": 0, - "fp": len(pred_list), - "tn": 0, - "fn": 0, - } - ) - # Add non-matches for each FA item using NonMatchesHelper - non_matches_helper = NonMatchesHelper() - result["non_matches"] = non_matches_helper.process_null_cases( - field_name, gt_list, pred_list - ) - elif FieldHelper.is_null_value(pred_list): - result.update( - {"tp": 0, "fa": 0, "fd": 0, "fp": 0, "tn": 0, "fn": len(gt_list)} - ) - # Add non-matches for each FN item using NonMatchesHelper - non_matches_helper = NonMatchesHelper() - result["non_matches"] = non_matches_helper.process_null_cases( - field_name, gt_list, pred_list - ) - else: - # Use existing comparison logic for list-level metrics - info = self.model.__class__._get_comparison_info(field_name) - comparator = info.comparator - threshold = info.threshold - - # Reuse existing Hungarian matching logic - match_result = self.model._compare_unordered_lists( - gt_list, pred_list, comparator, threshold, field_name=field_name - ) - - # Use the detailed confusion matrix results directly from Hungarian matcher - result.update( - { - "tp": match_result["tp"], - "fa": match_result[ - "fa" - ], # False alarms (unmatched prediction items) - "fd": match_result[ - "fd" - ], # False discoveries (matches below threshold) - "fp": match_result["fp"], # Total false positives (fa + fd) - "tn": 0, - "fn": match_result["fn"], # False negatives (unmatched GT items) - } - ) - - # Collect individual object-level non-matches using NonMatchesHelper - if gt_list and isinstance(gt_list[0], StructuredModel): - non_matches_helper = NonMatchesHelper() - non_matches = non_matches_helper.collect_list_non_matches( - field_name, gt_list, pred_list - ) - result["non_matches"] = non_matches - - # If list contains StructuredModel objects, calculate nested field metrics - if gt_list and isinstance(gt_list[0], StructuredModel): - nested_metrics = self.calculate_nested_field_metrics( - field_name, gt_list, pred_list, threshold - ) - result["nested_fields"] = nested_metrics - - # List-level metrics count object matches from the Hungarian algorithm; - # nested field metrics count field matches within those objects. They are - # separate concerns and are deliberately not rolled together here. - - # Add derived metrics - metrics_helper = MetricsHelper() - result["derived"] = metrics_helper.calculate_derived_metrics(result) - - return result - def classify_field_for_confusion_matrix( self, field_name: str, other_value: Any, threshold: float = None ) -> Dict[str, Any]: """Classify a field comparison according to confusion matrix rules. - + This method determines the confusion matrix classification for a single field comparison based on null states and similarity scores. - + Classification rules: - Both null: TN (True Negative) - GT null, pred non-null: FA (False Alarm) - GT non-null, pred null: FN (False Negative) - Both non-null and match: TP (True Positive) - Both non-null but don't match: FD (False Discovery) - + Args: field_name: Name of the field being compared other_value: Value to compare with threshold: Threshold for matching (uses field's threshold if None) - + Returns: Dictionary with TP, FP, TN, FN, FD counts and derived metrics - + Example: >>> calculator = ConfusionMatrixCalculator(gt_model) >>> result = calculator.classify_field_for_confusion_matrix("name", "John") @@ -204,7 +79,7 @@ def classify_field_for_confusion_matrix( if not gt_is_null and not pred_is_null: # Import here to avoid circular imports from .structured_model import StructuredModel - + if isinstance(gt_value, StructuredModel) and isinstance( pred_value, StructuredModel ): @@ -240,411 +115,3 @@ def classify_field_for_confusion_matrix( # Don't include similarity_score in the result as tests don't expect it return result - - def calculate_nested_field_metrics( - self, - list_field_name: str, - gt_list: List["StructuredModel"], - pred_list: List["StructuredModel"], - threshold: float, - ) -> Dict[str, Dict[str, Any]]: - """Calculate confusion matrix metrics for fields within list items. - - This method performs threshold-gated recursive analysis of fields within - matched list items. Only pairs with similarity >= match_threshold undergo - recursive field analysis. Poor matches and unmatched items are treated - as atomic units. - - Args: - list_field_name: Name of the parent list field (e.g., "transactions") - gt_list: Ground truth list of StructuredModel objects - pred_list: Predicted list of StructuredModel objects - threshold: Matching threshold for recursive analysis - - Returns: - Dictionary mapping nested field paths to their confusion matrix metrics. - E.g., {"transactions.date": {...}, "transactions.description": {...}} - - Example: - >>> calculator = ConfusionMatrixCalculator(gt_model) - >>> metrics = calculator.calculate_nested_field_metrics( - ... "items", gt_items, pred_items, 0.7 - ... ) - >>> print(metrics["items.name"]["tp"]) - """ - # Import here to avoid circular imports - from .structured_model import StructuredModel - - nested_metrics = {} - - if not gt_list or not isinstance(gt_list[0], StructuredModel): - return nested_metrics - - # Get the model class from the first item - model_class = gt_list[0].__class__ - - # CRITICAL FIX: Use field's threshold, not class's match_threshold - # Get the field info from the parent object to use the correct threshold - parent_field_info = self.model.__class__._get_comparison_info(list_field_name) - match_threshold = parent_field_info.threshold - - # For each field in the nested model - for field_name in model_class.model_fields: - if field_name == "extra_fields": - continue - - nested_field_path = f"{list_field_name}.{field_name}" - - # Initialize aggregated counts for this nested field - total_tp = total_fa = total_fd = total_fp = total_tn = total_fn = 0 - - # Use HungarianHelper for Hungarian matching operations - OPTIMIZED: Single call gets all info - hungarian_helper = HungarianHelper() - - # Use HungarianHelper to get optimal assignments with similarity scores - assignments = [] - matched_pairs_with_scores = [] - if gt_list and pred_list: - hungarian_info = hungarian_helper.get_complete_matching_info( - gt_list, pred_list - ) - matched_pairs_with_scores = hungarian_info["matched_pairs"] - # Extract (gt_idx, pred_idx) pairs from the matched_pairs - assignments = [(i, j) for i, j, score in matched_pairs_with_scores] - - # THRESHOLD-GATED RECURSION: Only process pairs that meet the match_threshold - for gt_idx, pred_idx, similarity_score in matched_pairs_with_scores: - if gt_idx < len(gt_list) and pred_idx < len(pred_list): - gt_item = gt_list[gt_idx] - pred_item = pred_list[pred_idx] - - # Handle floating point precision issues - is_above_threshold = ( - similarity_score >= match_threshold - or abs(similarity_score - match_threshold) < 1e-10 - ) - - # Only perform recursive field analysis if similarity meets threshold - if is_above_threshold: - # Get field values - gt_value = getattr(gt_item, field_name, None) - pred_value = getattr(pred_item, field_name, None) - - # Check if this field is a List[StructuredModel] that needs recursive processing - if ( - isinstance(gt_value, list) - and isinstance(pred_value, list) - and gt_value - and isinstance(gt_value[0], StructuredModel) - ): - # Handle List[StructuredModel] recursively - # Create a calculator for the gt_item - item_calculator = ConfusionMatrixCalculator(gt_item) - list_classification = item_calculator.calculate_list_confusion_matrix( - field_name, pred_value - ) - - # Aggregate the list-level counts - total_tp += list_classification["tp"] - total_fa += list_classification["fa"] - total_fd += list_classification["fd"] - total_fp += list_classification["fp"] - total_tn += list_classification["tn"] - total_fn += list_classification["fn"] - - # IMPORTANT: Also collect the deeper nested field metrics - if "nested_fields" in list_classification: - for ( - deeper_field_path, - deeper_metrics, - ) in list_classification["nested_fields"].items(): - # Create the full path: e.g., "products.attributes.name" - full_deeper_path = ( - f"{list_field_name}.{deeper_field_path}" - ) - - # Initialize or aggregate into the deeper nested metrics - if full_deeper_path not in nested_metrics: - nested_metrics[full_deeper_path] = { - "tp": 0, - "fa": 0, - "fd": 0, - "fp": 0, - "tn": 0, - "fn": 0, - } - - nested_metrics[full_deeper_path]["tp"] += ( - deeper_metrics["tp"] - ) - nested_metrics[full_deeper_path]["fa"] += ( - deeper_metrics["fa"] - ) - nested_metrics[full_deeper_path]["fd"] += ( - deeper_metrics["fd"] - ) - nested_metrics[full_deeper_path]["fp"] += ( - deeper_metrics["fp"] - ) - nested_metrics[full_deeper_path]["tn"] += ( - deeper_metrics["tn"] - ) - nested_metrics[full_deeper_path]["fn"] += ( - deeper_metrics["fn"] - ) - else: - # Handle primitive fields or single StructuredModel fields - # Create a calculator for the gt_item - item_calculator = ConfusionMatrixCalculator(gt_item) - field_classification = item_calculator.classify_field_for_confusion_matrix( - field_name, - pred_value, - None, # Use field's own threshold - ) - - # Aggregate counts - total_tp += field_classification["tp"] - total_fa += field_classification["fa"] - total_fd += field_classification["fd"] - total_fp += field_classification["fp"] - total_tn += field_classification["tn"] - total_fn += field_classification["fn"] - else: - # Skip recursive analysis for pairs below threshold - # These will be handled as FD at the object level - pass - - # Handle unmatched ground truth items (false negatives) - matched_gt_indices = set(idx for idx, _ in assignments) - for gt_idx, gt_item in enumerate(gt_list): - if gt_idx not in matched_gt_indices: - gt_value = getattr(gt_item, field_name, None) - if not FieldHelper.is_null_value(gt_value): - # Check if this is a List[StructuredModel] that needs deeper processing for FN - if ( - isinstance(gt_value, list) - and gt_value - and isinstance(gt_value[0], StructuredModel) - ): - # For List[StructuredModel], count each item in the list as a separate FN - # and handle deeper nested fields - total_fn += len(gt_value) # Each list item is a separate FN - - # Also handle deeper nested fields for unmatched items - dummy_empty_list = [] # Empty list for comparison - item_calculator = ConfusionMatrixCalculator(gt_item) - list_classification = item_calculator.calculate_list_confusion_matrix( - field_name, dummy_empty_list - ) - if "nested_fields" in list_classification: - for ( - deeper_field_path, - deeper_metrics, - ) in list_classification["nested_fields"].items(): - full_deeper_path = ( - f"{list_field_name}.{deeper_field_path}" - ) - if full_deeper_path not in nested_metrics: - nested_metrics[full_deeper_path] = { - "tp": 0, - "fa": 0, - "fd": 0, - "fp": 0, - "tn": 0, - "fn": 0, - } - nested_metrics[full_deeper_path]["fn"] += ( - deeper_metrics["fn"] - ) - else: - # Handle primitive fields or single StructuredModel fields - total_fn += 1 - - # Handle unmatched prediction items (false alarms) - matched_pred_indices = set(idx for _, idx in assignments) - for pred_idx, pred_item in enumerate(pred_list): - if pred_idx not in matched_pred_indices: - pred_value = getattr(pred_item, field_name, None) - if not FieldHelper.is_null_value(pred_value): - # Check if this is a List[StructuredModel] that needs deeper processing for FA - if ( - isinstance(pred_value, list) - and pred_value - and isinstance(pred_value[0], StructuredModel) - ): - # For List[StructuredModel], count each item in the list as a separate FA - # and handle deeper nested fields - total_fa += len( - pred_value - ) # Each list item is a separate FA - total_fp += len( - pred_value - ) # Each list item is also a separate FP - - # Also handle deeper nested fields for unmatched items - dummy_empty_list = [] # Empty list for comparison - # We need to create a dummy GT item for comparison to get the structure - if gt_list: # Use structure from an existing GT item - dummy_gt_item = gt_list[0] - dummy_calculator = ConfusionMatrixCalculator(dummy_gt_item) - list_classification = dummy_calculator.calculate_list_confusion_matrix( - field_name, pred_value - ) - if "nested_fields" in list_classification: - for ( - deeper_field_path, - deeper_metrics, - ) in list_classification["nested_fields"].items(): - full_deeper_path = ( - f"{list_field_name}.{deeper_field_path}" - ) - if full_deeper_path not in nested_metrics: - nested_metrics[full_deeper_path] = { - "tp": 0, - "fa": 0, - "fd": 0, - "fp": 0, - "tn": 0, - "fn": 0, - } - nested_metrics[full_deeper_path]["fa"] += ( - deeper_metrics["fa"] - ) - nested_metrics[full_deeper_path]["fp"] += ( - deeper_metrics["fp"] - ) - else: - # Handle primitive fields or single StructuredModel fields - total_fa += 1 - total_fp += 1 - - # Store the aggregated metrics for this nested field - nested_metrics[nested_field_path] = { - "tp": total_tp, - "fa": total_fa, - "fd": total_fd, - "fp": total_fp, - "tn": total_tn, - "fn": total_fn, - "derived": MetricsHelper().calculate_derived_metrics( - { - "tp": total_tp, - "fa": total_fa, - "fd": total_fd, - "fp": total_fp, - "tn": total_tn, - "fn": total_fn, - } - ), - } - - # Add derived metrics for all deeper nested fields that were collected - for deeper_path, deeper_metrics in nested_metrics.items(): - if deeper_path != nested_field_path and "derived" not in deeper_metrics: - deeper_metrics["derived"] = MetricsHelper().calculate_derived_metrics( - { - "tp": deeper_metrics["tp"], - "fa": deeper_metrics["fa"], - "fd": deeper_metrics["fd"], - "fp": deeper_metrics["fp"], - "tn": deeper_metrics["tn"], - "fn": deeper_metrics["fn"], - } - ) - - return nested_metrics - - def calculate_single_nested_field_metrics( - self, - parent_field_name: str, - gt_nested: "StructuredModel", - pred_nested: "StructuredModel", - ) -> Dict[str, Dict[str, Any]]: - """Calculate confusion matrix metrics for fields within a single nested StructuredModel. - - Args: - parent_field_name: Name of the parent field (e.g., "address") - gt_nested: Ground truth nested StructuredModel - pred_nested: Predicted nested StructuredModel - - Returns: - Dictionary mapping nested field paths to their confusion matrix metrics - E.g., {"address.street": {...}, "address.city": {...}} - """ - # Import here to avoid circular imports - from .structured_model import StructuredModel - - nested_metrics = {} - - if not isinstance(gt_nested, StructuredModel) or not isinstance( - pred_nested, StructuredModel - ): - # Handle case where one of the fields is a list of StructuredModel objects - if ( - not isinstance(gt_nested, list) - or not gt_nested - or not isinstance(gt_nested[0], StructuredModel) - ): - return nested_metrics - return nested_metrics - - - - # For each field in the nested model - for field_name in gt_nested.__class__.model_fields: - if field_name == "extra_fields": - continue - - nested_field_path = f"{parent_field_name}.{field_name}" - - - # Get the field value from the prediction - pred_value = getattr(pred_nested, field_name, None) - gt_value = getattr(gt_nested, field_name) - - # Handle lists of StructuredModel objects - if ( - isinstance(gt_value, list) - and isinstance(pred_value, list) - and gt_value - and isinstance(gt_value[0], StructuredModel) - ): - # Use the list comparison logic for lists of StructuredModel objects - nested_calculator = ConfusionMatrixCalculator(gt_nested) - list_metrics = nested_calculator.calculate_list_confusion_matrix( - field_name, pred_value - ) - - # Store the metrics for this nested field - nested_metrics[nested_field_path] = { - key: value - for key, value in list_metrics.items() - if key != "nested_fields" - } - - # Add nested field metrics if available - if "nested_fields" in list_metrics: - for sub_field, sub_metrics in list_metrics["nested_fields"].items(): - full_path = f"{nested_field_path}.{sub_field.split('.')[-1]}" - nested_metrics[full_path] = sub_metrics - else: - # Classify this field comparison - nested_calculator = ConfusionMatrixCalculator(gt_nested) - field_classification = nested_calculator.classify_field_for_confusion_matrix( - field_name, pred_value - ) - - # Store the metrics for this nested field - nested_metrics[nested_field_path] = field_classification - - # Recursively calculate metrics for deeper nesting - deeper_metrics = self.calculate_single_nested_field_metrics( - nested_field_path, gt_value, pred_value - ) - nested_metrics.update(deeper_metrics) - - - - - - return nested_metrics diff --git a/src/stickler/structured_object_evaluator/models/structured_model.py b/src/stickler/structured_object_evaluator/models/structured_model.py index b4a14410..0081f79c 100644 --- a/src/stickler/structured_object_evaluator/models/structured_model.py +++ b/src/stickler/structured_object_evaluator/models/structured_model.py @@ -1501,86 +1501,6 @@ def _classify_field_for_confusion_matrix( field_name, other_value, threshold ) - def _calculate_list_confusion_matrix( - self, field_name: str, other_list: List[Any] - ) -> Dict[str, Any]: - """Calculate confusion matrix for a list field, including nested field metrics. - - This method delegates to ConfusionMatrixCalculator for the actual implementation. - - Args: - field_name: Name of the list field being compared - other_list: Predicted list to compare with - - Returns: - Dictionary with: - - Top-level TP, FP, TN, FN, FD, FA counts and derived metrics for the list field - - nested_fields: Dict with metrics for individual fields within list items (e.g., "transactions.date") - - non_matches: List of individual object-level non-matches for detailed analysis - """ - from .confusion_matrix_calculator import ConfusionMatrixCalculator - - calculator = ConfusionMatrixCalculator(self) - return calculator.calculate_list_confusion_matrix(field_name, other_list) - - def _calculate_nested_field_metrics( - self, - list_field_name: str, - gt_list: List["StructuredModel"], - pred_list: List["StructuredModel"], - threshold: float, - ) -> Dict[str, Dict[str, Any]]: - """Calculate confusion matrix metrics for individual fields within list items. - - This method delegates to ConfusionMatrixCalculator for the actual implementation. - - THRESHOLD-GATED RECURSION: Only perform recursive field analysis for object pairs - with similarity >= StructuredModel.match_threshold. Poor matches and unmatched - items are treated as atomic units. - - Args: - list_field_name: Name of the parent list field (e.g., "transactions") - gt_list: Ground truth list of StructuredModel objects - pred_list: Predicted list of StructuredModel objects - threshold: Matching threshold (not used for threshold-gating) - - Returns: - Dictionary mapping nested field paths to their confusion matrix metrics - E.g., {"transactions.date": {...}, "transactions.description": {...}} - """ - from .confusion_matrix_calculator import ConfusionMatrixCalculator - - calculator = ConfusionMatrixCalculator(self) - return calculator.calculate_nested_field_metrics( - list_field_name, gt_list, pred_list, threshold - ) - - def _calculate_single_nested_field_metrics( - self, - parent_field_name: str, - gt_nested: "StructuredModel", - pred_nested: "StructuredModel", - ) -> Dict[str, Dict[str, Any]]: - """Calculate confusion matrix metrics for fields within a single nested StructuredModel. - - This method delegates to ConfusionMatrixCalculator for the actual implementation. - - Args: - parent_field_name: Name of the parent field (e.g., "address") - gt_nested: Ground truth nested StructuredModel - pred_nested: Predicted nested StructuredModel - - Returns: - Dictionary mapping nested field paths to their confusion matrix metrics - E.g., {"address.street": {...}, "address.city": {...}} - """ - from .confusion_matrix_calculator import ConfusionMatrixCalculator - - calculator = ConfusionMatrixCalculator(self) - return calculator.calculate_single_nested_field_metrics( - parent_field_name, gt_nested, pred_nested - ) - def _collect_enhanced_non_matches( self, recursive_result: dict, other: "StructuredModel" ) -> List[Dict[str, Any]]: