Download CODE/evaluation/eval/eval_geometric052_rc5.py from QLU-LLM/CAD: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/eval/eval_geometric052_rc5.py
- Command line
-
hf download hf://datasets/QLU-LLM/CAD/CODE/evaluation/eval/eval_geometric052_rc5.py
-
curl -L -o eval_geometric052_rc5.py https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/eval/eval_geometric052_rc5.py
11 kB
| #!/usr/bin/env python3 | |
| """v5.2-rc5 evaluator with hybrid, causally isolated view-layout offsets. | |
| RC5 retains every RC3 component except layout. A semantic role offset is the | |
| coordinate median of raw offsets from its already one-to-one matched | |
| primitives (LINE midpoint, CIRCLE/ARC centre). One match is sufficient. Only | |
| with zero matched pairs is RC3's parameter-stable view anchor used as an | |
| explicit fallback. Layout fails closed to zero when evidence is unavailable. | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import math | |
| from itertools import combinations | |
| from pathlib import Path | |
| from typing import Any, Mapping, Sequence | |
| import numpy as np | |
| try: | |
| from . import eval_geometric052_rc3 as RC3 | |
| except ImportError: # direct evaluator import | |
| import eval_geometric052_rc3 as RC3 | |
| METRIC_VERSION = "v5.2-rc5" | |
| SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc5" | |
| ENGINEERING_THRESHOLDS = dict(RC3.ENGINEERING_THRESHOLDS) | |
| PHYSICAL_SUPPORTED_SEMANTICS = RC3.PHYSICAL_SUPPORTED_SEMANTICS | |
| OFFSET_DEFINITION = "GT_anchor-global_scale*Pred_anchor" | |
| def _visibility(layer: Any) -> str: | |
| token = str(layer).casefold() | |
| return "hidden" if "hidden" in token or "dash" in token else "visible" | |
| def _family_entities(entities: Mapping[str, Any], family: str) -> list[Any]: | |
| if family in {"visible_line", "hidden_line"}: | |
| expected = "visible" if family == "visible_line" else "hidden" | |
| return [ | |
| item | |
| for item in entities.get("lines", []) | |
| if isinstance(item, Sequence) | |
| and not isinstance(item, (str, bytes)) | |
| and item | |
| and _visibility(item[-1]) == expected | |
| ] | |
| return list(entities.get("circles" if family == "circle" else "arcs", [])) | |
| def _anchor(item: Sequence[Any], family: str) -> np.ndarray | None: | |
| try: | |
| if family in {"visible_line", "hidden_line"}: | |
| if len(item) < 4: | |
| return None | |
| return np.asarray( | |
| ( | |
| 0.5 * (float(item[0]) + float(item[2])), | |
| 0.5 * (float(item[1]) + float(item[3])), | |
| ), | |
| dtype=float, | |
| ) | |
| if len(item) < 2: | |
| return None | |
| return np.asarray((float(item[0]), float(item[1])), dtype=float) | |
| except (TypeError, ValueError): | |
| return None | |
| def _role_offset( | |
| context: Mapping[str, Any], | |
| rows: Mapping[str, Any], | |
| role: str, | |
| *, | |
| scale: float, | |
| sheet_diagonal: float, | |
| ) -> tuple[np.ndarray | None, dict[str, Any]]: | |
| pred_index = rows[role].get("predicted_view_index") | |
| if not isinstance(pred_index, int) or not 0 <= pred_index < len(context["pred_views"]): | |
| return None, { | |
| "offset": None, | |
| "support_count": 0, | |
| "fallback_used": False, | |
| "offset_source": "unavailable", | |
| "offset_dispersion_fraction": None, | |
| } | |
| pred_view = context["pred_views"][pred_index] | |
| gt_view = context["gt_by_role"][role] | |
| pred_entities = pred_view.get("entities", {}) | |
| gt_entities = gt_view.get("entities", {}) | |
| offsets: list[np.ndarray] = [] | |
| matched_by_family: dict[str, int] = {} | |
| predicted_count = 0 | |
| target_count = 0 | |
| for family in ("visible_line", "hidden_line", "circle", "arc"): | |
| predicted = _family_entities(pred_entities, family) | |
| target = _family_entities(gt_entities, family) | |
| predicted_count += len(predicted) | |
| target_count += len(target) | |
| accepted = 0 | |
| for pair in rows[role]["primitive"][family].get("pairs", []): | |
| try: | |
| pred_item = predicted[int(pair["predicted_index"])] | |
| gt_item = target[int(pair["target_index"])] | |
| except (KeyError, TypeError, ValueError, IndexError): | |
| continue | |
| pred_anchor = _anchor(pred_item, family) | |
| gt_anchor = _anchor(gt_item, family) | |
| if pred_anchor is None or gt_anchor is None: | |
| continue | |
| offsets.append(gt_anchor - scale * pred_anchor) | |
| accepted += 1 | |
| matched_by_family[family] = accepted | |
| support = len(offsets) | |
| fallback_used = False | |
| source = "matched_primitive_pair_median" | |
| if support: | |
| offset = np.median(np.asarray(offsets, dtype=float), axis=0) | |
| dispersion = float( | |
| np.median([np.linalg.norm(item - offset) for item in offsets]) | |
| / sheet_diagonal | |
| ) | |
| else: | |
| pred_anchor = pred_view.get("layout_anchor") | |
| gt_anchor = gt_view.get("layout_anchor") | |
| if pred_anchor is None or gt_anchor is None: | |
| offset = None | |
| else: | |
| offset = np.asarray(gt_anchor, dtype=float) - scale * np.asarray( | |
| pred_anchor, dtype=float | |
| ) | |
| fallback_used = True | |
| dispersion = None | |
| source = "fallback_parameter_stable_view_anchor" | |
| precision = support / predicted_count if predicted_count else 0.0 | |
| recall = support / target_count if target_count else 0.0 | |
| return offset, { | |
| "offset": [RC3.BASE._round(float(value)) for value in offset] | |
| if offset is not None | |
| else None, | |
| "support_count": support, | |
| "matched_by_family": matched_by_family, | |
| "fallback_used": fallback_used, | |
| "offset_source": source if offset is not None else "unavailable", | |
| "predicted_anchor_count": predicted_count, | |
| "target_anchor_count": target_count, | |
| "anchor_precision": RC3.BASE._round(precision), | |
| "anchor_recall": RC3.BASE._round(recall), | |
| "offset_dispersion_fraction": RC3.BASE._round(dispersion), | |
| } | |
| def _layout_component( | |
| context: Mapping[str, Any], rows: Mapping[str, Any] | |
| ) -> dict[str, Any]: | |
| roles = [str(role) for role, row in rows.items() if row["present"]] | |
| alignment = context["alignment"] | |
| scale = float(alignment.get("global_scale", 1.0)) | |
| sheet_diagonal = max(float(alignment.get("sheet_diagonal", 1.0)), 1.0) | |
| if len(roles) < 2: | |
| return RC3.BASE._component( | |
| 0.0, | |
| True, | |
| "insufficient_layout_evidence", | |
| matched_roles=roles, | |
| global_scale=RC3.BASE._round(scale), | |
| core_component_fail_closed=True, | |
| ) | |
| offsets: dict[str, np.ndarray] = {} | |
| diagnostics: dict[str, Any] = {} | |
| for role in roles: | |
| offset, detail = _role_offset( | |
| context, rows, role, scale=scale, sheet_diagonal=sheet_diagonal | |
| ) | |
| diagnostics[role] = detail | |
| if offset is not None: | |
| offsets[role] = offset | |
| missing = [role for role in roles if role not in offsets] | |
| if missing: | |
| return RC3.BASE._component( | |
| 0.0, | |
| True, | |
| "insufficient_layout_evidence", | |
| matched_roles=roles, | |
| missing_offset_roles=missing, | |
| role_offsets=diagnostics, | |
| global_scale=RC3.BASE._round(scale), | |
| scale_source="alignment.global_scale", | |
| core_component_fail_closed=True, | |
| ) | |
| errors: list[float] = [] | |
| pair_rows: list[dict[str, Any]] = [] | |
| for first, second in combinations(roles, 2): | |
| error = float(np.linalg.norm(offsets[second] - offsets[first]) / sheet_diagonal) | |
| errors.append(error) | |
| pair_rows.append( | |
| {"roles": [first, second], "offset_error_fraction": RC3.BASE._round(error)} | |
| ) | |
| mean_error = float(np.mean(errors)) | |
| score = math.exp(-mean_error / 0.10) | |
| dispersions = [ | |
| float(detail["offset_dispersion_fraction"]) | |
| for detail in diagnostics.values() | |
| if detail.get("offset_dispersion_fraction") is not None | |
| ] | |
| return RC3.BASE._component( | |
| score, | |
| True, | |
| "ok" if mean_error <= 0.02 else "relative_view_layout_mismatch", | |
| matched_roles=roles, | |
| mean_pair_offset_error_fraction=RC3.BASE._round(mean_error), | |
| pairs=pair_rows, | |
| role_offsets=diagnostics, | |
| matched_support_total=sum( | |
| int(detail["support_count"]) for detail in diagnostics.values() | |
| ), | |
| fallback_role_count=sum( | |
| bool(detail["fallback_used"]) for detail in diagnostics.values() | |
| ), | |
| offset_dispersion_macro=RC3.BASE._round(float(np.mean(dispersions))) | |
| if dispersions | |
| else None, | |
| offset_definition=OFFSET_DEFINITION, | |
| global_scale=RC3.BASE._round(scale), | |
| scale_source="alignment.global_scale", | |
| uniform_sheet_scale_invariant=True, | |
| global_translation_invariant=True, | |
| core_component_fail_closed=True, | |
| ) | |
| def score_dxf_pair( | |
| pred: str | Path, | |
| gt: str | Path, | |
| sidecar: Mapping[str, Any] | None = None, | |
| category: str | None = None, | |
| **kwargs: Any, | |
| ) -> dict[str, Any]: | |
| """Run RC3 once, then replace layout and all dependent aggregates.""" | |
| result = RC3.score_dxf_pair( | |
| pred, gt, sidecar=sidecar, category=category, **kwargs | |
| ) | |
| result["schema_version"] = SCHEMA_VERSION | |
| result["metric_version"] = METRIC_VERSION | |
| result.setdefault("metric_definition", {}).update( | |
| { | |
| "layout_offset_formula": OFFSET_DEFINITION, | |
| "layout_anchor_sources": [ | |
| "line_midpoint", | |
| "circle_center", | |
| "arc_center", | |
| ], | |
| "layout_hybrid_policy": ( | |
| "matched_pair_if_support_ge_1_else_parameter_stable_view_anchor" | |
| ), | |
| "layout_failure_policy": "core_component_score_zero", | |
| } | |
| ) | |
| context = RC3._consume_appended_omitted_marker( | |
| RC3.MATCH.build_pair_context(pred, gt, sidecar=sidecar) | |
| ) | |
| if context.get("eligible") and context.get("prediction_valid"): | |
| rows, _curve = RC3.BASE._semantic_rows(context) | |
| layout = _layout_component(context, rows) | |
| components = result["components"] | |
| components["layout"] = layout | |
| prompt_components = result["online_reward_prompt_masked"]["components"] | |
| prompt_components["layout"] = copy.deepcopy(layout) | |
| atomic = result.get("diagnostics", {}).get("atomic_geometry", {}) | |
| result["verified_reward_full_gt"] = RC3._scoped_hierarchical_reward( | |
| components, atomic, scope="offline_full_gt_executed_dxf" | |
| ) | |
| prompt_reward = RC3._scoped_hierarchical_reward( | |
| prompt_components, atomic, scope="prompt_masked_actual_geometry" | |
| ) | |
| result["online_reward_prompt_masked"] = { | |
| **prompt_reward, | |
| "components": prompt_components, | |
| } | |
| result["benchmark"] = RC3._benchmark(components) | |
| result["engineering_success"] = result["benchmark"]["engineering_success"] | |
| release = result.get("diagnostics", {}).get("release_status") | |
| if isinstance(release, dict): | |
| release["candidate"] = METRIC_VERSION | |
| return result | |
| __all__ = [ | |
| "ENGINEERING_THRESHOLDS", | |
| "METRIC_VERSION", | |
| "OFFSET_DEFINITION", | |
| "PHYSICAL_SUPPORTED_SEMANTICS", | |
| "SCHEMA_VERSION", | |
| "score_dxf_pair", | |
| ] | |