| """FeasibilityJudge — V0/V1/V2/V3 gate per 02_protocol.md §2-§5. |
| |
| Inputs: ``NormalizedEdge`` from :mod:`validation_agent.core.edge_loader`. |
| Outputs: ``FeasibilityReport`` matching ``feasibility.schema.v0.2`` |
| (``validation_agent/schemas/feasibility.schema.json``). |
| |
| Gates implemented: |
| V0 — relies on EdgeLoader (already passed by the time edge reaches here). |
| V1 — Mappability: status ∈ {exact, close, tentative}; dataset/field |
| exist in v7; medications/dietary excluded (memory feedback-physiological-only); |
| pid space joinability ≥ 5 (04 §10.1.1). |
| V2 — Container filter: when Y (or X) is a container column, validate |
| upstream value_filter OR infer from edge text (Y / Y_original_text / |
| Y_qualifiers.definition). |
| V3 — Equation inference: from Y_qualifiers.measurement_scale + |
| X_contrast_type → equation_type + candidate_estimator; reject |
| if estimator not in M1 supported set. |
| |
| Out of scope (delegated): |
| - V4/V5/V6 (Plan / Codegen / Result schema gates) live in their own modules. |
| - Data layer inspection (n_per_stratum, value distribution) → DataInspector. |
| |
| Dataset-selection anchor (generic, reserved — NOT yet implemented; North Star |
| SPEC §1 "选在哪个数据集上验证"): |
| This gate judges runnability against the *single registered* validation target |
| — HPP, via its v7 synthetic isomorph (``v7_root`` / ``exists_in_v7`` / |
| ``hpp_to_v7_path``). The design is dataset-GENERIC: feasibility is conceptually |
| evaluated *per candidate dataset*, and a design-period, data-/inventory-driven |
| ``DatasetSelector`` (**never a rule table**) chooses which feasible dataset(s) to |
| validate on once the data is inventoried. M1a registry = {HPP} → selection is the |
| identity. Adding a dataset later = register it + run this same gate against its |
| inventory + let the selector pick; no rule-based / paper-specific branch is ever |
| introduced. (per 01 §3.2 anchor.) |
| |
| The reasoning text composed in §_compose_reasoning is human-readable and used |
| by Planner / PlanReviewer audit; not parsed downstream. |
| """ |
| from __future__ import annotations |
|
|
| import json as _json |
| import re |
| from dataclasses import dataclass, field |
| from datetime import datetime, timezone |
| from pathlib import Path |
| from typing import Any |
|
|
| import pyarrow.parquet as pq |
|
|
| from validation_agent import __metadata_version__ |
| from validation_agent.configs import excluded_dataset_reasons, excluded_value_filter_reasons |
| from validation_agent.core.edge_loader import CONTAINER_FIELDS, NormalizedEdge |
| from validation_agent.path_mapping import ( |
| DEFAULT_V7_ROOT, |
| hpp_to_v7_path, |
| split_dataset_subtable, |
| strip_hpp_prefix, |
| ) |
|
|
|
|
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
| _EQUATION_INFERENCE: dict[tuple[str, str], tuple[str, str, str]] = { |
| ("continuous", "level_contrast"): ("E1-linear-binary", "e1_linear", "M1"), |
| ("continuous", "unit_increment"): ("E1-linear", "e1_linear", "M1"), |
| ("continuous", "continuous_linear"): ("E1-linear", "e1_linear", "M1"), |
| ("continuous", "category_vs_reference"): ("E1-linear-category", "e1_linear", "M1"), |
| ("continuous", "threshold"): ("E1-linear-binary", "e1_linear", "M1"), |
| ("continuous", "quantile"): ("E1-linear-category", "e1_linear", "M1"), |
| ("continuous", "per_sd"): ("E1-linear", "e1_linear", "M1"), |
| ("continuous", "any"): ("E1-linear", "e1_linear", "M1"), |
| ("binary", "any"): ("E1-logistic-binary", "e1_logistic", "M1"), |
| ("proportion", "any"): ("E1-logistic-binary", "e1_logistic", "M1"), |
| ("time_to_event", "any"): ("E2-cox", "e2_cox", "M2"), |
| ("count", "any"): ("E1-poisson", "e1_poisson", "M2"), |
| ("rate", "any"): ("E1-poisson", "e1_poisson", "M2"), |
| } |
|
|
| |
| _M1_SUPPORTED_ESTIMATORS = frozenset({"e1_linear", "e1_logistic"}) |
|
|
| |
| _Y_PREFIXES_TO_STRIP = ( |
| "early-onset ", |
| "late-onset ", |
| "incident ", |
| "current ", |
| "history of ", |
| "diagnosed with ", |
| "new-onset ", |
| "recurrent ", |
| ) |
|
|
|
|
| |
| |
| |
|
|
|
|
| @dataclass |
| class FeasibilityReport: |
| """Structured V0/V1/V2/V3 result. |
| |
| The ``to_json_dict`` projection emits a dict that validates against |
| ``feasibility.schema.v0.2`` (validation_agent/schemas/feasibility.schema.json). |
| """ |
|
|
| edge_id: str |
| judged_at: str |
| metadata_version: str |
| is_runnable: bool |
| blockers: list[str] |
| warnings: list[str] |
| x_mapping: dict[str, Any] |
| y_mapping: dict[str, Any] |
| z_summary: dict[str, int] |
| inferred_equation_type: str | None = None |
| candidate_estimator: str | None = None |
| reasoning: str = "" |
| data_gap: dict[str, Any] | None = None |
| longitudinal: dict[str, Any] | None = None |
| |
| z_details: list[dict[str, Any]] = field(default_factory=list) |
| pid_overlap_count: int | None = None |
|
|
| def to_json_dict(self) -> dict[str, Any]: |
| """Serialize to feasibility.schema.v0.2 shape (no internal extras).""" |
| return { |
| "edge_id": self.edge_id, |
| "judged_at": self.judged_at, |
| "metadata_version": self.metadata_version, |
| "is_runnable": self.is_runnable, |
| "blockers": list(self.blockers), |
| "warnings": list(self.warnings), |
| "x_mapping": _project_role_mapping(self.x_mapping), |
| "y_mapping": _project_role_mapping(self.y_mapping), |
| "z_summary": dict(self.z_summary), |
| "inferred_equation_type": self.inferred_equation_type, |
| "candidate_estimator": self.candidate_estimator, |
| "reasoning": self.reasoning, |
| "data_gap": self.data_gap, |
| "longitudinal": self.longitudinal, |
| } |
|
|
|
|
| def _project_role_mapping(m: dict[str, Any]) -> dict[str, Any]: |
| """Drop internal keys (sub_table, parquet_path) before schema-validation.""" |
| allowed = { |
| "status", |
| "dataset", |
| "field", |
| "exists_in_v7", |
| "is_container", |
| "value_filter_required", |
| "value_filter_present", |
| "inferred_value_filter", |
| "v7_match_count_expected", |
| } |
| return {k: v for k, v in m.items() if k in allowed} |
|
|
|
|
| |
| |
| |
|
|
|
|
| class FeasibilityJudge: |
| """V0/V1/V2/V3 gate evaluator. Caches parquet schemas + pid sets in-process.""" |
|
|
| def __init__( |
| self, |
| v7_root: Path | str = DEFAULT_V7_ROOT, |
| *, |
| metadata_version: str = __metadata_version__, |
| min_pid_overlap: int = 5, |
| supported_estimators: frozenset[str] = _M1_SUPPORTED_ESTIMATORS, |
| ) -> None: |
| |
| |
| |
| |
| |
| self.v7_root = Path(v7_root) |
| self.metadata_version = metadata_version |
| self.min_pid_overlap = min_pid_overlap |
| self.supported_estimators = supported_estimators |
| |
| |
| self._excluded_datasets: dict[str, str] = excluded_dataset_reasons() |
| self._excluded_vf_types: dict[str, str] = excluded_value_filter_reasons() |
| self._parquet_columns_cache: dict[str, frozenset[str]] = {} |
| self._parquet_pids_cache: dict[str, frozenset[Any]] = {} |
| self._parquet_stages_cache: dict[str, list[str]] = {} |
|
|
| |
|
|
| def judge(self, edge: NormalizedEdge) -> FeasibilityReport: |
| blockers: list[str] = [] |
| warnings: list[str] = [] |
|
|
| x_mapping = self._check_role(edge, "X", blockers) |
| y_mapping = self._check_role(edge, "Y", blockers) |
|
|
| |
| pid_overlap_count: int | None = None |
| if x_mapping.get("exists_in_v7") and y_mapping.get("exists_in_v7"): |
| pid_overlap_count = self._pid_overlap( |
| x_mapping["__full_id"], y_mapping["__full_id"] |
| ) |
| if pid_overlap_count < self.min_pid_overlap: |
| blockers.append("v1_pid_space_disjoint") |
|
|
| |
| for role, mapping in (("X", x_mapping), ("Y", y_mapping)): |
| self._handle_container_filter(edge, role, mapping, blockers, warnings) |
|
|
| |
| eq_type, estimator = self._infer_equation_type(edge, y_mapping) |
| if estimator is not None and estimator not in self.supported_estimators: |
| blockers.append("v3_estimator_not_registered_in_m1") |
| elif eq_type is None and y_mapping.get("exists_in_v7"): |
| blockers.append("v3_cannot_infer_equation_type") |
|
|
| |
| |
| |
| |
| longitudinal = self._build_longitudinal(x_mapping, y_mapping) |
|
|
| |
| z_summary, z_details = self._categorize_z(edge) |
|
|
| |
| data_gap = self._build_data_gap(edge, x_mapping, y_mapping, blockers) |
|
|
| reasoning = self._compose_reasoning( |
| edge, |
| x_mapping=x_mapping, |
| y_mapping=y_mapping, |
| z_summary=z_summary, |
| eq_type=eq_type, |
| estimator=estimator, |
| blockers=blockers, |
| warnings=warnings, |
| pid_overlap=pid_overlap_count, |
| ) |
|
|
| is_runnable = not blockers |
|
|
| return FeasibilityReport( |
| edge_id=edge.edge_id, |
| judged_at=datetime.now(timezone.utc).isoformat(), |
| metadata_version=self.metadata_version, |
| is_runnable=is_runnable, |
| blockers=blockers, |
| warnings=warnings, |
| x_mapping=x_mapping, |
| y_mapping=y_mapping, |
| z_summary=z_summary, |
| inferred_equation_type=eq_type, |
| candidate_estimator=estimator, |
| reasoning=reasoning, |
| data_gap=data_gap, |
| longitudinal=longitudinal, |
| z_details=z_details, |
| pid_overlap_count=pid_overlap_count, |
| ) |
|
|
| |
|
|
| def _check_role( |
| self, |
| edge: NormalizedEdge, |
| role: str, |
| blockers: list[str], |
| ) -> dict[str, Any]: |
| role_code = role.lower() |
| m = edge.hpp_mapping.get(role, {}) or {} |
| status = m.get("status") |
| dataset = m.get("dataset") |
| field_name = m.get("field") |
|
|
| out: dict[str, Any] = { |
| "status": status, |
| "dataset": dataset, |
| "field": field_name, |
| "exists_in_v7": False, |
| "is_container": field_name in CONTAINER_FIELDS if field_name else False, |
| "value_filter_required": False, |
| |
| "__full_id": None, |
| "__parquet_path": None, |
| } |
|
|
| |
| |
| |
| |
| |
| excl = self._exclusion_blocker(dataset, m.get("value_filter")) |
| if excl: |
| blockers.append(excl) |
| return out |
|
|
| if status not in ("exact", "close", "tentative"): |
| blockers.append(f"v1_{role_code}_not_mappable") |
| return out |
|
|
| if not dataset or not field_name: |
| blockers.append(f"v1_{role_code}_not_mappable") |
| return out |
|
|
| try: |
| parquet_path = hpp_to_v7_path(dataset, v7_root=self.v7_root) |
| except ValueError: |
| blockers.append(f"v1_{role_code}_field_not_in_v7") |
| return out |
|
|
| columns = self._parquet_columns(parquet_path) |
| if field_name not in columns: |
| blockers.append(f"v1_{role_code}_field_not_in_v7") |
| return out |
|
|
| out["exists_in_v7"] = True |
| out["is_container"] = field_name in CONTAINER_FIELDS |
| out["value_filter_required"] = out["is_container"] |
| out["__full_id"] = dataset |
| out["__parquet_path"] = parquet_path |
| |
| vf = m.get("value_filter") |
| if isinstance(vf, dict) and isinstance(vf.get("include"), list) and vf.get("include"): |
| out["value_filter_present"] = True |
| elif vf is None: |
| out["value_filter_present"] = False |
| else: |
| out["value_filter_present"] = False |
| return out |
|
|
| |
|
|
| def _handle_container_filter( |
| self, |
| edge: NormalizedEdge, |
| role: str, |
| mapping: dict[str, Any], |
| blockers: list[str], |
| warnings: list[str], |
| ) -> None: |
| if not mapping.get("is_container") or not mapping.get("exists_in_v7"): |
| return |
| role_code = role.lower() |
| m = edge.hpp_mapping.get(role, {}) or {} |
| vf = m.get("value_filter") |
| |
| if isinstance(vf, dict): |
| include = vf.get("include") |
| if isinstance(include, list) and include: |
| |
| match_kind = vf.get("match") |
| if match_kind not in (None, "exact", "contains", "regex", "code_prefix"): |
| self._mark_v2_blocker(mapping, blockers, "v2_unsupported_filter_match") |
| return |
| if isinstance(include, list): |
| |
| self._mark_v2_blocker(mapping, blockers, "v2_value_filter_include_empty") |
| return |
| |
| self._mark_v2_blocker(mapping, blockers, f"v2_{role_code}_missing_value_filter") |
| return |
| |
| if isinstance(vf, str) and vf.strip(): |
| mapping["inferred_value_filter"] = vf.strip() |
| return |
| |
| inferred = self._infer_container_filter(edge, role) |
| if inferred: |
| mapping["inferred_value_filter"] = inferred |
| mapping["v7_match_count_expected"] = 0 |
| warnings.append(f"v7_{role_code}_value_filter_expected_to_match_zero") |
| return |
| |
| self._mark_v2_blocker(mapping, blockers, "v2_cannot_infer_value_filter") |
|
|
| @staticmethod |
| def _mark_v2_blocker(mapping: dict[str, Any], blockers: list[str], code: str) -> None: |
| """Append a V2 blocker and stamp it on the role mapping (for data_gap |
| attribution). The internal ``_v2_blocker`` key is stripped before schema |
| serialization (see ``_project_role_mapping``).""" |
| blockers.append(code) |
| mapping["_v2_blocker"] = code |
|
|
| def _infer_container_filter(self, edge: NormalizedEdge, role: str) -> str | None: |
| eqf = edge.equation_formula_reported |
| if role == "Y": |
| candidates = [ |
| eqf.get("Y"), |
| eqf.get("Y_original_text"), |
| (eqf.get("Y_qualifiers") or {}).get("definition"), |
| ] |
| else: |
| candidates = [ |
| eqf.get("X"), |
| eqf.get("X_original_text"), |
| (eqf.get("X_qualifiers") or {}).get("definition"), |
| ] |
| for src in candidates: |
| if not isinstance(src, str): |
| continue |
| text = src.strip() |
| if not text: |
| continue |
| lowered = text.lower() |
| for prefix in _Y_PREFIXES_TO_STRIP: |
| if lowered.startswith(prefix): |
| text = text[len(prefix):] |
| lowered = lowered[len(prefix):] |
| break |
| |
| words = text.split() |
| if not words: |
| continue |
| return " ".join(words[: min(len(words), 6)]) |
| return None |
|
|
| |
|
|
| def _infer_equation_type( |
| self, |
| edge: NormalizedEdge, |
| y_mapping: dict[str, Any], |
| ) -> tuple[str | None, str | None]: |
| if not y_mapping.get("exists_in_v7"): |
| return None, None |
| yq = edge.equation_formula_reported.get("Y_qualifiers") or {} |
| scale: str | None = yq.get("measurement_scale") |
| if not scale and y_mapping.get("is_container"): |
| |
| scale = "binary" |
| if not scale: |
| return None, None |
| xct = edge.equation_formula_reported.get("X_contrast_type") |
| candidate = _EQUATION_INFERENCE.get((scale, xct)) |
| if candidate is None: |
| candidate = _EQUATION_INFERENCE.get((scale, "any")) |
| if candidate is None: |
| return None, None |
| eq_type, estimator, _milestone = candidate |
| return eq_type, estimator |
|
|
| |
|
|
| def _categorize_z( |
| self, |
| edge: NormalizedEdge, |
| ) -> tuple[dict[str, int], list[dict[str, Any]]]: |
| z_items = edge.hpp_mapping.get("Z") or [] |
| details: list[dict[str, Any]] = [] |
| n_mapped = 0 |
| n_fuzzy = 0 |
| n_unmapped = 0 |
| for zm in z_items: |
| if not isinstance(zm, dict): |
| continue |
| d = self._categorize_z_item(zm) |
| details.append(d) |
| cat = d["category"] |
| if cat == "mapped": |
| n_mapped += 1 |
| elif cat == "fuzzy": |
| n_fuzzy += 1 |
| else: |
| n_unmapped += 1 |
| return ( |
| { |
| "n_total": len(z_items), |
| "n_mapped": n_mapped, |
| "n_fuzzy": n_fuzzy, |
| "n_unmapped": n_unmapped, |
| }, |
| details, |
| ) |
|
|
| def _categorize_z_item(self, zm: dict[str, Any]) -> dict[str, Any]: |
| concept = zm.get("name") or zm.get("concept") or "<unknown>" |
| dataset = zm.get("dataset") |
| field_name = zm.get("field") |
| status = zm.get("status") |
| out: dict[str, Any] = { |
| "concept": concept, |
| "dataset": dataset, |
| "field": field_name, |
| } |
|
|
| |
| |
| |
| excl = self._exclusion_blocker(dataset, zm.get("value_filter")) |
| if excl: |
| out["category"] = "unmapped" |
| out["reason"] = excl[3:] if excl.startswith("v1_") else excl |
| return out |
|
|
| if status not in ("exact", "close", "tentative"): |
| out["category"] = "unmapped" |
| out["reason"] = "unmapped" |
| return out |
|
|
| if dataset is None: |
| out["category"] = "unmapped" |
| out["reason"] = "unmapped" |
| return out |
|
|
| |
| try: |
| parquet_path = hpp_to_v7_path(dataset, v7_root=self.v7_root) |
| except ValueError: |
| bare = strip_hpp_prefix(dataset).split(".", 1)[0] |
| out["category"] = "unmapped" |
| out["reason"] = f"v7_dataset_not_available_{bare}" |
| return out |
|
|
| |
| if not field_name: |
| out["category"] = "fuzzy" |
| out["reason"] = "fuzzy_mapping_field_null_cannot_resolve" |
| return out |
|
|
| columns = self._parquet_columns(parquet_path) |
| if field_name not in columns: |
| out["category"] = "unmapped" |
| out["reason"] = "unmapped" |
| return out |
|
|
| |
| |
| if field_name in CONTAINER_FIELDS: |
| vf = zm.get("value_filter") |
| has_filter = ( |
| isinstance(vf, dict) and isinstance(vf.get("include"), list) and vf.get("include") |
| ) or (isinstance(vf, str) and vf.strip()) |
| if not has_filter: |
| out["category"] = "unmapped" |
| out["reason"] = "container_column_no_inferable_filter" |
| return out |
|
|
| out["category"] = "mapped" |
| out["mapping_quality"] = "mapped" |
| return out |
|
|
| |
|
|
| def _exclusion_blocker(self, dataset: str | None, value_filter: Any) -> str | None: |
| """Return the V1 blocker code if (dataset, value_filter) is permanently |
| excluded per configs/excluded_datasets.json (11 §6: medications / dietary / |
| behavioral self-report), else None. Single source of truth — no hardcoding. |
| """ |
| if isinstance(dataset, str): |
| bare = strip_hpp_prefix(dataset).split(".", 1)[0] |
| code = self._excluded_datasets.get(bare) |
| if code: |
| return code |
| if isinstance(value_filter, dict): |
| t = value_filter.get("type") |
| if isinstance(t, str): |
| code = self._excluded_vf_types.get(t) |
| if code: |
| return code |
| return None |
|
|
| def _parquet_columns(self, parquet_path: str) -> frozenset[str]: |
| if parquet_path in self._parquet_columns_cache: |
| return self._parquet_columns_cache[parquet_path] |
| schema = pq.read_schema(parquet_path) |
| cols: set[str] = set(schema.names) |
| |
| |
| meta = schema.metadata or {} |
| pandas_md = meta.get(b"pandas") |
| if pandas_md: |
| try: |
| pmd = _json.loads(pandas_md.decode("utf-8")) |
| except (UnicodeDecodeError, _json.JSONDecodeError): |
| pmd = None |
| if isinstance(pmd, dict): |
| for ix in pmd.get("index_columns", []) or []: |
| if isinstance(ix, str): |
| cols.add(ix) |
| elif isinstance(ix, dict): |
| name = ix.get("name") |
| if isinstance(name, str): |
| cols.add(name) |
| result = frozenset(cols) |
| self._parquet_columns_cache[parquet_path] = result |
| return result |
|
|
| def _parquet_pids(self, full_dataset_id: str) -> frozenset[Any]: |
| if full_dataset_id in self._parquet_pids_cache: |
| return self._parquet_pids_cache[full_dataset_id] |
| parquet_path = hpp_to_v7_path(full_dataset_id, v7_root=self.v7_root) |
| |
| table = pq.read_table(parquet_path, columns=None) |
| |
| df = table.to_pandas() |
| if df.index.names != [None]: |
| df = df.reset_index() |
| if "participant_id" not in df.columns: |
| result = frozenset() |
| else: |
| pids = df["participant_id"].dropna().unique().tolist() |
| result = frozenset(pids) |
| self._parquet_pids_cache[full_dataset_id] = result |
| return result |
|
|
| def _research_stages(self, parquet_path: str) -> list[str]: |
| """Sorted distinct research_stage values on a role parquet (mirrors |
| DataInventory._distinct_strings(df, 'research_stage')). [] when the column is absent.""" |
| if parquet_path in self._parquet_stages_cache: |
| return self._parquet_stages_cache[parquet_path] |
| table = pq.read_table(parquet_path, columns=None) |
| df = table.to_pandas() |
| if df.index.names != [None]: |
| df = df.reset_index() |
| if "research_stage" not in df.columns: |
| result: list[str] = [] |
| else: |
| vals = df["research_stage"].dropna().unique().tolist() |
| result = sorted(str(v) for v in vals) |
| self._parquet_stages_cache[parquet_path] = result |
| return result |
|
|
| def _build_longitudinal( |
| self, x_mapping: dict[str, Any], y_mapping: dict[str, Any] |
| ) -> dict[str, Any] | None: |
| """E3-longitudinal feasibility (02 §5.1 extension / REBUILD E3 row). Reads the distinct |
| research_stage count of the v7-resolved role tables; picks the role with the MOST stages |
| (so a static annotation role can't mask a longitudinal one). >=3 -> e3_lmm (LMM slope), |
| ==2 -> e3_change (change-score), <2 -> not_runnable. Returns None when no role resolves |
| to v7 (cannot inspect timepoints). Aligns with cev/schemas/feasibility_per_equation.""" |
| stages: list[str] = [] |
| for mapping in (y_mapping, x_mapping): |
| if mapping.get("exists_in_v7") and mapping.get("__parquet_path"): |
| s = self._research_stages(mapping["__parquet_path"]) |
| if len(s) > len(stages): |
| stages = s |
| if not stages: |
| return None |
| n = len(stages) |
| if n >= 3: |
| status, estimator, missing = "ok", "e3_lmm", [] |
| elif n == 2: |
| status, estimator, missing = "ok", "e3_change", [] |
| else: |
| status, estimator, missing = "not_runnable", None, ["research_stage_single_timepoint"] |
| return { |
| "equation_type": "E3-longitudinal", |
| "timepoints": stages, |
| "n_timepoints": n, |
| "candidate_estimator": estimator, |
| "status": status, |
| "missing": missing, |
| } |
|
|
| def _pid_overlap(self, x_full_id: str, y_full_id: str) -> int: |
| return len(self._parquet_pids(x_full_id) & self._parquet_pids(y_full_id)) |
|
|
| |
|
|
| def _build_data_gap( |
| self, |
| edge: NormalizedEdge, |
| x_mapping: dict[str, Any], |
| y_mapping: dict[str, Any], |
| blockers: list[str], |
| ) -> dict[str, Any] | None: |
| if not blockers: |
| return None |
| eqf = edge.equation_formula_reported |
| x_reason = self._role_reason(x_mapping, blockers, "x") |
| y_reason = self._role_reason(y_mapping, blockers, "y") |
| return { |
| "x_concept": eqf.get("X", "") or "", |
| "x_reason": x_reason, |
| "y_concept": eqf.get("Y", "") or "", |
| "y_reason": y_reason, |
| "recommended_v7_extensions": [], |
| } |
|
|
| @staticmethod |
| def _role_reason(mapping: dict[str, Any], blockers: list[str], role_code: str) -> str: |
| """data_gap reason for one role: 'ok' only if it both exists in v7 AND |
| cleared the V2 container check; otherwise the attributable blocker.""" |
| if not mapping.get("exists_in_v7"): |
| return FeasibilityJudge._pick_role_blocker(blockers, role_code) |
| v2_blocker = mapping.get("_v2_blocker") |
| return v2_blocker if v2_blocker else "ok" |
|
|
| @staticmethod |
| def _pick_role_blocker(blockers: list[str], role_code: str) -> str: |
| for b in blockers: |
| if b.startswith(f"v1_{role_code}_") or b.startswith(f"v2_{role_code}_"): |
| return b |
| return "not_runnable" |
|
|
| @staticmethod |
| def _compose_reasoning( |
| edge: NormalizedEdge, |
| *, |
| x_mapping: dict[str, Any], |
| y_mapping: dict[str, Any], |
| z_summary: dict[str, int], |
| eq_type: str | None, |
| estimator: str | None, |
| blockers: list[str], |
| warnings: list[str], |
| pid_overlap: int | None, |
| ) -> str: |
| parts: list[str] = [] |
| parts.append( |
| f"X status={x_mapping.get('status')} -> " |
| f"{x_mapping.get('dataset')}.{x_mapping.get('field')} " |
| f"(exists_in_v7={x_mapping.get('exists_in_v7')});" |
| ) |
| parts.append( |
| f"Y status={y_mapping.get('status')} -> " |
| f"{y_mapping.get('dataset')}.{y_mapping.get('field')} " |
| f"(exists_in_v7={y_mapping.get('exists_in_v7')}, " |
| f"is_container={y_mapping.get('is_container')})." |
| ) |
| if y_mapping.get("inferred_value_filter"): |
| parts.append( |
| f"Inferred Y value_filter={y_mapping['inferred_value_filter']!r}; " |
| "v7 placeholder substrate -> match_count expected 0." |
| ) |
| parts.append( |
| f"Z mapping: {z_summary['n_mapped']} mapped / {z_summary['n_fuzzy']} fuzzy / " |
| f"{z_summary['n_unmapped']} unmapped (of {z_summary['n_total']} total)." |
| ) |
| if pid_overlap is not None: |
| parts.append(f"pid_overlap_count={pid_overlap}.") |
| if eq_type and estimator: |
| parts.append( |
| f"Inferred equation_type={eq_type}, candidate_estimator={estimator}." |
| ) |
| if blockers: |
| parts.append(f"Blockers: {', '.join(blockers)}.") |
| if warnings: |
| parts.append(f"Warnings: {', '.join(warnings)}.") |
| return " ".join(parts) |
|
|
|
|
| __all__ = [ |
| "FeasibilityJudge", |
| "FeasibilityReport", |
| ] |
|
|