Upload missingness and cardinality evaluation code support
Browse filesFiles changed (20)
- evaluation/query_family/code_support/README.mdAdded+14
- evaluation/query_family/code_support/src/eval/analytics_contract.pyAdded+341
- evaluation/query_family/code_support/src/eval/common.pyAdded+1629
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/__init__.pyAdded+5
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/runner.pyAdded
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_final.pyAdded+107
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_heatmap_palette.pyAdded+60
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_grouped_bars.pyAdded+261
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_heatmap.pyAdded+155
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/__init__.pyAdded+1
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/__init__.pyAdded+1
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/runner.pyAdded+563
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/regime_diagnostic_runner.pyAdded+334
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/review_strict_pairwise.pyAdded+519
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/runner.pyAdded+1171
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/__init__.pyAdded+2
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/runner.pyAdded+463
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/__init__.pyAdded+2
- evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/runner.pyAdded+521
- evaluation/query_family/code_support/tests/comissing_condition_eval.pyAdded+663
1234567891011121314# Query Family Evaluation Code Support
This support bundle mirrors the server-side code needed to reproducethe missingness and cardinality query-family evaluations.
Included components:- `src/eval/common.py`- `src/eval/analytics_contract.py`- `src/eval/query_fivepart_breakdown/common_*` helpers- `src/eval/query_fivepart_breakdown/missingness_breakdown/*`- `src/eval/query_fivepart_breakdown/cardinality/*`- `tests/comissing_condition_eval.py`
Source of truth: `/data/jialinzhang/TabQueryBench/code_snapshot`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341"""Canonical analytics family/sub-item contract helpers.
This module centralizes how query-level evidence is mapped onto thefrozen analytics sub-item contract defined in`doc/analytics_family_subitem_contract_v1.md`."""
from __future__ import annotations
import refrom statistics import meanfrom typing import Any, Mapping
ANALYTICS_CONTRACT_VERSION = "analytics_family_subitem_contract_v1"
CANONICAL_ANALYTICS_SUBITEMS: dict[str, list[str]] = { "subgroup_structure": [ "internal_profile_stability", "subgroup_size_stability", ], "conditional_dependency_structure": [ "dependency_strength_similarity", "direction_consistency", "slice_level_consistency", ], "tail_rarity_structure": [ "tail_set_consistency", "tail_mass_similarity", "tail_concentration_consistency", ], "missingness_structure": [ "marginal_missing_rate_consistency", "co_missingness_pattern_consistency", ],}
_FACET_TO_SUBITEM: dict[str, dict[str, str]] = { "subgroup_structure": { "subgroup_distribution_shift": "internal_profile_stability", "subgroup_rank_order": "internal_profile_stability", "subgroup_conditional_contrast": "internal_profile_stability", }, "conditional_dependency_structure": { "pairwise_conditional_dependency": "dependency_strength_similarity", "conditional_rate_shift": "direction_consistency", "conditional_interaction_hotspots": "slice_level_consistency", }, "tail_rarity_structure": { "rare_target_concentration": "tail_concentration_consistency", "low_support_extremes": "tail_set_consistency", "tail_ranked_signal": "tail_concentration_consistency", }, "missingness_structure": { "missing_indicator_distribution": "marginal_missing_rate_consistency", "missing_target_interaction": "co_missingness_pattern_consistency", "missing_rate_by_subgroup": "co_missingness_pattern_consistency", },}
_ROLE_ALIASES = { "group_count": "count_distribution", "filtered_group_count_topk": "filtered_stable_view", "group_condition_rate": "within_group_proportion", "group_ratio_two_conditions": "within_group_proportion", "group_sum": "collapsed_target_view", "group_avg_numeric": "collapsed_target_view", "support_guarded_group_avg": "filtered_stable_view", "binned_numeric_group_avg": "collapsed_target_view", "two_dimensional_group_avg": "collapsed_target_view",}
_ROLE_TO_SUBITEM: dict[str, dict[str, str]] = { "subgroup_structure": { "count_distribution": "subgroup_size_stability", "filtered_stable_view": "subgroup_size_stability", "within_group_proportion": "internal_profile_stability", "collapsed_target_view": "internal_profile_stability", "ranked_signal_view": "internal_profile_stability", "focused_target_view": "internal_profile_stability", "contrastive_conditional_view": "internal_profile_stability", "rare_extreme_view": "internal_profile_stability", }, "conditional_dependency_structure": { "within_group_proportion": "dependency_strength_similarity", "collapsed_target_view": "dependency_strength_similarity", "count_distribution": "slice_level_consistency", "filtered_stable_view": "slice_level_consistency", "ranked_signal_view": "direction_consistency", "focused_target_view": "direction_consistency", "contrastive_conditional_view": "direction_consistency", "rare_extreme_view": "direction_consistency", }, "tail_rarity_structure": { "rare_extreme_view": "tail_set_consistency", "count_distribution": "tail_mass_similarity", "filtered_stable_view": "tail_mass_similarity", "within_group_proportion": "tail_concentration_consistency", "focused_target_view": "tail_concentration_consistency", "contrastive_conditional_view": "tail_concentration_consistency", "ranked_signal_view": "tail_concentration_consistency", "collapsed_target_view": "tail_concentration_consistency", }, "missingness_structure": { "missing_indicator_view": "marginal_missing_rate_consistency", "missing_ranked_view": "marginal_missing_rate_consistency", "filtered_stable_view": "marginal_missing_rate_consistency", "count_distribution": "marginal_missing_rate_consistency", "missing_target_interaction": "co_missingness_pattern_consistency", "missing_rate_by_subgroup": "co_missingness_pattern_consistency", "focused_target_view": "co_missingness_pattern_consistency", "contrastive_conditional_view": "co_missingness_pattern_consistency", "rare_extreme_view": "co_missingness_pattern_consistency", "within_group_proportion": "co_missingness_pattern_consistency", },}
_RATE_RE = re.compile(r"(rate|ratio|proportion|share|pct|percent|bucket_rate|global_rate|within_group_rate|focus_rate)", re.IGNORECASE)_COUNT_RE = re.compile(r"(count|support|total|freq|frequency)", re.IGNORECASE)_RANK_RE = re.compile(r"(rank|ranked|order|top|highest|lowest|strongest|weakest|focus)", re.IGNORECASE)_TAIL_RE = re.compile(r"(tail|rare|extreme|low[\s\-_]?support|outlier)", re.IGNORECASE)_CONCENTRATION_RE = re.compile(r"(concentrat|dominant|heavy|share|focus)", re.IGNORECASE)_MISSING_RE = re.compile(r"(missing|null|not_missing)", re.IGNORECASE)_PAIRWISE_RE = re.compile(r"(pairwise|co[\s\-_]?missing|joint|interaction|subgroup)", re.IGNORECASE)
def canonical_subitem_score_field(family_id: str, subitem_id: str) -> str: return f"{family_id}__{subitem_id}_score"
def all_canonical_subitem_score_fields() -> list[str]: fields: list[str] = [] for family_id, subitems in CANONICAL_ANALYTICS_SUBITEMS.items(): for subitem_id in subitems: fields.append(canonical_subitem_score_field(family_id, subitem_id)) return fields
def normalize_variant_semantic_role(value: Any) -> str: text = str(value or "").strip().lower() if not text: return "" return _ROLE_ALIASES.get(text, text)
def _normalize_family(value: Any) -> str: return str(value or "").strip().lower()
def _normalize_facet(value: Any) -> str: return str(value or "").strip().lower()
def _text_blob(query_row: Mapping[str, Any]) -> str: parts = [ query_row.get("question"), query_row.get("research_question"), query_row.get("expected_output_shape"), query_row.get("template_name"), query_row.get("template_id"), query_row.get("variant_semantic_role"), query_row.get("intended_facet_id"), query_row.get("intended_structure_claim"), query_row.get("sql"), ] return " ".join(str(item or "") for item in parts).strip().lower()
def infer_canonical_subitem(query_row: Mapping[str, Any]) -> dict[str, Any]: family_id = _normalize_family(query_row.get("family_id") or query_row.get("family")) if family_id not in CANONICAL_ANALYTICS_SUBITEMS: return { "family_id": family_id, "canonical_subitem_id": "", "contract_version": ANALYTICS_CONTRACT_VERSION, "normalized_variant_semantic_role": normalize_variant_semantic_role(query_row.get("variant_semantic_role")), "normalized_intended_facet_id": _normalize_facet(query_row.get("intended_facet_id")), "subitem_inference_source": "non_analytics_family", "subitem_inference_note": "family_not_in_canonical_contract", }
normalized_role = normalize_variant_semantic_role(query_row.get("variant_semantic_role")) normalized_facet = _normalize_facet(query_row.get("intended_facet_id")) text_blob = _text_blob(query_row) sql_text = str(query_row.get("sql") or "").lower() explicit_subitem_id = str(query_row.get("canonical_subitem_id") or "").strip()
if explicit_subitem_id and explicit_subitem_id in CANONICAL_ANALYTICS_SUBITEMS.get(family_id, []): return { "family_id": family_id, "canonical_subitem_id": explicit_subitem_id, "contract_version": ANALYTICS_CONTRACT_VERSION, "normalized_variant_semantic_role": normalized_role, "normalized_intended_facet_id": normalized_facet, "subitem_inference_source": "explicit", "subitem_inference_note": "canonical_subitem_id", }
if normalized_facet in _FACET_TO_SUBITEM.get(family_id, {}): return { "family_id": family_id, "canonical_subitem_id": _FACET_TO_SUBITEM[family_id][normalized_facet], "contract_version": ANALYTICS_CONTRACT_VERSION, "normalized_variant_semantic_role": normalized_role, "normalized_intended_facet_id": normalized_facet, "subitem_inference_source": "facet", "subitem_inference_note": normalized_facet, }
if normalized_role in _ROLE_TO_SUBITEM.get(family_id, {}): return { "family_id": family_id, "canonical_subitem_id": _ROLE_TO_SUBITEM[family_id][normalized_role], "contract_version": ANALYTICS_CONTRACT_VERSION, "normalized_variant_semantic_role": normalized_role, "normalized_intended_facet_id": normalized_facet, "subitem_inference_source": "role", "subitem_inference_note": normalized_role, }
if family_id == "subgroup_structure": if _RATE_RE.search(text_blob) or _RANK_RE.search(text_blob): subitem_id = "internal_profile_stability" note = "heuristic_rate_or_rank" elif _COUNT_RE.search(text_blob) or "count(" in sql_text: subitem_id = "subgroup_size_stability" note = "heuristic_count_or_support" else: subitem_id = "internal_profile_stability" note = "heuristic_family_default" elif family_id == "conditional_dependency_structure": if "contrast" in text_blob or _RANK_RE.search(text_blob): subitem_id = "direction_consistency" note = "heuristic_directional_signal" elif _COUNT_RE.search(text_blob) and not _RATE_RE.search(text_blob): subitem_id = "slice_level_consistency" note = "heuristic_slice_support" else: subitem_id = "dependency_strength_similarity" note = "heuristic_dependency_strength" elif family_id == "tail_rarity_structure": if _TAIL_RE.search(text_blob) and ("support asc" in sql_text or "order by support asc" in sql_text): subitem_id = "tail_set_consistency" note = "heuristic_tail_membership" elif _CONCENTRATION_RE.search(text_blob) and (_RANK_RE.search(text_blob) or "focus_rate" in sql_text): subitem_id = "tail_concentration_consistency" note = "heuristic_tail_concentration" elif (_RATE_RE.search(text_blob) or "focus_rate" in sql_text) and ("group by" in sql_text or "partition by" in sql_text): subitem_id = "tail_concentration_consistency" note = "heuristic_tail_concentration_from_rate_view" else: subitem_id = "tail_mass_similarity" note = "heuristic_tail_mass" else: # missingness_structure if _PAIRWISE_RE.search(text_blob) or "missing_rate" in sql_text or "group by" in sql_text and _MISSING_RE.search(text_blob): subitem_id = "co_missingness_pattern_consistency" note = "heuristic_missing_structure" else: subitem_id = "marginal_missing_rate_consistency" note = "heuristic_missing_marginal"
return { "family_id": family_id, "canonical_subitem_id": subitem_id, "contract_version": ANALYTICS_CONTRACT_VERSION, "normalized_variant_semantic_role": normalized_role, "normalized_intended_facet_id": normalized_facet, "subitem_inference_source": "heuristic", "subitem_inference_note": note, }
def annotate_query_row_with_contract(query_row: dict[str, Any]) -> dict[str, Any]: annotated = dict(query_row) annotated.update(infer_canonical_subitem(query_row)) return annotated
def build_subitem_and_family_rows( *, query_rows: list[dict[str, Any]], context_fields: Mapping[str, Any], score_field: str = "query_score", missingness_applicable: bool = True,) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: subitem_rows: list[dict[str, Any]] = [] family_rows: list[dict[str, Any]] = []
by_family_subitem: dict[tuple[str, str], list[dict[str, Any]]] = {} family_query_counts: dict[str, int] = {} for row in query_rows: family_id = _normalize_family(row.get("family_id")) subitem_id = str(row.get("canonical_subitem_id") or "") if family_id not in CANONICAL_ANALYTICS_SUBITEMS or not subitem_id: continue if family_id == "missingness_structure" and not missingness_applicable: continue by_family_subitem.setdefault((family_id, subitem_id), []).append(row) family_query_counts[family_id] = family_query_counts.get(family_id, 0) + 1
for family_id, subitems in CANONICAL_ANALYTICS_SUBITEMS.items(): active_scores: list[float] = [] for order_index, subitem_id in enumerate(subitems, start=1): applicable = not (family_id == "missingness_structure" and not missingness_applicable) rows = by_family_subitem.get((family_id, subitem_id), []) score_values = [ float(item.get(score_field)) for item in rows if item.get(score_field) is not None ] score = mean(score_values) if score_values else None if applicable and score is not None: active_scores.append(float(score)) inference_sources = sorted({str(item.get("subitem_inference_source") or "") for item in rows if item.get("subitem_inference_source")}) subitem_rows.append( { **context_fields, "family_id": family_id, "subitem_id": subitem_id, "subitem_order": order_index, "subitem_score": round(float(score), 6) if score is not None else None, "query_count": len(rows), "subitem_applicable": applicable, "subitem_inference_sources": ",".join(inference_sources), "contract_version": ANALYTICS_CONTRACT_VERSION, } )
family_score = mean(active_scores) if active_scores else None family_rows.append( { **context_fields, "family_id": family_id, "family_score": round(float(family_score), 6) if family_score is not None else None, "query_count": family_query_counts.get(family_id, 0), "active_subitem_count": len(active_scores), "subitem_count": len(subitems), "contract_version": ANALYTICS_CONTRACT_VERSION, } )
return subitem_rows, family_rows123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629"""Shared utilities for synthetic-data evaluation."""
from __future__ import annotations
import csvimport hashlibimport jsonimport mathimport osimport reimport sqlite3import timefrom collections import Counter, defaultdictfrom dataclasses import asdict, dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterable
from src.eval.subitem_workload_v2.paths import ( SUPPORTED_LINE_VERSIONS, normalize_line_version, registry_dir, run_manifest_dir, runs_root,)from src.eval.subitem_workload_v2.registry import load_registry_rows
PROJECT_ROOT = Path(__file__).resolve().parents[2]
def _env_path(name: str, default: Path) -> Path: value = os.environ.get(name, "").strip() return Path(value).expanduser() if value else default
DATA_ROOT = _env_path("EVAL_REAL_DATA_ROOT", PROJECT_ROOT / "data")LOGS_ROOT = _env_path("EVAL_LOGS_ROOT", PROJECT_ROOT / "logs" / "runs")OUTPUT_ROOT = _env_path("EVAL_OUTPUT_ROOT", PROJECT_ROOT / "Evaluation")SQL_RESULT_ROLE_ANNOTATION_ROOT = DATA_ROOT / "sql_result_role_annotations_v1" / "datasets"
PROVENANCE_CONTRACT_VERSION = "evaluation_source_provenance_v1"SQL_SOURCE_VERSION_ENV_VAR = "EVAL_SQL_SOURCE_VERSION"SQL_SOURCE_VERSION_V1 = "v1"SQL_SOURCE_VERSION_V2 = "v2"SQL_SOURCE_VERSION_V3 = "v3"SQL_SOURCE_VERSION_V4 = "v4"CURRENT_SQL_SOURCE_VERSIONS = tuple(SUPPORTED_LINE_VERSIONS)SQL_SOURCE_VERSION_CHOICES = ( SQL_SOURCE_VERSION_V1, *CURRENT_SQL_SOURCE_VERSIONS,)DEFAULT_SQL_SOURCE_VERSION = SQL_SOURCE_VERSION_V2
_SQL_SOURCE_LABELS = { SQL_SOURCE_VERSION_V1: "v1_legacy", SQL_SOURCE_VERSION_V2: "v2_current", SQL_SOURCE_VERSION_V3: "v3_current", SQL_SOURCE_VERSION_V4: "v4_current",}_SQL_SOURCE_DESCRIPTIONS = { SQL_SOURCE_VERSION_V1: "legacy grounded SQL runs under logs/runs/", SQL_SOURCE_VERSION_V2: "current registry-backed workload SQL under logs/subitem_workload_v2/", SQL_SOURCE_VERSION_V3: "current registry-backed workload SQL under logs/subitem_workload_v3/", SQL_SOURCE_VERSION_V4: "current registry-backed workload SQL under logs/subitem_workload_v4/",}_SQL_SOURCE_ALIASES = { "v1": SQL_SOURCE_VERSION_V1, "legacy": SQL_SOURCE_VERSION_V1, "v1_legacy": SQL_SOURCE_VERSION_V1, "logs/runs": SQL_SOURCE_VERSION_V1, "logs\\runs": SQL_SOURCE_VERSION_V1, "v2": SQL_SOURCE_VERSION_V2, "query_registry_v2": SQL_SOURCE_VERSION_V2, "current": SQL_SOURCE_VERSION_V2, "v2_current": SQL_SOURCE_VERSION_V2, "subitem_workload_v2": SQL_SOURCE_VERSION_V2, "logs/subitem_workload_v2": SQL_SOURCE_VERSION_V2, "logs\\subitem_workload_v2": SQL_SOURCE_VERSION_V2, "v3": SQL_SOURCE_VERSION_V3, "v3_current": SQL_SOURCE_VERSION_V3, "query_registry_v3": SQL_SOURCE_VERSION_V3, "subitem_workload_v3": SQL_SOURCE_VERSION_V3, "logs/subitem_workload_v3": SQL_SOURCE_VERSION_V3, "logs\\subitem_workload_v3": SQL_SOURCE_VERSION_V3, "v4": SQL_SOURCE_VERSION_V4, "v4_current": SQL_SOURCE_VERSION_V4, "query_registry_v4": SQL_SOURCE_VERSION_V4, "subitem_workload_v4": SQL_SOURCE_VERSION_V4, "logs/subitem_workload_v4": SQL_SOURCE_VERSION_V4, "logs\\subitem_workload_v4": SQL_SOURCE_VERSION_V4,}
ROOT_CONFIGS = { "SynOutput": { "path": _env_path("EVAL_SYNOUTPUT_ROOT", PROJECT_ROOT / "SynOutput"), "server_type": "rtx_pro_6000", "gpu_hour_ratio": 1.0, }, "SynOutput-5090": { "path": _env_path("EVAL_SYNOUTPUT_5090_ROOT", PROJECT_ROOT / "SynOutput-5090"), "server_type": "rtx_5090", "gpu_hour_ratio": 1.0, }, "Benchmark-trainonly-v1": { "path": _env_path("EVAL_BENCHMARK_TRAINONLY_ROOT", PROJECT_ROOT / "remote-output-Benchmark-trainonly-v1"), "server_type": "trainonly_serial", "gpu_hour_ratio": 1.0, }, "Hyperparameter-trainonly-v1": { "path": _env_path( "EVAL_HYPERPARAMETER_TRAINONLY_ROOT", PROJECT_ROOT / "hyperparameter" / "output-Benchmark-trainonly-v1", ), "server_type": "hyperparameter_trainonly", "gpu_hour_ratio": 1.0, }, "TabQueryBench-SynDataSuccess-main": { "path": _env_path( "EVAL_TABQUERYBENCH_MAIN_ROOT", Path("/data/jialinzhang/TabQueryBench/SynDataSuccess/main"), ), "server_type": "server_authoritative_main", "gpu_hour_ratio": 1.0, },}
USD_PER_GPU_HOUR = 1.0MAX_FALLBACK_GPU_SECONDS = 12 * 3600MISSING_TEXT = {"", "null", "none", "nan", "na", "n/a", "<null>"}TIMESTAMP_RE = re.compile(r"(\d{8}_\d{6})")RUNTIME_RESULT_RE = re.compile(r"(?P<prefix>.+?)__runtime_result\.json$", re.IGNORECASE)TRAIN_TIME_RE = re.compile( r"(?:totoal|total)\s+training\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)", re.IGNORECASE,)SAMPLE_TIME_RE = re.compile( r"(?:totoal|total)\s+sampling\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)", re.IGNORECASE,)GENERIC_SECONDS_RE = re.compile( r"(?:elapsed|duration|runtime|wall\s*time|completed\s+in|finished\s+in)\D+([0-9]+(?:\.[0-9]+)?)\s*(?:seconds|secs|s)?", re.IGNORECASE,)SUBITEM_RUNS_PATH_RE = re.compile( r"/logs/subitem_workload_(v[234])/runs/(?P<suffix>.+)$", re.IGNORECASE,)
@dataclassclass SyntheticAsset: dataset_id: str model_id: str server_type: str root_name: str root_path: str asset_dir: str run_id: str synthetic_csv_path: str metadata_paths: list[str] log_paths: list[str] discovered_via: str timestamp_utc: str | None synthetic_source_mtime_utc: str | None synthetic_source_size_bytes: int | None gpu_seconds_raw: float gpu_hours_equivalent: float gpu_hours_source: str cost_usd: float
@property def asset_key(self) -> str: return f"{self.dataset_id}__{self.server_type}__{self.model_id}__{self.run_id}"
@property def model_server_key(self) -> str: return f"{self.model_id}__{self.server_type}"
def to_dict(self) -> dict[str, Any]: row = asdict(self) row["asset_key"] = self.asset_key row["model_server_key"] = self.model_server_key row["provenance_contract_version"] = PROVENANCE_CONTRACT_VERSION row["synthetic_source_path"] = row["synthetic_csv_path"] row["synthetic_source_root_name"] = row["root_name"] row["synthetic_source_root_path"] = row["root_path"] row["synthetic_source_asset_dir"] = row["asset_dir"] row["synthetic_source_run_id"] = row["run_id"] row["synthetic_source_discovered_via"] = row["discovered_via"] return row
def now_run_tag() -> str: return datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
def read_json(path: Path, default: Any = None) -> Any: if not path.exists(): return default try: return json.loads(path.read_text(encoding="utf-8")) except Exception: return default
def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as f: for row in rows: f.write(json.dumps(row, ensure_ascii=False) + "\n")
def write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str] | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) if fieldnames is None: keys: set[str] = set() for row in rows: keys.update(row.keys()) fieldnames = sorted(keys) with path.open("w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() for row in rows: writer.writerow({key: row.get(key) for key in fieldnames})
def format_duration(seconds: float | int | None) -> str: if seconds is None: return "--:--:--" total_seconds = max(0, int(round(float(seconds)))) hours, rem = divmod(total_seconds, 3600) minutes, secs = divmod(rem, 60) return f"{hours:02d}:{minutes:02d}:{secs:02d}"
@dataclassclass TaskProgressTracker: task_name: str total_steps: int step_label: str = "datasets" substep_label: str = "assets" total_substeps: int = 0 completed_steps: int = 0 completed_substeps: int = 0
def __post_init__(self) -> None: self._start_ts = time.monotonic() self._last_print_ts = self._start_ts
def print_start(self, extra: str = "") -> None: parts = [ f"[{self.task_name}] start", f"{self.step_label}=0/{self.total_steps}", ] if self.total_substeps > 0: parts.append(f"{self.substep_label}=0/{self.total_substeps}") if extra: parts.append(extra) print(" | ".join(parts), flush=True)
def advance(self, *, step_name: str, substeps_done: int = 0, extra: str = "") -> None: self.completed_steps += 1 self.completed_substeps += max(0, int(substeps_done)) elapsed = time.monotonic() - self._start_ts avg_per_step = (elapsed / self.completed_steps) if self.completed_steps > 0 else None remaining_steps = max(0, self.total_steps - self.completed_steps) eta_seconds = (avg_per_step * remaining_steps) if avg_per_step is not None else None
parts = [ f"[{self.task_name}] {self.step_label}={self.completed_steps}/{self.total_steps}", ] if self.total_substeps > 0: parts.append(f"{self.substep_label}={self.completed_substeps}/{self.total_substeps}") parts.extend( [ f"elapsed={format_duration(elapsed)}", f"eta={format_duration(eta_seconds)}", f"done={step_name}", ] ) if extra: parts.append(extra) print(" | ".join(parts), flush=True)
def make_task_run_dir(task_name: str, run_tag: str) -> Path: run_dir = OUTPUT_ROOT / task_name / "runs" / run_tag run_dir.mkdir(parents=True, exist_ok=True) write_json(OUTPUT_ROOT / task_name / "LATEST_RUN.json", {"run_tag": run_tag, "run_dir": str(run_dir.resolve())}) return run_dir
def list_dataset_ids() -> list[str]: out: list[str] = [] if not DATA_ROOT.exists(): return out for path in sorted(DATA_ROOT.iterdir()): if not path.is_dir(): continue if path.name.startswith("."): continue train_csv = resolve_real_split_path(path.name, split="train") if train_csv.exists(): out.append(path.name) return out
def resolve_dataset_dir(dataset_id: str) -> Path: return DATA_ROOT / dataset_id
def resolve_real_split_path(dataset_id: str, split: str = "train") -> Path: candidates = [ DATA_ROOT / dataset_id / f"{dataset_id}-{split}.csv", DATA_ROOT / dataset_id / "raw" / f"{dataset_id}-{split}.csv", ] for path in candidates: if path.exists(): return path return candidates[0]
def resolve_field_registry_path(dataset_id: str) -> Path | None: candidates = [ DATA_ROOT / dataset_id / "metadata_core" / "field_registry.json", DATA_ROOT / dataset_id / "metadata" / "field_registry.json", ] for path in candidates: if path.exists(): return path return None
def load_field_registry(dataset_id: str) -> dict[str, Any]: path = resolve_field_registry_path(dataset_id) if path is None: return {} return read_json(path, {}) or {}
def load_field_type_hints(dataset_id: str) -> dict[str, str]: payload = load_field_registry(dataset_id) hints: dict[str, str] = {} for item in payload.get("fields", []) if isinstance(payload, dict) else []: if not isinstance(item, dict): continue name = str(item.get("name") or "").strip() if not name: continue semantic = str(item.get("semantic_type") or "").strip().lower() declared = str(item.get("declared_type") or "").strip().lower() hints[name] = semantic or declared return hints
def resolve_sql_result_role_annotation_path(dataset_id: str) -> Path: return SQL_RESULT_ROLE_ANNOTATION_ROOT / dataset_id / "outputs" / "sql_result_roles_ai_v1.json"
def load_sql_result_role_annotations( dataset_id: str, *, sql_source_version: str | None = None,) -> dict[tuple[str, str], dict[str, Any]]: path = resolve_sql_result_role_annotation_path(dataset_id) payload = read_json(path, {}) or {} query_annotations = payload.get("query_annotations") if isinstance(payload, dict) else [] requested_version = normalize_sql_source_version(sql_source_version) if sql_source_version else None
output: dict[tuple[str, str], dict[str, Any]] = {} if not isinstance(query_annotations, list): return output
for item in query_annotations: if not isinstance(item, dict): continue version_text = str(item.get("sql_source_version") or "").strip() query_id = str(item.get("query_id") or "").strip() if not query_id: continue try: normalized_version = normalize_sql_source_version(version_text or requested_version or DEFAULT_SQL_SOURCE_VERSION) except Exception: continue if requested_version and normalized_version != requested_version: continue output[(normalized_version, query_id)] = item return output
def parse_timestamp_text(value: str | None) -> datetime | None: if not value: return None text = str(value).strip() try: if text.endswith("Z"): text = text[:-1] + "+00:00" parsed = datetime.fromisoformat(text) if parsed.tzinfo is None: parsed = parsed.replace(tzinfo=timezone.utc) return parsed.astimezone(timezone.utc) except Exception: pass match = TIMESTAMP_RE.search(text) if not match: return None try: return datetime.strptime(match.group(1), "%Y%m%d_%H%M%S").replace(tzinfo=timezone.utc) except Exception: return None
def _candidate_timestamps(*values: str | Path | None) -> list[datetime]: out: list[datetime] = [] for value in values: if value is None: continue parsed = parse_timestamp_text(str(value)) if parsed is not None: out.append(parsed) return out
def _stat_mtime_ts(path: Path | None) -> datetime | None: if path is None or not path.exists(): return None try: return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc) except Exception: return None
def _stat_size_bytes(path: Path | None) -> int | None: if path is None or not path.exists(): return None try: return int(path.stat().st_size) except Exception: return None
def _resolved_path_text(path: Path | None) -> str: if path is None: return "" try: return str(path.expanduser().resolve()) except Exception: return str(path)
def _path_provenance_fields(prefix: str, path: Path | None) -> dict[str, Any]: mtime = _stat_mtime_ts(path) return { f"{prefix}_path": _resolved_path_text(path), f"{prefix}_exists": bool(path and path.exists()), f"{prefix}_mtime_utc": (mtime.isoformat() if mtime is not None else None), f"{prefix}_size_bytes": _stat_size_bytes(path), }
def _sha256_text(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _resolve_registry_backed_path(raw_path: str | Path | None) -> Path: text = str(raw_path or "").strip() if not text: return Path("") candidate = Path(text).expanduser() if candidate.exists(): return candidate
normalized = text.replace("\\", "/") marker = "/SQLagent/" if marker in normalized: suffix = normalized.split(marker, 1)[1].lstrip("/") rebased = (PROJECT_ROOT / suffix).resolve() if rebased.exists(): return rebased
if normalized.startswith("SQLagent/"): rebased = (PROJECT_ROOT / normalized[len("SQLagent/"):]).resolve() if rebased.exists(): return rebased
match = SUBITEM_RUNS_PATH_RE.search(normalized) if match: version = match.group(1).lower() suffix = match.group("suffix").lstrip("/") rebased = (runs_root(version) / suffix).resolve() if rebased.exists(): return rebased
return candidate
def sql_source_family(version: str | None) -> str: normalized = normalize_sql_source_version(version) return "legacy" if normalized == SQL_SOURCE_VERSION_V1 else "current"
def sql_source_line_version(version: str | None) -> str: normalized = normalize_sql_source_version(version) return normalized if normalized in CURRENT_SQL_SOURCE_VERSIONS else ""
def sql_source_registry_root(version: str | None) -> Path | None: normalized = normalize_sql_source_version(version) if normalized == SQL_SOURCE_VERSION_V1: return None return registry_dir(normalized)
def is_current_sql_source_version(version: str | None) -> bool: return normalize_sql_source_version(version) in CURRENT_SQL_SOURCE_VERSIONS
def real_split_provenance(dataset_id: str, split: str = "train") -> dict[str, Any]: real_path = resolve_real_split_path(dataset_id, split=split) return { "provenance_contract_version": PROVENANCE_CONTRACT_VERSION, "real_reference_split": split, "real_source_kind": "reference_split_csv", "real_source_dataset_id": dataset_id, "real_source_split": split, **_path_provenance_fields("real_source", real_path), }
def resolve_latest_task_run_dir(task_name: str) -> Path | None: latest_path = OUTPUT_ROOT / task_name / "LATEST_RUN.json" payload = read_json(latest_path, {}) or {} run_dir = payload.get("run_dir") if not run_dir: return None candidate = Path(str(run_dir)) return candidate if candidate.exists() else None
def resolve_requested_sql_source_version( task_name: str | None = None, default: str = DEFAULT_SQL_SOURCE_VERSION,) -> str: override = str(os.environ.get(SQL_SOURCE_VERSION_ENV_VAR) or "").strip() if override: return normalize_sql_source_version(override) if task_name: return resolve_latest_task_sql_source_version(task_name, default=default) return normalize_sql_source_version(default)
def resolve_latest_task_sql_source_version(task_name: str, default: str = DEFAULT_SQL_SOURCE_VERSION) -> str: run_dir = resolve_latest_task_run_dir(task_name) if run_dir is None: return normalize_sql_source_version(default) manifest = read_json(run_dir / "manifest.json", {}) or {} try: return normalize_sql_source_version(str(manifest.get("sql_source_version") or default)) except Exception: return normalize_sql_source_version(default)
def resolve_task_run_dir_for_sql_source( task_name: str, sql_source_version: str | None = None, *, default: str = DEFAULT_SQL_SOURCE_VERSION,) -> Path | None: requested = resolve_requested_sql_source_version(task_name=task_name, default=default) target_version = normalize_sql_source_version(sql_source_version or requested) latest_run_dir = resolve_latest_task_run_dir(task_name) if latest_run_dir is not None: latest_manifest = read_json(latest_run_dir / "manifest.json", {}) or {} latest_version = str(latest_manifest.get("sql_source_version") or "").strip() if latest_version: try: if normalize_sql_source_version(latest_version) == target_version: return latest_run_dir except Exception: pass
runs_root_dir = OUTPUT_ROOT / task_name / "runs" if not runs_root_dir.exists(): return None
ranked: list[tuple[int, int, str, Path]] = [] for candidate in runs_root_dir.iterdir(): if not candidate.is_dir(): continue manifest_path = candidate / "manifest.json" if not manifest_path.exists(): continue manifest = read_json(manifest_path, {}) or {} manifest_version = str(manifest.get("sql_source_version") or "").strip() if not manifest_version: continue try: if normalize_sql_source_version(manifest_version) != target_version: continue except Exception: continue ranked.append( ( int(manifest.get("dataset_count") or 0), int(manifest.get("asset_count") or 0), candidate.name, candidate.resolve(), ) ) if not ranked: return None ranked.sort(reverse=True) return ranked[0][3]
def build_sql_source_provenance( *, sql_source_version: str, sql_source_kind: str, sql_source_selection_mode: str, source_run_id: str = "", sql_file_path: Path | None = None, manifest_path: Path | None = None, registry_path: Path | None = None, run_dir: Path | None = None, dataset_dir: Path | None = None, registry_version: str = "", declared_version: str = "", declared_label: str = "", sql_file_sha256: str = "",) -> dict[str, Any]: normalized = normalize_sql_source_version(sql_source_version) registry_root = sql_source_registry_root(normalized) return { "provenance_contract_version": PROVENANCE_CONTRACT_VERSION, "sql_source_family": sql_source_family(normalized), "sql_source_line_version": sql_source_line_version(normalized), "sql_source_version": normalized, "sql_source_label": sql_source_label(normalized), "sql_source_description": sql_source_description(normalized), "sql_source_root": _resolved_path_text(sql_source_root(normalized)), "sql_source_registry_root": _resolved_path_text(registry_root), "sql_source_kind": sql_source_kind, "sql_source_selection_mode": sql_source_selection_mode, "sql_source_registry_version": str(registry_version or ""), "sql_source_declared_version": str(declared_version or ""), "sql_source_declared_label": str(declared_label or ""), "sql_source_file_sha256": str(sql_file_sha256 or ""), "source_run_id": str(source_run_id or ""), "sql_origin_path": _resolved_path_text(sql_file_path), **_path_provenance_fields("sql_source_file", sql_file_path), **_path_provenance_fields("sql_source_manifest", manifest_path), **_path_provenance_fields("sql_source_registry", registry_path), **_path_provenance_fields("sql_source_run_dir", run_dir), **_path_provenance_fields("sql_source_dataset_dir", dataset_dir), }
def _find_local_artifact_by_name(search_root: Path, name: str) -> Path | None: if not name: return None for path in search_root.rglob(name): if path.is_file(): return path return None
def _choose_synthetic_csv(candidates: list[Path]) -> Path | None: filtered = _list_synthetic_csv_candidates(candidates) if not filtered: return None filtered.sort(key=lambda p: (parse_timestamp_text(p.name) or _stat_mtime_ts(p) or datetime.min.replace(tzinfo=timezone.utc))) return filtered[-1]
def _list_synthetic_csv_candidates(candidates: Iterable[Path]) -> list[Path]: return [path for path in candidates if _is_synthetic_candidate_csv(path)]
def _is_synthetic_candidate_csv(path: Path) -> bool: lname = path.name.lower() stem = path.stem.lower() if "train_continuous_imputed" in lname: return False for suffix in ("real", "test", "val", "train"): if f"__{suffix}.csv" in lname or lname.endswith(f"_{suffix}.csv") or stem.endswith(f"_{suffix}"): return False return True
def _synthetic_candidate_sort_key(path: Path) -> datetime: return parse_timestamp_text(path.name) or _stat_mtime_ts(path) or datetime.min.replace(tzinfo=timezone.utc)
def _runtime_result_prefix(path: Path) -> str: match = RUNTIME_RESULT_RE.match(path.name) if match: return str(match.group("prefix") or "").strip() return path.stem
def _match_runtime_payload_for_synthetic_csv(runtime_files: list[Path], synthetic_csv_path: Path) -> tuple[dict[str, Any], Path | None]: synthetic_name = synthetic_csv_path.name for runtime_file in sorted(runtime_files, reverse=True): prefix = _runtime_result_prefix(runtime_file) if prefix and synthetic_name.startswith(prefix): return read_json(runtime_file, {}) or {}, runtime_file if runtime_files: chosen = sorted(runtime_files)[-1] return read_json(chosen, {}) or {}, chosen return {}, None
def _derive_run_id_for_candidate(runtime_run_id: str, synthetic_csv_path: Path) -> str: stem = synthetic_csv_path.stem if runtime_run_id and runtime_run_id in stem: suffix = stem.split(runtime_run_id, 1)[1].strip("_-") if suffix: return f"{runtime_run_id}__{suffix}" return runtime_run_id if runtime_run_id: return runtime_run_id return stem
def _extract_gpu_seconds_from_logs(log_paths: list[Path], synthetic_csv_path: Path | None = None) -> tuple[float, str]: explicit_seconds = 0.0 saw_explicit = False for path in log_paths: try: text = path.read_text(encoding="utf-8", errors="ignore") except Exception: continue for regex in [TRAIN_TIME_RE, SAMPLE_TIME_RE, GENERIC_SECONDS_RE]: for match in regex.findall(text): try: explicit_seconds += float(match) saw_explicit = True except Exception: continue if saw_explicit and explicit_seconds > 0: return explicit_seconds, "explicit_log_seconds"
inferred_seconds = 0.0 for path in log_paths: start_ts = parse_timestamp_text(path.name) or parse_timestamp_text(path.stem) end_ts = _stat_mtime_ts(path) if start_ts is not None and end_ts is not None: delta = (end_ts - start_ts).total_seconds() if 0 < delta <= MAX_FALLBACK_GPU_SECONDS: inferred_seconds += delta if inferred_seconds > 0: return inferred_seconds, "log_mtime_fallback"
if log_paths and synthetic_csv_path is not None and synthetic_csv_path.exists(): start_candidates = [parse_timestamp_text(path.name) for path in log_paths] start_candidates = [item for item in start_candidates if item is not None] end_ts = _stat_mtime_ts(synthetic_csv_path) if start_candidates and end_ts is not None: delta = (end_ts - min(start_candidates)).total_seconds() if 0 < delta <= MAX_FALLBACK_GPU_SECONDS: return delta, "artifact_mtime_fallback"
return 0.0, "unavailable_zero"
def _extract_gpu_seconds_from_runtime_payload(runtime_payload: dict[str, Any] | None) -> tuple[float, str] | None: if not isinstance(runtime_payload, dict): return None timings = runtime_payload.get("timings") if not isinstance(timings, dict): return None total_seconds = 0.0 saw_duration = False for stage_name in ("train", "generate"): stage_payload = timings.get(stage_name) if not isinstance(stage_payload, dict): continue raw_value = stage_payload.get("duration_sec") if raw_value is None: continue try: duration_sec = float(raw_value) except Exception: continue if duration_sec > 0: total_seconds += duration_sec saw_duration = True if saw_duration: return total_seconds, "runtime_result_timings" return None
def _hyperparameter_tabsyn_is_consistent_batch(env_overrides: dict[str, Any]) -> bool: # Accept any successful Tabsyn hyperparameter run that explicitly varies # training knobs. Older code only admitted one very specific sweep shape, # which filtered out newer smoke/BO runs (e.g. smaller batch sizes). keys = {str(k): v for k, v in env_overrides.items()} has_batch = any( str(keys.get(name) or "").strip() for name in ( "TABSYN_VAE_BATCH_SIZE", "TABSYN_DIFFUSION_BATCH_SIZE", "TABSYN_VAE_ENCODE_BATCH_SIZE", "TABSYN_VAE_EVAL_BATCH_SIZE", "TABSYN_VAE_INFER_BATCH_SIZE", ) ) has_epoch = any( str(keys.get(name) or "").strip() for name in ( "TABSYN_VAE_EPOCHS", "TABSYN_DIFFUSION_MAX_EPOCHS", ) ) if not (has_batch and has_epoch): return False num_workers = str(keys.get("TABSYN_VAE_NUM_WORKERS") or "").strip() if num_workers and num_workers != "0": return False return True
def _should_keep_hyperparameter_run(*, model_id: str, run_config_payload: dict[str, Any], runtime_payload: dict[str, Any]) -> bool: if str(runtime_payload.get("train_status") or "").strip().lower() != "success": return False if str(runtime_payload.get("generate_status") or "").strip().lower() != "success": return False env_overrides = run_config_payload.get("env_overrides") if not isinstance(env_overrides, dict) or not env_overrides: return False if str(model_id or "").strip().lower() == "tabsyn": if _hyperparameter_tabsyn_is_consistent_batch(env_overrides): return True cli_args = run_config_payload.get("cli_args") cli_args = cli_args if isinstance(cli_args, dict) else {} has_epoch_signal = bool(str(cli_args.get("epochs") or "").strip()) or any( str(env_overrides.get(name) or "").strip() for name in ("TABSYN_VAE_EPOCHS", "TABSYN_DIFFUSION_MAX_EPOCHS") ) has_batch_signal = any( str(env_overrides.get(name) or "").strip() for name in ( "TABSYN_VAE_BATCH_SIZE", "TABSYN_DIFFUSION_BATCH_SIZE", "TABSYN_VAE_ENCODE_BATCH_SIZE", "TABSYN_VAE_EVAL_BATCH_SIZE", "TABSYN_VAE_INFER_BATCH_SIZE", ) ) return has_epoch_signal and has_batch_signal return True
def _has_substantive_hyperparameter_overrides(env_overrides: dict[str, Any]) -> bool: for key, value in env_overrides.items(): if str(key).startswith("BENCHMARK_"): continue if value is None: continue if str(value).strip(): return True return False
def _build_asset( *, dataset_id: str, model_id: str, root_name: str, asset_dir: Path, run_id: str, synthetic_csv_path: Path, metadata_paths: list[Path], log_paths: list[Path], discovered_via: str, runtime_payload: dict[str, Any] | None = None,) -> SyntheticAsset: cfg = ROOT_CONFIGS[root_name] timestamp_candidates = [] timestamp_candidates.extend(_candidate_timestamps(run_id, synthetic_csv_path.name)) timestamp_candidates.extend(item for item in (_stat_mtime_ts(synthetic_csv_path), _stat_mtime_ts(asset_dir)) if item is not None) timestamp = max(timestamp_candidates) if timestamp_candidates else None runtime_timing = _extract_gpu_seconds_from_runtime_payload(runtime_payload) if runtime_timing is not None: gpu_seconds_raw, gpu_source = runtime_timing else: gpu_seconds_raw, gpu_source = _extract_gpu_seconds_from_logs(log_paths, synthetic_csv_path) gpu_hours_equivalent = (gpu_seconds_raw / 3600.0) * float(cfg["gpu_hour_ratio"]) return SyntheticAsset( dataset_id=dataset_id, model_id=model_id, server_type=str(cfg["server_type"]), root_name=root_name, root_path=str(Path(cfg["path"]).resolve()), asset_dir=str(asset_dir.resolve()), run_id=run_id, synthetic_csv_path=str(synthetic_csv_path.resolve()), metadata_paths=[str(path.resolve()) for path in metadata_paths], log_paths=[str(path.resolve()) for path in log_paths], discovered_via=discovered_via, timestamp_utc=(timestamp.isoformat() if timestamp is not None else None), synthetic_source_mtime_utc=(_stat_mtime_ts(synthetic_csv_path).isoformat() if _stat_mtime_ts(synthetic_csv_path) is not None else None), synthetic_source_size_bytes=_stat_size_bytes(synthetic_csv_path), gpu_seconds_raw=round(gpu_seconds_raw, 6), gpu_hours_equivalent=round(gpu_hours_equivalent, 6), gpu_hours_source=gpu_source, cost_usd=round(gpu_hours_equivalent * USD_PER_GPU_HOUR, 6), )
def _discover_assets_in_synoutput(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()): manifest_path = run_dir / "manifest.json" if not manifest_path.exists(): continue manifest = read_json(manifest_path, {}) or {} runtime_result = manifest.get("runtime_result") if isinstance(manifest, dict) else {} artifacts = runtime_result.get("artifacts") if isinstance(runtime_result, dict) else {} desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None if synthetic_csv_path is None: synthetic_csv_path = _choose_synthetic_csv(list((run_dir / "synthetic").glob("*.csv"))) if synthetic_csv_path is None: continue run_id = str(runtime_result.get("run_id") or manifest.get("run_id") or run_dir.name) log_paths = sorted((run_dir / "logs").glob("*.log")) metadata_paths = [manifest_path] + sorted((run_dir / "meta").glob("*.json")) assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=run_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via="manifest_json", ) ) return assets
def _discover_assets_in_synoutput_5090(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name runtime_files = sorted((model_dir / "metadata").glob("*__runtime_result.json")) synthetic_candidates = sorted( _list_synthetic_csv_candidates((model_dir / "synthetic_data").glob("*.csv")), key=_synthetic_candidate_sort_key, ) if not synthetic_candidates: continue metadata_paths_all = sorted((model_dir / "metadata").glob("*.json")) log_paths = sorted((model_dir / "logs").glob("*.log"))
for synthetic_csv_path in synthetic_candidates: runtime_payload, matched_runtime = _match_runtime_payload_for_synthetic_csv(runtime_files, synthetic_csv_path) runtime_run_id = str(runtime_payload.get("run_id") or model_dir.name) run_id = _derive_run_id_for_candidate(runtime_run_id, synthetic_csv_path) metadata_paths = list(metadata_paths_all) if matched_runtime is not None and matched_runtime not in metadata_paths: metadata_paths = [matched_runtime] + metadata_paths assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=model_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via=("runtime_result_json_matched" if matched_runtime is not None else "synthetic_csv_scan"), ) ) return assets
def _discover_assets_in_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()): runtime_path = run_dir / "runtime_result.json" runtime_payload = read_json(runtime_path, {}) or {} if not isinstance(runtime_payload, dict): continue artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {} desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name candidate_files = list(run_dir.glob("*.csv")) synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None if synthetic_csv_path is None: synthetic_csv_path = _choose_synthetic_csv(candidate_files) if synthetic_csv_path is None: continue
run_id = str(runtime_payload.get("run_id") or run_dir.name) log_paths = sorted(run_dir.glob("*.log")) metadata_paths = [runtime_path] if runtime_path.exists() else [] for extra in [ run_dir / "input_snapshot.json", run_dir / "run_config.json", run_dir / "public_gate" / "public_gate_report.json", run_dir / "public_gate" / "normalized_schema_snapshot.json", run_dir / "public_gate" / "staged_input_manifest.json", ]: if extra.exists() and extra not in metadata_paths: metadata_paths.append(extra) assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=run_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via="runtime_result_json", runtime_payload=runtime_payload, ) ) return assets
def _discover_assets_in_hyperparameter_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]: root = Path(ROOT_CONFIGS[root_name]["path"]) dataset_root = root / dataset_id if not dataset_root.exists(): return [] assets: list[SyntheticAsset] = [] for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()): model_id = model_dir.name candidate_runs: list[tuple[Path, dict[str, Any], dict[str, Any], bool]] = [] for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()): runtime_path = run_dir / "runtime_result.json" run_config_path = run_dir / "run_config.json" runtime_payload = read_json(runtime_path, {}) or {} run_config_payload = read_json(run_config_path, {}) or {} if not isinstance(runtime_payload, dict) or not isinstance(run_config_payload, dict): continue if not _should_keep_hyperparameter_run( model_id=model_id, run_config_payload=run_config_payload, runtime_payload=runtime_payload, ): continue env_overrides = run_config_payload.get("env_overrides") env_overrides = env_overrides if isinstance(env_overrides, dict) else {} candidate_runs.append( ( run_dir, runtime_payload, run_config_payload, _has_substantive_hyperparameter_overrides(env_overrides), ) )
if not candidate_runs: continue keep_only_substantive = any(item[3] for item in candidate_runs) for run_dir, runtime_payload, run_config_payload, has_substantive_overrides in candidate_runs: if keep_only_substantive and not has_substantive_overrides: continue artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {} desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name candidate_files = list(run_dir.glob("*.csv")) synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None if synthetic_csv_path is None: synthetic_csv_path = _choose_synthetic_csv(candidate_files) if synthetic_csv_path is None: continue
run_id = str(runtime_payload.get("run_id") or run_dir.name) log_paths = sorted(run_dir.glob("*.log")) metadata_paths = [runtime_path] if runtime_path.exists() else [] for extra in [ run_config_path, run_dir / "input_snapshot.json", run_dir / "public_gate" / "public_gate_report.json", run_dir / "public_gate" / "normalized_schema_snapshot.json", run_dir / "public_gate" / "staged_input_manifest.json", ]: if extra.exists() and extra not in metadata_paths: metadata_paths.append(extra) assets.append( _build_asset( dataset_id=dataset_id, model_id=model_id, root_name=root_name, asset_dir=run_dir, run_id=run_id, synthetic_csv_path=synthetic_csv_path, metadata_paths=metadata_paths, log_paths=log_paths, discovered_via="runtime_result_json_hyperparameter", runtime_payload=runtime_payload, ) ) return assets
def discover_synthetic_assets( *, datasets: list[str] | None = None, latest_only: bool = True, root_names: list[str] | tuple[str, ...] | None = None,) -> list[SyntheticAsset]: dataset_ids = datasets or list_dataset_ids() requested_roots = [str(item).strip() for item in (root_names or []) if str(item).strip()] if requested_roots: invalid = sorted(set(requested_roots) - set(ROOT_CONFIGS.keys())) if invalid: raise ValueError(f"Unsupported synthetic root names: {invalid}. Available: {sorted(ROOT_CONFIGS.keys())}") active_roots = requested_roots or list(ROOT_CONFIGS.keys()) assets: list[SyntheticAsset] = [] for dataset_id in dataset_ids: for root_name in active_roots: if root_name == "SynOutput": assets.extend(_discover_assets_in_synoutput(dataset_id, root_name)) elif root_name == "SynOutput-5090": assets.extend(_discover_assets_in_synoutput_5090(dataset_id, root_name)) elif root_name == "Benchmark-trainonly-v1": assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name)) elif root_name == "Hyperparameter-trainonly-v1": assets.extend(_discover_assets_in_hyperparameter_trainonly_root(dataset_id, root_name)) elif root_name == "TabQueryBench-SynDataSuccess-main": assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name)) if not latest_only: return sorted(assets, key=lambda item: (item.dataset_id, item.server_type, item.model_id, item.timestamp_utc or ""))
latest_map: dict[tuple[str, str, str], SyntheticAsset] = {} for asset in assets: key = (asset.dataset_id, asset.server_type, asset.model_id) current = latest_map.get(key) asset_ts = parse_timestamp_text(asset.timestamp_utc or "") current_ts = parse_timestamp_text(current.timestamp_utc or "") if current else None if current is None or ((asset_ts or datetime.min.replace(tzinfo=timezone.utc)) >= (current_ts or datetime.min.replace(tzinfo=timezone.utc))): latest_map[key] = asset return sorted(latest_map.values(), key=lambda item: (item.dataset_id, item.server_type, item.model_id))
def split_sql_statements(sql_text: str) -> list[str]: statements: list[str] = [] buf: list[str] = [] in_single = False in_double = False prev = "" for ch in sql_text: if ch == "'" and not in_double and prev != "\\": in_single = not in_single elif ch == '"' and not in_single and prev != "\\": in_double = not in_double if ch == ";" and not in_single and not in_double: stmt = "".join(buf).strip() if stmt: statements.append(stmt) buf = [] else: buf.append(ch) prev = ch tail = "".join(buf).strip() if tail: statements.append(tail) cleaned = [] for stmt in statements: lines = [line for line in stmt.splitlines() if not line.strip().startswith("--")] candidate = "\n".join(lines).strip() if candidate: cleaned.append(candidate) return cleaned
def normalize_sql_source_version(value: str | None) -> str: text = str(value or "").strip().lower() if not text: return DEFAULT_SQL_SOURCE_VERSION match = re.search(r"(v[1-4])", text) if match and match.group(1) in SQL_SOURCE_VERSION_CHOICES: candidate = match.group(1) if candidate == SQL_SOURCE_VERSION_V1 and "subitem_workload" in text: candidate = "" if candidate: return candidate version = _SQL_SOURCE_ALIASES.get(text) if version is None: raise ValueError( f"Unsupported sql source version: {value!r}. Expected one of: {', '.join(SQL_SOURCE_VERSION_CHOICES)}" ) return version
def sql_source_label(version: str | None) -> str: normalized = normalize_sql_source_version(version) return _SQL_SOURCE_LABELS[normalized]
def sql_source_description(version: str | None) -> str: normalized = normalize_sql_source_version(version) return _SQL_SOURCE_DESCRIPTIONS[normalized]
def sql_source_root(version: str | None) -> Path: normalized = normalize_sql_source_version(version) if normalized == SQL_SOURCE_VERSION_V1: return LOGS_ROOT if normalized in CURRENT_SQL_SOURCE_VERSIONS: return runs_root(normalized) raise ValueError(f"Unsupported sql source version: {version!r}")
def resolve_sql_run_dir(*, sql_source_version: str, run_id: str, dataset_id: str | None = None) -> Path: normalized = normalize_sql_source_version(sql_source_version) if normalized == SQL_SOURCE_VERSION_V1: return LOGS_ROOT / run_id if not dataset_id: raise ValueError("dataset_id is required when resolving a current workload run directory.") return runs_root(normalized) / run_id / dataset_id
def _load_latest_v1_sql_query_groups( *, dataset_ids: Iterable[str] | None = None, engines: tuple[str, ...] = ("cli",),) -> dict[tuple[str, str], dict[str, Any]]: grouped: dict[tuple[str, str], dict[str, Any]] = {} if not LOGS_ROOT.exists(): return grouped
dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()} for manifest_path in LOGS_ROOT.rglob("run_manifest.json"): payload = read_json(manifest_path, {}) or {} if str(payload.get("status") or "") != "completed": continue if str(payload.get("mode") or "") != "template_grounded_sql_qa": continue dataset_id = str(payload.get("dataset_id") or "").strip() if not dataset_id: continue if dataset_filter and dataset_id not in dataset_filter: continue engine = str(payload.get("engine") or "").strip() if engines and engine not in engines: continue question_record = payload.get("question_record") if not isinstance(question_record, dict): continue question_id = str(question_record.get("question_id") or "").strip() if not question_id: continue sql_path = manifest_path.parent / "generated_sql.sql" if not sql_path.exists(): continue ended_at = str(payload.get("ended_at") or payload.get("started_at") or "") key = (dataset_id, question_id) current = grouped.get(key) if current is None: grouped[key] = { "payload": payload, "sql_path": sql_path, "sort_dt": parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc), "manifest_path": manifest_path, } continue new_dt = parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc) if new_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)): grouped[key] = { "payload": payload, "sql_path": sql_path, "sort_dt": new_dt, "manifest_path": manifest_path, } return grouped
def _current_query_manifest_path( *, run_id: str, dataset_id: str, query_record_id: str, sql_source_version: str,) -> Path: normalized = normalize_line_version(sql_source_version) return run_manifest_dir(run_id, dataset_id, line_version=normalized) / query_record_id / "run_manifest.json"
def _load_latest_current_sql_query_groups( *, sql_source_version: str, dataset_ids: Iterable[str] | None = None, engines: tuple[str, ...] = ("cli",), require_accepted_for_eval: bool = True,) -> dict[tuple[str, str], dict[str, Any]]: grouped: dict[tuple[str, str], dict[str, Any]] = {} normalized = normalize_sql_source_version(sql_source_version) registry_root = registry_dir(normalized) if not registry_root.exists(): return grouped
dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()} for registry_path in sorted(registry_root.glob(f"*_query_registry_{normalized}.jsonl")): for row in load_registry_rows(registry_path): dataset_id = str(row.get("dataset_id") or "").strip() if not dataset_id: continue if dataset_filter and dataset_id not in dataset_filter: continue engine = str(row.get("engine") or "").strip() if engines and engine not in engines: continue if require_accepted_for_eval and not bool(row.get("accepted_for_eval")): continue query_record_id = str(row.get("query_record_id") or "").strip() if not query_record_id: continue sql_path = _resolve_registry_backed_path(row.get("sql_path")) if not sql_path.exists(): continue run_id = str(row.get("round_id") or "").strip() manifest_path = _current_query_manifest_path( run_id=run_id, dataset_id=dataset_id, query_record_id=query_record_id, sql_source_version=normalized, ) manifest = read_json(manifest_path, {}) or {} sort_dt = ( parse_timestamp_text(str(manifest.get("ended_at") or manifest.get("started_at") or "")) or _stat_mtime_ts(sql_path) or _stat_mtime_ts(manifest_path) or _stat_mtime_ts(registry_path) or datetime.min.replace(tzinfo=timezone.utc) ) key = (dataset_id, query_record_id) current = grouped.get(key) if current is None or sort_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)): grouped[key] = { "row": row, "sql_path": sql_path, "registry_path": registry_path, "manifest_path": manifest_path, "manifest": manifest, "sql_source_version": normalized, "sort_dt": sort_dt, } return grouped
def load_latest_sql_queries_by_dataset( *, dataset_ids: Iterable[str], engines: tuple[str, ...] = ("cli",), include_all_statements: bool = True, sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,) -> dict[str, list[dict[str, Any]]]: dataset_ids = [str(item).strip() for item in dataset_ids if str(item).strip()] normalized_source = normalize_sql_source_version(sql_source_version) rows_by_dataset: dict[str, list[dict[str, Any]]] = defaultdict(list) if normalized_source == SQL_SOURCE_VERSION_V1: grouped = _load_latest_v1_sql_query_groups(dataset_ids=dataset_ids, engines=engines) for (dataset_id, question_id), item in sorted(grouped.items()): payload = item["payload"] sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore") sql_file_hash = _sha256_text(sql_text) statements = split_sql_statements(sql_text) if not statements: continue if not include_all_statements: statements = statements[:1] question_record = payload.get("question_record") or {} provenance = build_sql_source_provenance( sql_source_version=SQL_SOURCE_VERSION_V1, sql_source_kind="legacy_grounded_run_manifest", sql_source_selection_mode="latest_per_question_id", source_run_id=str(payload.get("run_id") or ""), sql_file_path=item["sql_path"], manifest_path=item["manifest_path"], run_dir=item["manifest_path"].parent, declared_version=str(payload.get("sql_source_version") or ""), declared_label=str(payload.get("sql_source_label") or ""), sql_file_sha256=sql_file_hash, ) for idx, statement in enumerate(statements, start=1): rows_by_dataset[dataset_id].append( { "dataset_id": dataset_id, "question_id": question_id, "query_id": f"{question_id}__sql{idx}", "sql_index": idx, "question": str(payload.get("question") or question_record.get("question") or ""), "template_id": str(question_record.get("template_id") or ""), "template_name": str(question_record.get("template_name") or ""), "family_id": str(question_record.get("primary_family") or ""), "canonical_subitem_id": str(question_record.get("canonical_subitem_id") or ""), "intended_facet_id": str(question_record.get("intended_facet_id") or ""), "variant_semantic_role": str(question_record.get("variant_semantic_role") or ""), "stable_question_id": str(question_record.get("stable_question_id") or ""), "query_identity_stable_key": str(question_record.get("query_identity_stable_key") or ""), "source_run_id": str(payload.get("run_id") or ""), "engine": str(payload.get("engine") or ""), "model": str(payload.get("model") or ""), "sql": statement, **provenance, } ) else: grouped = _load_latest_current_sql_query_groups( sql_source_version=normalized_source, dataset_ids=dataset_ids, engines=engines, require_accepted_for_eval=True, ) for (dataset_id, query_record_id), item in sorted(grouped.items()): row = item["row"] manifest = item["manifest"] if isinstance(item.get("manifest"), dict) else {} question_record = manifest.get("question_record") if isinstance(manifest, dict) else {} sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore") sql_file_hash = str(row.get("sql_sha256") or "") or _sha256_text(sql_text) statements = split_sql_statements(sql_text) if not statements: continue if not include_all_statements: statements = statements[:1] declared_version = str(row.get("sql_source_version") or manifest.get("sql_source_version") or "") declared_label = str(row.get("sql_source_label") or manifest.get("sql_source_label") or "") run_id = str(row.get("round_id") or "") current_runs_root = runs_root(normalized_source) run_root = current_runs_root / run_id dataset_dir = run_root / dataset_id provenance = build_sql_source_provenance( sql_source_version=normalized_source, sql_source_kind="current_query_registry", sql_source_selection_mode="latest_per_query_record_id", source_run_id=run_id, sql_file_path=item["sql_path"], manifest_path=item["manifest_path"], registry_path=item["registry_path"], run_dir=run_root, dataset_dir=dataset_dir, registry_version=str(row.get("registry_version") or ""), declared_version=declared_version, declared_label=declared_label, sql_file_sha256=sql_file_hash, ) for idx, statement in enumerate(statements, start=1): query_id = query_record_id if len(statements) == 1 else f"{query_record_id}__sql{idx}" rows_by_dataset[dataset_id].append( { "dataset_id": dataset_id, "question_id": query_record_id, "query_id": query_id, "sql_index": idx, "question": str(row.get("question_text") or question_record.get("question") or ""), "template_id": str(row.get("template_id") or question_record.get("template_id") or ""), "template_name": str(row.get("template_name") or question_record.get("template_name") or ""), "family_id": str(row.get("family_id") or question_record.get("family_id") or ""), "canonical_subitem_id": str(row.get("canonical_subitem_id") or question_record.get("canonical_subitem_id") or ""), "intended_facet_id": str(row.get("intended_facet_id") or question_record.get("intended_facet_id") or ""), "variant_semantic_role": str(row.get("variant_semantic_role") or question_record.get("variant_semantic_role") or ""), "stable_question_id": query_record_id, "query_identity_stable_key": str(row.get("query_identity_stable_key") or f"{dataset_id}::{query_record_id}"), "source_run_id": run_id, "engine": str(row.get("engine") or manifest.get("engine") or ""), "model": str(manifest.get("model") or ""), "sql": statement, "accepted_for_eval": bool(row.get("accepted_for_eval")), **provenance, } ) return {dataset_id: rows_by_dataset.get(dataset_id, []) for dataset_id in dataset_ids}
def load_latest_sql_queries( *, dataset_id: str, engines: tuple[str, ...] = ("cli",), include_all_statements: bool = True, sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,) -> list[dict[str, Any]]: return load_latest_sql_queries_by_dataset( dataset_ids=[dataset_id], engines=engines, include_all_statements=include_all_statements, sql_source_version=sql_source_version, ).get(dataset_id, [])
def materialize_csv_to_sqlite(csv_path: Path, sqlite_path: Path, table_name: str) -> None: if sqlite_path.exists(): sqlite_path.unlink() sqlite_path.parent.mkdir(parents=True, exist_ok=True)
def _sqlite_ident(name: str) -> str: return f'"{str(name).replace("\"", "\"\"")}"'
def _sniff_delimiter(path: Path) -> str: try: with path.open("r", encoding="utf-8-sig", newline="") as handle: sample = handle.read(4096) dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|") return dialect.delimiter except Exception: return ","
def _repair_single_field_row(row: list[str], delimiter: str) -> list[str]: if len(row) != 1: return row cell = str(row[0] or "") if delimiter not in cell: return row repaired = cell.strip() if repaired.startswith('"') and repaired.endswith('"') and len(repaired) >= 2: repaired = repaired[1:-1] repaired = repaired.replace('""', '"') try: return next(csv.reader([repaired], delimiter=delimiter)) except Exception: return repaired.split(delimiter)
def _infer_header_from_synthetic(dataset_id: str, width: int) -> list[str] | None: try: assets = discover_synthetic_assets( datasets=[dataset_id], root_names=["TabQueryBench-SynDataSuccess-main"], ) except Exception: return None for asset in assets: synthetic_path = Path(asset.synthetic_csv_path) if not synthetic_path.exists(): continue try: delimiter = _sniff_delimiter(synthetic_path) with synthetic_path.open("r", encoding="utf-8-sig", newline="") as synthetic_file: synthetic_reader = csv.reader(synthetic_file, delimiter=delimiter) synthetic_headers = next(synthetic_reader, []) except Exception: continue normalized = [str(header or "").strip() for header in synthetic_headers] if len(normalized) == width and all(normalized): return normalized return None
def _normalize_headers(first_row: list[str]) -> tuple[list[str], bool]: cleaned = [str(header or "").strip() for header in first_row] counts = Counter(cleaned) has_duplicates = any(name and count > 1 for name, count in counts.items()) has_empty = any(not name for name in cleaned) if has_duplicates or has_empty: inferred = _infer_header_from_synthetic(table_name, len(first_row)) if inferred: return inferred, True return [f"col_{idx}" for idx in range(1, len(first_row) + 1)], True return cleaned, False
conn = sqlite3.connect(sqlite_path) try: cur = conn.cursor() delimiter = _sniff_delimiter(csv_path) with csv_path.open("r", encoding="utf-8-sig", newline="") as f: reader = csv.reader(f, delimiter=delimiter) first_row = _repair_single_field_row(next(reader, []), delimiter) if not first_row: raise ValueError(f"Empty header: {csv_path}") headers, headerless = _normalize_headers(first_row) col_defs = ", ".join([f"{_sqlite_ident(header)} TEXT" for header in headers]) cur.execute(f"DROP TABLE IF EXISTS {_sqlite_ident(table_name)}") cur.execute(f"CREATE TABLE {_sqlite_ident(table_name)} ({col_defs})") placeholders = ",".join(["?" for _ in headers]) insert_sql = f"INSERT INTO {_sqlite_ident(table_name)} VALUES ({placeholders})" batch: list[list[str]] = [] if headerless: row = list(first_row) if len(row) < len(headers): row = row + [""] * (len(headers) - len(row)) elif len(row) > len(headers): row = row[: len(headers)] batch.append(row) for row in reader: row = _repair_single_field_row(row, delimiter) if len(row) < len(headers): row = row + [""] * (len(headers) - len(row)) elif len(row) > len(headers): row = row[: len(headers)] batch.append(row) if len(batch) >= 1000: cur.executemany(insert_sql, batch) batch.clear() if batch: cur.executemany(insert_sql, batch) conn.commit() finally: conn.close()
def normalize_missing(value: Any) -> bool: if value is None: return True return str(value).strip().lower() in MISSING_TEXT
def mean_or_none(values: Iterable[float | None]) -> float | None: cleaned = [float(value) for value in values if value is not None and not math.isnan(float(value))] if not cleaned: return None return sum(cleaned) / len(cleaned)12345"""Cardinality/range dynamic analysis outputs and runners."""
from .runner import main
__all__ = ["main"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107from __future__ import annotations
import shutilfrom pathlib import Pathfrom typing import Iterable, Mapping
def versioned_name(filename: str, version_tag: str) -> str: path = Path(str(filename)) suffix = path.suffix stem = path.stem if suffix else path.name tagged = f"{stem}__{version_tag}" return f"{tagged}{suffix}" if suffix else tagged
def _copy_file(src: Path, dst: Path) -> None: if not src.exists(): return dst.parent.mkdir(parents=True, exist_ok=True) try: if src.resolve() == dst.resolve(): return except FileNotFoundError: pass shutil.copy2(src, dst)
def sync_final_outputs( final_dir: Path, files: Iterable[Path], must_do_aliases: Mapping[str, Path] | None = None, *, version_tag: str | None = None, copy_plain_files: bool = True,) -> None: final_dir.mkdir(parents=True, exist_ok=True) must_do_dir = final_dir / "must_do" must_do_dir.mkdir(parents=True, exist_ok=True) version_dir = final_dir / str(version_tag) if version_tag else None version_must_do_dir = (version_dir / "must_do") if version_dir is not None else None if version_dir is not None: version_dir.mkdir(parents=True, exist_ok=True) if version_must_do_dir is not None: version_must_do_dir.mkdir(parents=True, exist_ok=True)
for src in files: if copy_plain_files: _copy_file(src, final_dir / src.name) if version_tag: tagged_name = versioned_name(src.name, str(version_tag)) _copy_file(src, final_dir / tagged_name) if version_dir is not None: _copy_file(src, version_dir / tagged_name)
for alias_name, src in (must_do_aliases or {}).items(): if copy_plain_files: _copy_file(src, final_dir / alias_name) _copy_file(src, must_do_dir / alias_name) if version_tag: tagged_alias = versioned_name(alias_name, str(version_tag)) _copy_file(src, final_dir / tagged_alias) _copy_file(src, must_do_dir / tagged_alias) if version_dir is not None: _copy_file(src, version_dir / tagged_alias) if version_must_do_dir is not None: _copy_file(src, version_must_do_dir / tagged_alias)
def render_final_readme( *, title: str, summary: str, primary_files: list[str], must_do_files: list[str], support_files: list[str] | None = None, notes: list[str] | None = None,) -> str: lines = [ f"# {title}", "", summary.strip(), "", "Primary paper-facing files:", "", ] lines.extend(f"- `{item}`" for item in primary_files) lines.extend( [ "", "Must-do bundle (`must_do/`):", "", ] ) lines.extend(f"- `must_do/{item}`" for item in must_do_files) if support_files: lines.extend( [ "", "Support files:", "", ] ) lines.extend(f"- `{item}`" for item in support_files) if notes: lines.extend(["", *notes]) lines.append("") return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960from __future__ import annotations
import math
import matplotlib
matplotlib.use("Agg")from matplotlib import colormaps
HEATMAP_NA_HEX = "F1F1F1"
_BASE_HEATMAP_CMAP = colormaps["YlGnBu"].copy()_BASE_HEATMAP_CMAP.set_bad(f"#{HEATMAP_NA_HEX}")
def get_heatmap_cmap(): return _BASE_HEATMAP_CMAP
def coerce_heatmap_value(value: object) -> float | None: if value is None: return None try: numeric = float(value) except (TypeError, ValueError): return None if math.isnan(numeric): return None return max(0.0, min(1.0, numeric))
def heatmap_hex(value: object) -> str: numeric = coerce_heatmap_value(value) if numeric is None: return HEATMAP_NA_HEX red, green, blue, _alpha = get_heatmap_cmap()(numeric) return "".join(f"{int(round(channel * 255)):02X}" for channel in (red, green, blue))
def text_hex_for_fill(fill_hex: str) -> str: red = int(fill_hex[0:2], 16) green = int(fill_hex[2:4], 16) blue = int(fill_hex[4:6], 16) luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue return "111111" if luminance >= 150 else "F8F8F8"
def format_heatmap_latex_cell(value: object, *, precision: int = 2, show_text: bool = False) -> str: numeric = coerce_heatmap_value(value) if numeric is None: return "" fill_hex = heatmap_hex(numeric) if not show_text: return rf"\cellcolor[HTML]{{{fill_hex}}}" text_hex = text_hex_for_fill(fill_hex) return ( rf"\cellcolor[HTML]{{{fill_hex}}}" rf"\textcolor[HTML]{{{text_hex}}}{{{numeric:.{precision}f}}}" )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261from __future__ import annotations
from pathlib import Pathfrom typing import Mapping, Sequence
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport pandas as pd
def _escape_tex(text: str) -> str: replacements = { "\\": r"\textbackslash{}", "&": r"\&", "%": r"\%", "$": r"\$", "#": r"\#", "_": r"\_", "{": r"\{", "}": r"\}", } out = str(text) for src, dst in replacements.items(): out = out.replace(src, dst) return out
def _tex_preamble() -> str: return "\n".join( [ r"\documentclass[tikz,border=4pt]{standalone}", r"\usepackage{pgfplots}", r"\usepackage{xcolor}", r"\pgfplotsset{compat=1.18}", "", ] )
def _filtered_subitem_rows(heatmap_df: pd.DataFrame, *, include_summary_row: bool) -> pd.DataFrame: if include_summary_row: return heatmap_df.copy().reset_index(drop=True) out = heatmap_df.loc[heatmap_df["subitem_id"].astype(str).str.lower() != "family_mean"].copy() return out.reset_index(drop=True)
def _cluster_layout( heatmap_df: pd.DataFrame, *, model_order: Sequence[str], model_label_map: Mapping[str, str], include_real_baseline: bool, real_label: str, real_value: float, include_summary_row: bool, intra_gap: float, cluster_gap: float,) -> tuple[list[dict[str, object]], list[dict[str, object]], list[float]]: plot_df = _filtered_subitem_rows(heatmap_df, include_summary_row=include_summary_row) displayed_models = ([("__real__", real_label)] if include_real_baseline else []) + [ (model_id, model_label_map.get(model_id, model_id)) for model_id in model_order ]
bars: list[dict[str, object]] = [] clusters: list[dict[str, object]] = [] separators: list[float] = [] cursor = 0.0 for cluster_index, row in enumerate(plot_df.itertuples(index=False)): cluster_start = cursor for model_key, model_label in displayed_models: if model_key == "__real__": value = float(real_value) else: raw = getattr(row, model_key, None) value = None if raw is None or pd.isna(raw) else float(raw) if value is None: cursor += 1.0 + intra_gap continue bars.append( { "cluster_index": cluster_index, "subitem_id": str(row.subitem_id), "subitem_label": str(row.subitem_label), "model_id": str(model_key), "model_label": str(model_label), "x": float(cursor), "score": float(value), } ) cursor += 1.0 + intra_gap cluster_end = cursor - (1.0 + intra_gap) clusters.append( { "cluster_index": cluster_index, "subitem_id": str(row.subitem_id), "subitem_label": str(row.subitem_label), "start_x": float(cluster_start), "end_x": float(cluster_end), "center_x": float((cluster_start + cluster_end) / 2.0), } ) if cluster_index < len(plot_df) - 1: separators.append(float(cursor - intra_gap / 2.0 + cluster_gap / 2.0)) cursor += cluster_gap return bars, clusters, separators
def write_model_subitem_grouped_bar_tex( heatmap_df: pd.DataFrame, *, model_order: Sequence[str], model_label_map: Mapping[str, str], model_color_map: Mapping[str, str], title: str, y_label: str, path: Path, include_real_baseline: bool = True, real_label: str = "REAL", real_value: float = 1.0, include_summary_row: bool = False, intra_gap: float = 0.10, cluster_gap: float = 1.35,) -> None: if heatmap_df.empty: path.write_text("", encoding="utf-8") return
bars, clusters, separators = _cluster_layout( heatmap_df, model_order=model_order, model_label_map=model_label_map, include_real_baseline=include_real_baseline, real_label=real_label, real_value=real_value, include_summary_row=include_summary_row, intra_gap=intra_gap, cluster_gap=cluster_gap, ) if not bars: path.write_text("", encoding="utf-8") return
label_lookup = {} for item in bars: label_lookup[float(item["x"])] = str(item["model_label"]) x_positions = [float(item["x"]) for item in bars] x_labels = [label_lookup[pos] for pos in x_positions] max_x = max(x_positions) + 1.0
color_defs = [] for model_id in ["__real__", *model_order]: color = "#000000" if model_id == "__real__" else str(model_color_map.get(model_id, "#777777")) color_defs.append(rf"\definecolor{{bar{model_id.replace('_', '').replace('-', '')}}}{{HTML}}{{{color.replace('#', '')}}}")
lines = [ _tex_preamble(), *color_defs, r"\begin{document}", r"\begin{tikzpicture}", r"\begin{axis}[", rf"width={max(13.5, 0.32 * len(x_positions) + 3.6):.2f}cm,", r"height=8.8cm,", r"ymin=0.0, ymax=1.08,", rf"ylabel={{{_escape_tex(y_label)}}},", rf"title={{{_escape_tex(title)}}},", r"ymajorgrids,", r"grid style={draw=gray!22},", r"major grid style={draw=gray!30},", r"axis line style={draw=black!70},", r"tick style={draw=black!70},", rf"xtick={{{','.join(f'{item:.4f}' for item in x_positions)}}},", rf"xticklabels={{{','.join(_escape_tex(item) for item in x_labels)}}},", r"x tick label style={rotate=90, anchor=east, font=\scriptsize},", r"enlarge x limits=0.01,", r"clip=false,", r"]", ] for item in bars: model_id = str(item["model_id"]) color_name = f"bar{model_id.replace('_', '').replace('-', '')}" lines.append( rf"\addplot+[ybar, bar width=5.8pt, draw={color_name}, fill={color_name}] coordinates {{({float(item['x']):.4f},{float(item['score']):.6f})}};" ) for sep in separators: lines.append(rf"\draw[dashed, gray!70, line width=0.6pt] (axis cs:{sep:.4f},0) -- (axis cs:{sep:.4f},1.08);") for cluster in clusters: lines.append( rf"\node[anchor=south, font=\bfseries\small] at (axis cs:{float(cluster['center_x']):.4f},1.035) {{{_escape_tex(str(cluster['subitem_label']))}}};" ) lines.extend([r"\end{axis}", r"\end{tikzpicture}", r"\end{document}", ""]) path.write_text("\n".join(lines), encoding="utf-8")
def plot_model_subitem_grouped_bar_preview( heatmap_df: pd.DataFrame, *, model_order: Sequence[str], model_label_map: Mapping[str, str], model_color_map: Mapping[str, str], title: str, y_label: str, pdf_path: Path, png_path: Path, include_real_baseline: bool = True, real_label: str = "REAL", real_value: float = 1.0, include_summary_row: bool = False, intra_gap: float = 0.10, cluster_gap: float = 1.35,) -> None: if heatmap_df.empty: return
bars, clusters, separators = _cluster_layout( heatmap_df, model_order=model_order, model_label_map=model_label_map, include_real_baseline=include_real_baseline, real_label=real_label, real_value=real_value, include_summary_row=include_summary_row, intra_gap=intra_gap, cluster_gap=cluster_gap, ) if not bars: return
x_positions = [float(item["x"]) for item in bars] values = [float(item["score"]) for item in bars] x_labels = [str(item["model_label"]) for item in bars] colors = ["#000000" if str(item["model_id"]) == "__real__" else str(model_color_map.get(str(item["model_id"]), "#777777")) for item in bars]
fig_width = max(14.0, 0.33 * len(x_positions) + 3.8) fig, ax = plt.subplots(figsize=(fig_width, 7.9)) ax.bar(x_positions, values, width=0.90, color=colors, edgecolor=colors, linewidth=0.8) for sep in separators: ax.axvline(sep, color="#666666", linestyle="--", linewidth=1.0, alpha=0.75) for cluster in clusters: ax.text( float(cluster["center_x"]), 1.035, str(cluster["subitem_label"]), ha="center", va="bottom", fontsize=11, fontweight="bold", )
ax.set_ylim(0.0, 1.08) ax.set_ylabel(y_label) ax.set_title(title) ax.set_xticks(x_positions) ax.set_xticklabels(x_labels, rotation=90, ha="center", va="top", fontsize=8) ax.grid(axis="y", alpha=0.24) ax.margins(x=0.01) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=260, bbox_inches="tight") plt.close(fig)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155from __future__ import annotations
from pathlib import Pathfrom typing import Mapping, Sequence
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport pandas as pd
from src.eval.query_fivepart_breakdown.common_heatmap_palette import ( format_heatmap_latex_cell, get_heatmap_cmap,)
def _escape_tex(text: str) -> str: replacements = { "\\": r"\textbackslash{}", "&": r"\&", "%": r"\%", "$": r"\$", "#": r"\#", "_": r"\_", "{": r"\{", "}": r"\}", } out = str(text) for src, dst in replacements.items(): out = out.replace(src, dst) return out
def _tex_preamble() -> str: return "\n".join( [ r"\documentclass{standalone}", r"\usepackage[table]{xcolor}", r"\usepackage{xcolor}", r"\usepackage{booktabs}", "", ] )
def build_model_subitem_heatmap_df( summary_df: pd.DataFrame, *, model_id_col: str, model_order: Sequence[str], subitem_specs: Sequence[tuple[str, str, str]], summary_row_spec: tuple[str, str, str] | None = None,) -> pd.DataFrame: columns = ["subitem_id", "subitem_label", *model_order] if summary_df.empty: return pd.DataFrame(columns=columns) indexed = summary_df.set_index(model_id_col, drop=False) rows: list[dict[str, float | str | None]] = [] for subitem_id, subitem_label, mean_col in subitem_specs: payload: dict[str, float | str | None] = { "subitem_id": subitem_id, "subitem_label": subitem_label, } for model_id in model_order: value = None if model_id in indexed.index and mean_col in indexed.columns: raw = indexed.loc[model_id, mean_col] if isinstance(raw, pd.Series): raw = raw.iloc[0] value = float(raw) if pd.notna(raw) else None payload[model_id] = value rows.append(payload) if summary_row_spec is not None: subitem_id, subitem_label, mean_col = summary_row_spec payload = { "subitem_id": subitem_id, "subitem_label": subitem_label, } for model_id in model_order: value = None if model_id in indexed.index and mean_col in indexed.columns: raw = indexed.loc[model_id, mean_col] if isinstance(raw, pd.Series): raw = raw.iloc[0] value = float(raw) if pd.notna(raw) else None payload[model_id] = value rows.append(payload) return pd.DataFrame(rows, columns=columns)
def write_model_subitem_heatmap_tex( heatmap_df: pd.DataFrame, *, model_order: Sequence[str], model_label_map: Mapping[str, str], title: str, colorbar_title: str, path: Path,) -> None: if heatmap_df.empty: path.write_text("", encoding="utf-8") return
n_cols = len(model_order) lines = [ _tex_preamble(), r"\begin{document}", r"\scriptsize", rf"\textbf{{{_escape_tex(title)}}}\\[0.4em]", rf"\emph{{{_escape_tex(colorbar_title)}, 0--1; missing cells stay white.}}\\[0.5em]", r"\setlength{\tabcolsep}{4pt}", rf"\begin{{tabular}}{{l{'c' * n_cols}}}", r"\toprule", "Subitem & " + " & ".join(_escape_tex(model_label_map.get(model_id, model_id)) for model_id in model_order) + r" \\", r"\midrule", ] for row_index, row in enumerate(heatmap_df.itertuples(index=False), start=1): _ = row_index cells = [_escape_tex(getattr(row, "subitem_label"))] for model_id in model_order: value = getattr(row, model_id) cells.append(format_heatmap_latex_cell(value)) lines.append(" & ".join(cells) + r" \\") lines.extend([r"\bottomrule", r"\end{tabular}", r"\end{document}", ""]) path.write_text("\n".join(lines), encoding="utf-8")
def plot_model_subitem_heatmap_preview( heatmap_df: pd.DataFrame, *, model_order: Sequence[str], model_label_map: Mapping[str, str], title: str, pdf_path: Path, png_path: Path,) -> None: if heatmap_df.empty: return plot_df = heatmap_df.copy() value_matrix = plot_df[model_order].to_numpy(dtype=float) fig_height = max(3.8, 0.72 * len(plot_df) + 1.9) fig, ax = plt.subplots(figsize=(14.0, fig_height)) image = ax.imshow(value_matrix, aspect="auto", vmin=0.0, vmax=1.0, cmap=get_heatmap_cmap()) ax.set_xticks(range(len(model_order))) ax.set_xticklabels([model_label_map.get(model_id, model_id) for model_id in model_order], rotation=45, ha="right", fontsize=9) ax.set_yticks(range(len(plot_df))) ax.set_yticklabels(plot_df["subitem_label"], fontsize=10) ax.set_title(title) cbar = fig.colorbar(image, ax=ax, fraction=0.03, pad=0.02) cbar.set_label("Mean score") fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=260, bbox_inches="tight") plt.close(fig)1"""Missingness breakdown task."""1"""Experimental pairwise-centered co-missing diagnostic."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563#!/usr/bin/env python3"""Experimental missingness diagnostic using missing-target pairs and centered profiles."""
from __future__ import annotations
from collections import defaultdictfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom functools import lru_cacheimport osfrom os import cpu_countfrom pathlib import Pathimport sysfrom typing import Any
import numpy as npimport pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[5]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from src.eval.common import normalize_missing, write_csvfrom tests.comissing_condition_eval import _clip01, _load_real_df, build_dataset_context
OUTPUT_ROOT = ( PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown" / "pairwise_centered_diagnostic")DATA_DIR = OUTPUT_ROOT / "data"FINAL_DIR = OUTPUT_ROOT / "final"CURRENT_ASSET_CSV = ( PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown" / "data" / "direct_asset_scores.csv")EMIT_PAIR_ROWS = os.environ.get("PAIRWISE_CENTERED_EMIT_PAIR_ROWS", "").strip().lower() in {"1", "true", "yes"}MODEL_ALIASES = {"rtf": "realtabformer"}PREFERRED_MODEL_ORDER = [ "arf", "bayesnet", "cdtd", "codi", "ctgan", "forestdiffusion", "goggle", "realtabformer", "tabbyflow", "tabddpm", "tabdiff", "tabpfgen", "tabsyn", "tvae",]MODEL_LABELS = { "arf": "ARF", "bayesnet": "BayesNet", "cdtd": "CDTD", "codi": "CoDi", "ctgan": "CTGAN", "forestdiffusion": "ForestDiffusion", "goggle": "GOGGLE", "realtabformer": "RealTabFormer", "tabbyflow": "TabbyFlow", "tabddpm": "TabDDPM", "tabdiff": "TabDiff", "tabpfgen": "TabPFGen", "tabsyn": "TabSyn", "tvae": "TVAE",}
def _ensure_dirs() -> None: for path in (OUTPUT_ROOT, DATA_DIR, FINAL_DIR): path.mkdir(parents=True, exist_ok=True)
def _normalize_model(model_id: Any) -> str: key = str(model_id or "").strip().lower() return MODEL_ALIASES.get(key, key)
def _model_label(model_id: str) -> str: return MODEL_LABELS.get(model_id, model_id)
def _model_sort_key(model_id: str) -> tuple[int, str]: if model_id in PREFERRED_MODEL_ORDER: return (PREFERRED_MODEL_ORDER.index(model_id), model_id) return (len(PREFERRED_MODEL_ORDER), model_id)
def _dataset_prefix(dataset_id: str) -> str: text = str(dataset_id or "").strip().lower() if not text: return "?" return text[0]
def _binary_missing_indicator(series: pd.Series) -> np.ndarray: return series.map(normalize_missing).to_numpy(dtype=float)
def _ordered_centered_profile_score_from_counts( *, target_idx: int, related_idx: int, real_row_count: int, syn_row_count: int, real_missing_counts: np.ndarray, syn_missing_counts: np.ndarray, real_joint_missing_counts: np.ndarray, syn_joint_missing_counts: np.ndarray,) -> tuple[float, dict[str, Any]]: real_target_rate = float(real_missing_counts[target_idx] / max(real_row_count, 1)) syn_target_rate = float(syn_missing_counts[target_idx] / max(syn_row_count, 1))
real_related_missing = float(real_missing_counts[related_idx]) real_related_nonmissing = float(real_row_count - real_related_missing) real_state_probs = np.array( [real_related_nonmissing / max(real_row_count, 1), real_related_missing / max(real_row_count, 1)], dtype=float, )
real_joint = float(real_joint_missing_counts[target_idx, related_idx]) real_cond_nonmissing = (float(real_missing_counts[target_idx]) - real_joint) / max(real_related_nonmissing, 1.0) real_cond_missing = real_joint / max(real_related_missing, 1.0) real_conditional_rates = np.array([real_cond_nonmissing, real_cond_missing], dtype=float)
syn_related_missing = float(syn_missing_counts[related_idx]) syn_related_nonmissing = float(syn_row_count - syn_related_missing) syn_joint = float(syn_joint_missing_counts[target_idx, related_idx]) syn_cond_nonmissing = (float(syn_missing_counts[target_idx]) - syn_joint) / max(syn_related_nonmissing, 1.0) syn_cond_missing = syn_joint / max(syn_related_missing, 1.0) syn_conditional_rates = np.array([syn_cond_nonmissing, syn_cond_missing], dtype=float) if syn_related_nonmissing <= 0: syn_conditional_rates[0] = syn_target_rate if syn_related_missing <= 0: syn_conditional_rates[1] = syn_target_rate
delta_real = real_conditional_rates - real_target_rate delta_syn = syn_conditional_rates - syn_target_rate centered_distance = float( real_state_probs[0] * abs(float(delta_real[0]) - float(delta_syn[0])) + real_state_probs[1] * abs(float(delta_real[1]) - float(delta_syn[1])) ) centered_profile_score = _clip01(1.0 - (0.5 * centered_distance))
pair_row = { "target_missing_index": int(target_idx), "related_missing_index": int(related_idx), "real_target_missing_rate": round(real_target_rate, 6), "synthetic_target_missing_rate": round(syn_target_rate, 6), "real_conditional_nonmissing": round(float(real_conditional_rates[0]), 6), "real_conditional_missing": round(float(real_conditional_rates[1]), 6), "synthetic_conditional_nonmissing": round(float(syn_conditional_rates[0]), 6), "synthetic_conditional_missing": round(float(syn_conditional_rates[1]), 6), "real_delta_nonmissing": round(float(delta_real[0]), 6), "real_delta_missing": round(float(delta_real[1]), 6), "synthetic_delta_nonmissing": round(float(delta_syn[0]), 6), "synthetic_delta_missing": round(float(delta_syn[1]), 6), "centered_profile_distance": round(centered_distance, 6), "pairwise_centered_ordered_score": round(float(centered_profile_score), 6), } return centered_profile_score, pair_row
@lru_cache(maxsize=None)def _get_dataset_context(dataset_id: str): return build_dataset_context(dataset_id)
@lru_cache(maxsize=None)def _get_real_target_df(dataset_id: str, missing_targets_key: tuple[str, ...]) -> pd.DataFrame: real_df = _load_real_df(dataset_id) return real_df[list(missing_targets_key)].copy()
def _load_syn_target_df(synthetic_csv_path: Path, target_columns: list[str]) -> pd.DataFrame: target_set = set(target_columns) try: syn_df = pd.read_csv( synthetic_csv_path, dtype=str, keep_default_na=False, usecols=lambda name: str(name) in target_set, ) except ValueError: syn_df = pd.read_csv(synthetic_csv_path, dtype=str, keep_default_na=False) syn_df = syn_df[[column for column in target_columns if column in syn_df.columns]] for column in target_columns: if column not in syn_df.columns: syn_df[column] = "" return syn_df[target_columns].copy()
def _pairwise_centered_score_for_asset(dataset_id: str, synthetic_csv_path: Path) -> dict[str, Any]: context = _get_dataset_context(dataset_id) missing_targets = [target.column for target in context.missing_targets] if len(missing_targets) < 2: return { "pairwise_centered_status": "not_applicable_fewer_than_2_missing_targets", "pairwise_centered_comissing_score": None, "pairwise_centered_pair_count": 0, "pairwise_centered_ordered_edge_count": 0, "active_missing_target_count": len(missing_targets), "pair_rows": [], }
real_df = _get_real_target_df(dataset_id, tuple(missing_targets)) syn_df = _load_syn_target_df(synthetic_csv_path, missing_targets)
real_row_count = len(real_df) syn_row_count = len(syn_df) real_matrix = np.column_stack([_binary_missing_indicator(real_df[col]) for col in missing_targets]).astype(np.float32) syn_matrix = np.column_stack([_binary_missing_indicator(syn_df[col]) for col in missing_targets]).astype(np.float32) real_missing_counts = real_matrix.sum(axis=0) syn_missing_counts = syn_matrix.sum(axis=0) real_joint_missing_counts = real_matrix.T @ real_matrix syn_joint_missing_counts = syn_matrix.T @ syn_matrix
target_count = len(missing_targets) real_target_rates = real_missing_counts / max(real_row_count, 1) syn_target_rates = syn_missing_counts / max(syn_row_count, 1)
real_related_missing = real_missing_counts[np.newaxis, :] real_related_nonmissing = (real_row_count - real_missing_counts)[np.newaxis, :] syn_related_missing = syn_missing_counts[np.newaxis, :] syn_related_nonmissing = (syn_row_count - syn_missing_counts)[np.newaxis, :]
real_cond_missing = np.divide( real_joint_missing_counts, np.maximum(real_related_missing, 1.0), out=np.zeros_like(real_joint_missing_counts, dtype=float), ) real_cond_nonmissing = np.divide( real_missing_counts[:, np.newaxis] - real_joint_missing_counts, np.maximum(real_related_nonmissing, 1.0), out=np.zeros_like(real_joint_missing_counts, dtype=float), ) syn_cond_missing = np.divide( syn_joint_missing_counts, np.maximum(syn_related_missing, 1.0), out=np.zeros_like(syn_joint_missing_counts, dtype=float), ) syn_cond_nonmissing = np.divide( syn_missing_counts[:, np.newaxis] - syn_joint_missing_counts, np.maximum(syn_related_nonmissing, 1.0), out=np.zeros_like(syn_joint_missing_counts, dtype=float), )
syn_missing_zero_mask = (syn_related_missing <= 0)[0] syn_nonmissing_zero_mask = (syn_related_nonmissing <= 0)[0] if bool(np.any(syn_missing_zero_mask)): syn_cond_missing[:, syn_missing_zero_mask] = syn_target_rates[:, np.newaxis] if bool(np.any(syn_nonmissing_zero_mask)): syn_cond_nonmissing[:, syn_nonmissing_zero_mask] = syn_target_rates[:, np.newaxis]
real_delta_missing = real_cond_missing - real_target_rates[:, np.newaxis] real_delta_nonmissing = real_cond_nonmissing - real_target_rates[:, np.newaxis] syn_delta_missing = syn_cond_missing - syn_target_rates[:, np.newaxis] syn_delta_nonmissing = syn_cond_nonmissing - syn_target_rates[:, np.newaxis]
real_state_prob_missing = real_related_missing / max(real_row_count, 1) real_state_prob_nonmissing = real_related_nonmissing / max(real_row_count, 1) centered_distance_matrix = ( real_state_prob_nonmissing * np.abs(real_delta_nonmissing - syn_delta_nonmissing) + real_state_prob_missing * np.abs(real_delta_missing - syn_delta_missing) ) ordered_score_matrix = np.clip(1.0 - (0.5 * centered_distance_matrix), 0.0, 1.0) np.fill_diagonal(ordered_score_matrix, np.nan)
pair_score_matrix = 0.5 * (ordered_score_matrix + ordered_score_matrix.T) upper_left, upper_right = np.triu_indices(target_count, k=1) pair_scores = pair_score_matrix[upper_left, upper_right] ordered_edge_count = int(pair_scores.size * 2) pair_rows: list[dict[str, Any]] = [] if EMIT_PAIR_ROWS: for left_idx, right_idx in zip(upper_left.tolist(), upper_right.tolist(), strict=False): left_score, left_row = _ordered_centered_profile_score_from_counts( target_idx=left_idx, related_idx=right_idx, real_row_count=real_row_count, syn_row_count=syn_row_count, real_missing_counts=real_missing_counts, syn_missing_counts=syn_missing_counts, real_joint_missing_counts=real_joint_missing_counts, syn_joint_missing_counts=syn_joint_missing_counts, ) right_score, right_row = _ordered_centered_profile_score_from_counts( target_idx=right_idx, related_idx=left_idx, real_row_count=real_row_count, syn_row_count=syn_row_count, real_missing_counts=real_missing_counts, syn_missing_counts=syn_missing_counts, real_joint_missing_counts=real_joint_missing_counts, syn_joint_missing_counts=syn_joint_missing_counts, ) pair_id = f"{missing_targets[left_idx]}__{missing_targets[right_idx]}" pair_rows.append( { "pair_id": pair_id, "target_missing_column": missing_targets[left_idx], "related_missing_column": missing_targets[right_idx], "direction": f"{missing_targets[left_idx]}|{missing_targets[right_idx]}", **left_row, } ) pair_rows.append( { "pair_id": pair_id, "target_missing_column": missing_targets[right_idx], "related_missing_column": missing_targets[left_idx], "direction": f"{missing_targets[right_idx]}|{missing_targets[left_idx]}", **right_row, } )
if pair_scores.size == 0: return { "pairwise_centered_status": "not_applicable_no_pairs", "pairwise_centered_comissing_score": None, "pairwise_centered_pair_count": 0, "pairwise_centered_ordered_edge_count": 0, "active_missing_target_count": len(missing_targets), "pair_rows": [], }
return { "pairwise_centered_status": "ok", "pairwise_centered_comissing_score": round(float(np.nanmean(pair_scores)), 6), "pairwise_centered_pair_count": int(pair_scores.size), "pairwise_centered_ordered_edge_count": ordered_edge_count, "active_missing_target_count": len(missing_targets), "pair_rows": pair_rows, }
def _maybe_float(value: Any) -> float | None: if value is None or pd.isna(value): return None try: return float(value) except (TypeError, ValueError): return None
def _evaluate_asset_row(source_row: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: dataset_id = str(source_row.get("dataset_id") or "").strip() synthetic_csv_path = Path(str(source_row.get("synthetic_csv_path") or "").strip()) model_id = _normalize_model(source_row.get("model_id")) if not synthetic_csv_path.exists(): payload = { **source_row, "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "model_id": model_id, "model_label": _model_label(model_id), "current_status": source_row.get("status"), "marginal_missing_rate_consistency": _maybe_float(source_row.get("marginal_missing_rate_consistency")), "current_broad_comissing_score": _maybe_float(source_row.get("co_missingness_pattern_consistency")), "current_missingness_structure_score": _maybe_float(source_row.get("missingness_structure_score")), "pairwise_centered_status": "synthetic_csv_missing", "pairwise_centered_comissing_score": None, "pairwise_centered_pair_count": 0, "pairwise_centered_ordered_edge_count": 0, "active_missing_target_count": None, "pairwise_centered_missingness_structure_score": None, "delta_pairwise_centered_minus_current_broad": None, } return payload, []
pairwise_result = _pairwise_centered_score_for_asset(dataset_id, synthetic_csv_path) payload = { **source_row, "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "model_id": model_id, "model_label": _model_label(model_id), "current_status": source_row.get("status"), "marginal_missing_rate_consistency": _maybe_float(source_row.get("marginal_missing_rate_consistency")), "current_broad_comissing_score": _maybe_float(source_row.get("co_missingness_pattern_consistency")), "current_missingness_structure_score": _maybe_float(source_row.get("missingness_structure_score")), "pairwise_centered_status": pairwise_result.get("pairwise_centered_status"), "pairwise_centered_comissing_score": pairwise_result.get("pairwise_centered_comissing_score"), "pairwise_centered_pair_count": pairwise_result.get("pairwise_centered_pair_count"), "pairwise_centered_ordered_edge_count": pairwise_result.get("pairwise_centered_ordered_edge_count"), "active_missing_target_count": pairwise_result.get("active_missing_target_count"), } marginal = payload.get("marginal_missing_rate_consistency") pairwise_score = payload.get("pairwise_centered_comissing_score") if marginal is not None and pairwise_score is not None: payload["pairwise_centered_missingness_structure_score"] = round(float(np.mean([float(marginal), float(pairwise_score)])), 6) else: payload["pairwise_centered_missingness_structure_score"] = None current_broad = payload.get("current_broad_comissing_score") if current_broad is not None and pairwise_score is not None: payload["delta_pairwise_centered_minus_current_broad"] = round(float(pairwise_score) - float(current_broad), 6) else: payload["delta_pairwise_centered_minus_current_broad"] = None
pair_rows = [] for row in pairwise_result.get("pair_rows", []): pair_rows.append( { "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "model_id": model_id, "model_label": _model_label(model_id), "synthetic_csv_path": str(synthetic_csv_path), **row, } ) return payload, pair_rows
def _mean_or_none(values: list[Any]) -> float | None: cleaned = [float(value) for value in values if value is not None and not pd.isna(value)] if not cleaned: return None return float(np.mean(cleaned))
def _summarize_asset_rows(asset_rows: list[dict[str, Any]], group_keys: tuple[str, ...]) -> list[dict[str, Any]]: grouped: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list) for row in asset_rows: grouped[tuple(str(row.get(key) or "") for key in group_keys)].append(row)
rows: list[dict[str, Any]] = [] for key, items in sorted(grouped.items()): payload = {field: value for field, value in zip(group_keys, key)} payload["asset_count"] = len(items) payload["current_applicable_asset_count"] = sum(1 for item in items if item.get("current_status") == "ok") payload["pairwise_centered_applicable_asset_count"] = sum(1 for item in items if item.get("pairwise_centered_status") == "ok") for field in ( "marginal_missing_rate_consistency", "current_broad_comissing_score", "current_missingness_structure_score", "pairwise_centered_comissing_score", "pairwise_centered_missingness_structure_score", "delta_pairwise_centered_minus_current_broad", ): payload[field] = _mean_or_none([item.get(field) for item in items]) if payload[field] is not None: payload[field] = round(float(payload[field]), 6) payload["pairwise_centered_pair_count__max"] = int( max(float(item.get("pairwise_centered_pair_count") or 0.0) for item in items) ) payload["active_missing_target_count__max"] = int( max(float(item.get("active_missing_target_count") or 0.0) for item in items) ) rows.append(payload) return rows
def run_pairwise_centered_diagnostic(max_workers: int | None = None) -> dict[str, Path]: _ensure_dirs() asset_df_source = pd.read_csv(CURRENT_ASSET_CSV, encoding="utf-8-sig") source_rows = asset_df_source.to_dict(orient="records")
asset_rows: list[dict[str, Any]] = [] pair_rows: list[dict[str, Any]] = [] worker_count = max_workers if max_workers is not None else min(8, max(1, (cpu_count() or 4) - 1))
with ThreadPoolExecutor(max_workers=max(1, worker_count)) as executor: futures = [executor.submit(_evaluate_asset_row, row) for row in source_rows] for index, future in enumerate(as_completed(futures), start=1): asset_row, asset_pair_rows = future.result() asset_rows.append(asset_row) pair_rows.extend(asset_pair_rows) print( f"[pairwise-centered] asset={index}/{len(futures)}" f" dataset={asset_row['dataset_id']}" f" model={asset_row['model_id']}" f" status={asset_row['pairwise_centered_status']}", flush=True, )
asset_df = pd.DataFrame(asset_rows) pair_df = pd.DataFrame(pair_rows) if not asset_df.empty: asset_df["model_sort"] = asset_df["model_id"].map(lambda item: _model_sort_key(str(item))) asset_df = asset_df.sort_values(["dataset_id", "model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True)
dataset_model_df = pd.DataFrame(_summarize_asset_rows(asset_rows, ("dataset_id", "dataset_prefix", "model_id", "model_label"))) model_overall_df = pd.DataFrame(_summarize_asset_rows(asset_rows, ("model_id", "model_label"))) dataset_overall_df = pd.DataFrame(_summarize_asset_rows(asset_rows, ("dataset_id", "dataset_prefix"))) if not model_overall_df.empty: model_overall_df["model_sort"] = model_overall_df["model_id"].map(lambda item: _model_sort_key(str(item))) model_overall_df = model_overall_df.sort_values(["model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True) if not dataset_model_df.empty: dataset_model_df["model_sort"] = dataset_model_df["model_id"].map(lambda item: _model_sort_key(str(item))) dataset_model_df = dataset_model_df.sort_values(["dataset_id", "model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True) if not pair_df.empty: pair_df["model_sort"] = pair_df["model_id"].map(lambda item: _model_sort_key(str(item))) pair_df = pair_df.sort_values(["dataset_id", "model_sort", "model_id", "pair_id", "direction"]).drop(columns=["model_sort"]).reset_index(drop=True)
asset_csv = DATA_DIR / "pairwise_centered_asset_scores.csv" pair_csv = DATA_DIR / "pairwise_centered_pair_scores.csv" dataset_model_csv = DATA_DIR / "pairwise_centered_model_dataset_summary.csv" model_overall_csv = DATA_DIR / "pairwise_centered_model_overall_summary.csv" dataset_overall_csv = DATA_DIR / "pairwise_centered_dataset_overall_summary.csv"
write_csv(asset_csv, asset_df.to_dict(orient="records")) write_csv(pair_csv, pair_df.to_dict(orient="records")) write_csv(dataset_model_csv, dataset_model_df.to_dict(orient="records")) write_csv(model_overall_csv, model_overall_df.to_dict(orient="records")) write_csv(dataset_overall_csv, dataset_overall_df.to_dict(orient="records"))
applicable_panels = int( asset_df["pairwise_centered_status"].eq("ok").sum() ) if not asset_df.empty else 0 applicable_datasets = int( asset_df.loc[asset_df["pairwise_centered_status"].eq("ok"), "dataset_id"].nunique() ) if not asset_df.empty else 0 readme_lines = [ "# Pairwise-Centered Co-Missing Diagnostic", "", "- This is an experimental diagnostic and does not modify the official missingness bundle.", "- Canonical marginal score is reused unchanged from the direct missingness evaluator.", "- Experimental co-missing score restricts the second axis to pairs of active missing-target columns.", "- For each ordered pair `(Mi | Mj)`, we compare centered profiles:", " - `delta_real(r) = P_real(Mi=1 | Mj=r) - P_real(Mi=1)`", " - `delta_syn(r) = P_syn(Mi=1 | Mj=r) - P_syn(Mi=1)`", " - `score = 1 - 0.5 * sum_r P_real(Mj=r) * |delta_real(r) - delta_syn(r)|`", "- Final experimental co-missing score = mean over unordered missing-target pairs after averaging both directions.", "", f"- Asset panels evaluated: `{asset_df.shape[0]}`", f"- Pairwise-applicable panels: `{applicable_panels}`", f"- Pairwise-applicable datasets: `{applicable_datasets}`", "", "## Files", "", "- `data/pairwise_centered_asset_scores.csv`", "- `data/pairwise_centered_pair_scores.csv`", "- `data/pairwise_centered_model_dataset_summary.csv`", "- `data/pairwise_centered_model_overall_summary.csv`", "- `data/pairwise_centered_dataset_overall_summary.csv`", ] (OUTPUT_ROOT / "README.md").write_text("\n".join(readme_lines) + "\n", encoding="utf-8") (FINAL_DIR / "README.md").write_text("\n".join(readme_lines) + "\n", encoding="utf-8") for src in (asset_csv, pair_csv, dataset_model_csv, model_overall_csv, dataset_overall_csv): (FINAL_DIR / src.name).write_text(src.read_text(encoding="utf-8-sig"), encoding="utf-8-sig")
return { "asset_scores": asset_csv, "pair_scores": pair_csv, "model_dataset_summary": dataset_model_csv, "model_overall_summary": model_overall_csv, "dataset_overall_summary": dataset_overall_csv, }
if __name__ == "__main__": outputs = run_pairwise_centered_diagnostic() for key, value in outputs.items(): print(f"{key}: {value}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334#!/usr/bin/env python3"""Build missingness regime diagnostic grouped-bar figures.
This diagnostic compares categorical, mixed, and numerical regimes for:
1. missingness_structure_score2. co_missingness_pattern_consistency3. marginal_missing_rate_consistency
It writes paper-friendly PNG/PDF previews plus concise text insights."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[4]OUTPUT_ROOT = PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown" / "regime_diagnostic"DATA_DIR = OUTPUT_ROOT / "data"FIG_DIR = OUTPUT_ROOT / "figures"FINAL_DIR = OUTPUT_ROOT / "final"SOURCE_CSV = ( PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown" / "final" / "prefix_summary__v2.csv")
MODEL_COLORS = { "REAL": "#000000", "RealTabFormer": "#332288", "TVAE": "#4477AA", "ForestDiffusion": "#228833", "TabDDPM": "#EE7733", "TabSyn": "#66CCEE", "TabDiff": "#AA3377", "CTGAN": "#EE6677", "ARF": "#777777", "BayesNet": "#CCBB44", "TabPFGen": "#009988", "TabbyFlow": "#882255",}
MODEL_ORDER = [ "ARF", "BayesNet", "CTGAN", "ForestDiffusion", "RealTabFormer", "TabbyFlow", "TabDDPM", "TabDiff", "TabPFGen", "TabSyn", "TVAE",]
PREFIX_ORDER = ["c", "m", "n"]PREFIX_LABELS = {"c": "Categorical", "m": "Mixed", "n": "Numerical"}PREFIX_COLORS = {"c": "#E6C229", "m": "#3FA7D6", "n": "#D1495B"}
METRIC_SPECS = [ ( "missingness_structure_score", "missingness_regime_grouped_bars_main", "Missingness family score across regimes", ), ( "co_missingness_pattern_consistency", "missingness_regime_grouped_bars_profile_appendix", "Co-missingness profile score across regimes", ), ( "marginal_missing_rate_consistency", "missingness_regime_grouped_bars_marginal_appendix", "Marginal missing-rate score across regimes", ),]
def _ensure_dirs() -> None: for path in [OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR]: path.mkdir(parents=True, exist_ok=True)
def _load_prefix_summary() -> pd.DataFrame: df = pd.read_csv(SOURCE_CSV) df = df.rename(columns={"model_label": "Model", "dataset_prefix": "Prefix"}) df["Model"] = df["Model"].astype(str) df["Prefix"] = df["Prefix"].astype(str) return df
def _pivot_metric(df: pd.DataFrame, metric: str) -> pd.DataFrame: pivot = ( df.pivot(index="Model", columns="Prefix", values=metric) .reindex(index=MODEL_ORDER, columns=PREFIX_ORDER) .reset_index() ) return pivot
def _write_csv(df: pd.DataFrame, path: Path) -> None: df.to_csv(path, index=False, encoding="utf-8")
def _plot_grouped_bars(metric_df: pd.DataFrame, title: str, pdf_path: Path, png_path: Path) -> None: models = metric_df["Model"].tolist() x = np.arange(len(models)) width = 0.23 fig, ax = plt.subplots(figsize=(13.6, 5.8))
for idx, prefix in enumerate(PREFIX_ORDER): values = pd.to_numeric(metric_df[prefix], errors="coerce").to_numpy(dtype=float) offset = (idx - 1) * width mask = ~np.isnan(values) ax.bar( x[mask] + offset, values[mask], width=width, color=PREFIX_COLORS[prefix], label=PREFIX_LABELS[prefix], edgecolor="white", linewidth=0.8, )
ax.set_title(title, fontsize=15) ax.set_ylabel("Score") ax.set_xlabel("Model") ax.set_ylim(0.0, 1.02) ax.set_xticks(x) ax.set_xticklabels(models, rotation=90, ha="center", va="top") ax.grid(axis="y", alpha=0.25) ax.legend(frameon=False, ncol=3, loc="upper right") fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=240, bbox_inches="tight") plt.close(fig)
def _tex_escape(text: str) -> str: escaped = str(text) for src, dst in [ ("\\", r"\textbackslash{}"), ("&", r"\&"), ("%", r"\%"), ("$", r"\$"), ("#", r"\#"), ("_", r"\_"), ("{", r"\{"), ("}", r"\}"), ]: escaped = escaped.replace(src, dst) return escaped
def _write_grouped_bars_tex(metric_df: pd.DataFrame, title: str, tex_path: Path) -> None: models = metric_df["Model"].tolist() symbolic = ",".join(_tex_escape(model) for model in models) bar_width = "8pt" lines = [ r"\documentclass[tikz,border=4pt]{standalone}", r"\usepackage{pgfplots}", r"\pgfplotsset{compat=1.18}", r"\usepackage{xcolor}", r"\begin{document}", r"\begin{tikzpicture}", r"\begin{axis}[", f"title={{{_tex_escape(title)}}},", r"width=15.6cm,", r"height=7.0cm,", r"ymin=0, ymax=1.02,", r"ylabel={Score},", r"xlabel={Model},", r"ymajorgrids=true,", r"grid style={gray!25},", r"legend style={draw=none, fill=none, at={(0.98,0.98)}, anchor=north east},", r"legend columns=3,", f"symbolic x coords={{{symbolic}}},", r"xtick=data,", r"x tick label style={rotate=90, anchor=east, font=\small},", r"enlarge x limits=0.05,", f"bar width={bar_width},", r"]", ]
for idx, prefix in enumerate(PREFIX_ORDER): color = PREFIX_COLORS[prefix] label = PREFIX_LABELS[prefix] shift = (-1 + idx) * 10 coords: list[str] = [] for row in metric_df.itertuples(index=False): value = getattr(row, prefix) if pd.isna(value): continue coords.append(f"({_tex_escape(row.Model)},{float(value):.6f})") lines.extend( [ rf"\addplot+[ybar, bar shift={shift}pt, draw=white, fill={color}] coordinates {{", " ".join(coords), r"};", rf"\addlegendentry{{{_tex_escape(label)}}}", ] )
lines.extend( [ r"\end{axis}", r"\end{tikzpicture}", r"\end{document}", "", ] ) tex_path.write_text("\n".join(lines), encoding="utf-8")
def _format_value(value: Any) -> str: if pd.isna(value): return "NA" return f"{float(value):.3f}"
def _build_story_txt(main_df: pd.DataFrame) -> str: numeric = pd.to_numeric(main_df["n"], errors="coerce") categorical = pd.to_numeric(main_df["c"], errors="coerce") mixed = pd.to_numeric(main_df["m"], errors="coerce") work = main_df.copy() work["drop_c_to_n"] = categorical - numeric work["drop_m_to_n"] = mixed - numeric work["range_max_min"] = pd.concat([categorical, mixed, numeric], axis=1).max(axis=1) - pd.concat([categorical, mixed, numeric], axis=1).min(axis=1)
valid_n = work.loc[work["n"].notna()].copy() valid_n = valid_n.sort_values("n", ascending=False) largest_drop = valid_n.sort_values("drop_m_to_n", ascending=False)
lines = [ "Insight 1: Numerical missingness is the hardest regime for most models.", ( "Across the regime summary, most models follow a categorical -> mixed -> numerical decline or at least end lower on numerical than on the other two regimes. " f"The numerical column is especially weak for ARF ({_format_value(valid_n.loc[valid_n['Model']=='ARF', 'n'].iloc[0])}), " f"BayesNet ({_format_value(valid_n.loc[valid_n['Model']=='BayesNet', 'n'].iloc[0])}), " f"CTGAN ({_format_value(valid_n.loc[valid_n['Model']=='CTGAN', 'n'].iloc[0])}), " f"TabSyn ({_format_value(valid_n.loc[valid_n['Model']=='TabSyn', 'n'].iloc[0])}), and TabbyFlow ({_format_value(valid_n.loc[valid_n['Model']=='TabbyFlow', 'n'].iloc[0])})." ), "", "Insight 2: Some models collapse sharply on numerical missingness, but RealTabFormer remains stable.", ( f"RealTabFormer stays high in all three regimes with c/m/n = " f"{_format_value(valid_n.loc[valid_n['Model']=='RealTabFormer', 'c'].iloc[0])}/" f"{_format_value(valid_n.loc[valid_n['Model']=='RealTabFormer', 'm'].iloc[0])}/" f"{_format_value(valid_n.loc[valid_n['Model']=='RealTabFormer', 'n'].iloc[0])}. " f"By contrast, the largest mixed-to-numerical drops come from " f"{largest_drop.iloc[0]['Model']} ({_format_value(largest_drop.iloc[0]['m'])} -> {_format_value(largest_drop.iloc[0]['n'])}), " f"{largest_drop.iloc[1]['Model']} ({_format_value(largest_drop.iloc[1]['m'])} -> {_format_value(largest_drop.iloc[1]['n'])}), and " f"{largest_drop.iloc[2]['Model']} ({_format_value(largest_drop.iloc[2]['m'])} -> {_format_value(largest_drop.iloc[2]['n'])}). " "This suggests that preserving numerical missingness structure is not just uniformly harder; for some models it is a clear regime-specific failure mode." ), ] return "\n".join(lines) + "\n"
def _build_manifest(metric_tables: dict[str, str]) -> dict[str, Any]: return { "task": "missingness_regime_diagnostic", "source_csv": str(SOURCE_CSV), "output_root": str(OUTPUT_ROOT), "metric_tables": metric_tables, "model_order": MODEL_ORDER, "prefix_order": PREFIX_ORDER, }
def run() -> dict[str, Any]: _ensure_dirs() df = _load_prefix_summary() metric_tables: dict[str, str] = {}
main_metric_df: pd.DataFrame | None = None for metric, stem, title in METRIC_SPECS: metric_df = _pivot_metric(df, metric) _write_csv(metric_df, DATA_DIR / f"{stem}.csv") _write_grouped_bars_tex(metric_df, title, FIG_DIR / f"{stem}.tex") _plot_grouped_bars(metric_df, title, FIG_DIR / f"{stem}.pdf", FIG_DIR / f"{stem}.png") metric_tables[metric] = f"data/{stem}.csv" if metric == "missingness_structure_score": main_metric_df = metric_df
if main_metric_df is None: raise RuntimeError("Main metric table was not built.")
story_txt = _build_story_txt(main_metric_df) (FINAL_DIR / "missingness_regime_insights.txt").write_text(story_txt, encoding="utf-8") (FINAL_DIR / "README.txt").write_text( "\n".join( [ "Missingness regime diagnostic bundle", "", "Main figure:", "- figures/missingness_regime_grouped_bars_main.png", "- figures/missingness_regime_grouped_bars_main.tex", "", "Appendix figures:", "- figures/missingness_regime_grouped_bars_profile_appendix.png", "- figures/missingness_regime_grouped_bars_profile_appendix.tex", "- figures/missingness_regime_grouped_bars_marginal_appendix.png", "- figures/missingness_regime_grouped_bars_marginal_appendix.tex", "", "Text insight:", "- final/missingness_regime_insights.txt", ] ) + "\n", encoding="utf-8", )
manifest = _build_manifest(metric_tables) (OUTPUT_ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") return manifest
if __name__ == "__main__": print(json.dumps(run(), indent=2))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519#!/usr/bin/env python3"""Temporary audit: compare current broad co-missingness vs strict pairwise co-missingness.
This script does not modify the official missingness breakdown outputs.It writes a standalone review bundle under:
Evaluation/query_fivepart_breakdown/missingness_breakdown/review_strict_pairwise"""
from __future__ import annotations
import mathimport sysfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom functools import lru_cachefrom pathlib import Pathfrom statistics import meanfrom typing import Any
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[4]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from src.eval.common import normalize_missing, resolve_real_split_pathfrom tests.comissing_condition_eval import _clip01, _relation_strength, build_dataset_context
OUTPUT_ROOT = ( PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown" / "review_strict_pairwise")DATA_DIR = OUTPUT_ROOT / "data"FIG_DIR = OUTPUT_ROOT / "figures"NOTES_DIR = OUTPUT_ROOT / "notes"
CURRENT_ASSET_CSV = ( PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown" / "data" / "direct_asset_scores.csv")
EXCLUDED_MODELS = {"cdtd", "codi", "goggle"}MODEL_ALIASES = {"rtf": "realtabformer"}MODEL_LABELS = { "arf": "ARF", "bayesnet": "BayesNet", "ctgan": "CTGAN", "forestdiffusion": "ForestDiffusion", "realtabformer": "RealTabFormer", "tabbyflow": "TabbyFlow", "tabddpm": "TabDDPM", "tabdiff": "TabDiff", "tabpfgen": "TabPFGen", "tabsyn": "TabSyn", "tvae": "TVAE",}MODEL_COLORS = { "realtabformer": "#332288", "tvae": "#4477AA", "forestdiffusion": "#228833", "tabddpm": "#EE7733", "tabsyn": "#66CCEE", "tabdiff": "#AA3377", "ctgan": "#EE6677", "arf": "#777777", "bayesnet": "#CCBB44", "tabpfgen": "#009988", "tabbyflow": "#882255",}MODEL_ORDER = [ "arf", "bayesnet", "ctgan", "forestdiffusion", "realtabformer", "tabbyflow", "tabddpm", "tabdiff", "tabpfgen", "tabsyn", "tvae",]
def _ensure_dirs() -> None: for path in (OUTPUT_ROOT, DATA_DIR, FIG_DIR, NOTES_DIR): path.mkdir(parents=True, exist_ok=True)
def _normalize_model(model_id: Any) -> str: key = str(model_id or "").strip().lower() return MODEL_ALIASES.get(key, key)
def _model_label(model_id: str) -> str: return MODEL_LABELS.get(model_id, model_id)
def _write_csv(df: pd.DataFrame, path: Path) -> None: df.to_csv(path, index=False, encoding="utf-8-sig")
def _binary_missing_indicator(series: pd.Series) -> np.ndarray: return series.map(normalize_missing).to_numpy(dtype=float)
def _load_syn_target_df(synthetic_csv_path: Path, target_columns: list[str]) -> pd.DataFrame: try: syn_df = pd.read_csv( synthetic_csv_path, dtype=str, keep_default_na=False, usecols=lambda name: str(name) in set(target_columns), ) except ValueError: syn_df = pd.read_csv(synthetic_csv_path, dtype=str, keep_default_na=False) syn_df = syn_df[[col for col in target_columns if col in syn_df.columns]] for column in target_columns: if column not in syn_df.columns: syn_df[column] = "" return syn_df[target_columns]
def _state_codes_from_indicator(indicator: np.ndarray) -> np.ndarray: # 0 = non-missing, 1 = missing return indicator.astype(np.int16, copy=False)
def _conditional_rate_stats(missing_indicator: np.ndarray, related_codes: np.ndarray) -> tuple[np.ndarray, np.ndarray]: support_counts = np.bincount(related_codes, minlength=2) missing_sums = np.bincount(related_codes, weights=missing_indicator, minlength=2) rates = np.zeros(2, dtype=float) nonzero = support_counts > 0 rates[nonzero] = missing_sums[nonzero] / support_counts[nonzero] return support_counts, rates
def _strict_pair_score( real_target: np.ndarray, real_related: np.ndarray, syn_target: np.ndarray, syn_related: np.ndarray,) -> tuple[float, float, float]: real_global_missing_rate = float(np.mean(real_target)) real_related_codes = _state_codes_from_indicator(real_related) syn_related_codes = _state_codes_from_indicator(syn_related)
real_support_counts, real_conditional_rates = _conditional_rate_stats(real_target, real_related_codes) supported_state_indices = tuple(int(idx) for idx in np.where(real_support_counts > 0)[0].tolist()) real_state_probabilities = real_support_counts.astype(float) / max(1, len(real_target)) real_strength = _relation_strength(real_global_missing_rate, real_state_probabilities, real_conditional_rates)
syn_support_counts, syn_conditional_rates = _conditional_rate_stats(syn_target, syn_related_codes) syn_rates_fallback = syn_conditional_rates.copy() zero_support = syn_support_counts <= 0 syn_rates_fallback[zero_support] = float(np.mean(syn_target))
profile_distance = 0.0 for idx in supported_state_indices: profile_distance += float(real_state_probabilities[idx]) * abs( float(real_conditional_rates[idx]) - float(syn_rates_fallback[idx]) ) profile_score = _clip01(1.0 - profile_distance)
denom = max(real_global_missing_rate * (1.0 - real_global_missing_rate), 1e-12) syn_weighted_var = 0.0 for idx in supported_state_indices: syn_weighted_var += float(real_state_probabilities[idx]) * ( (float(syn_rates_fallback[idx]) - real_global_missing_rate) ** 2 ) syn_strength = _clip01(syn_weighted_var / denom) strength_score = _clip01(1.0 - abs(real_strength - syn_strength))
edge_score = _clip01((0.7 * profile_score) + (0.3 * strength_score)) return edge_score, profile_score, strength_score
def _ordered_edge_score_from_counts( target_idx: int, related_idx: int, row_count: int, real_missing_counts: np.ndarray, syn_missing_counts: np.ndarray, real_joint_missing_counts: np.ndarray, syn_joint_missing_counts: np.ndarray,) -> float: real_target_rate = float(real_missing_counts[target_idx] / row_count) syn_target_rate = float(syn_missing_counts[target_idx] / row_count)
real_related_missing = float(real_missing_counts[related_idx]) real_related_nonmissing = float(row_count - real_related_missing) real_state_probs = np.array( [real_related_nonmissing / row_count, real_related_missing / row_count], dtype=float, )
real_joint = float(real_joint_missing_counts[target_idx, related_idx]) real_cond_nonmissing = (float(real_missing_counts[target_idx]) - real_joint) / max(real_related_nonmissing, 1.0) real_cond_missing = real_joint / max(real_related_missing, 1.0) real_conditional_rates = np.array([real_cond_nonmissing, real_cond_missing], dtype=float) real_strength = _relation_strength(real_target_rate, real_state_probs, real_conditional_rates)
syn_related_missing = float(syn_missing_counts[related_idx]) syn_related_nonmissing = float(row_count - syn_related_missing) syn_joint = float(syn_joint_missing_counts[target_idx, related_idx])
syn_cond_nonmissing = (float(syn_missing_counts[target_idx]) - syn_joint) / max(syn_related_nonmissing, 1.0) syn_cond_missing = syn_joint / max(syn_related_missing, 1.0) syn_conditional_rates = np.array([syn_cond_nonmissing, syn_cond_missing], dtype=float) if syn_related_nonmissing <= 0: syn_conditional_rates[0] = syn_target_rate if syn_related_missing <= 0: syn_conditional_rates[1] = syn_target_rate
profile_distance = float( real_state_probs[0] * abs(real_conditional_rates[0] - syn_conditional_rates[0]) + real_state_probs[1] * abs(real_conditional_rates[1] - syn_conditional_rates[1]) ) profile_score = _clip01(1.0 - profile_distance)
denom = max(syn_target_rate * (1.0 - syn_target_rate), 1e-12) syn_weighted_var = float( real_state_probs[0] * ((syn_conditional_rates[0] - syn_target_rate) ** 2) + real_state_probs[1] * ((syn_conditional_rates[1] - syn_target_rate) ** 2) ) syn_strength = _clip01(syn_weighted_var / denom) strength_score = _clip01(1.0 - abs(real_strength - syn_strength)) return _clip01((0.7 * profile_score) + (0.3 * strength_score))
@lru_cache(maxsize=None)def _get_dataset_context(dataset_id: str): return build_dataset_context(dataset_id)
@lru_cache(maxsize=None)def _get_real_df(dataset_id: str) -> pd.DataFrame: return pd.read_csv(resolve_real_split_path(dataset_id, split="train"), dtype=str, keep_default_na=False)
def _strict_pairwise_score_for_asset(dataset_id: str, synthetic_csv_path: Path) -> dict[str, Any]: try: context = _get_dataset_context(dataset_id) except FileNotFoundError: return { "strict_status": "real_train_csv_missing_locally", "strict_pairwise_score": None, "strict_pair_count": 0, "active_missing_target_count": 0, } missing_targets = [target.column for target in context.missing_targets]
if len(missing_targets) < 2: return { "strict_status": "not_applicable_fewer_than_2_missing_targets", "strict_pairwise_score": None, "strict_pair_count": 0, "active_missing_target_count": len(missing_targets), }
real_df = _get_real_df(dataset_id) syn_df = _load_syn_target_df(synthetic_csv_path, missing_targets)
row_count = len(real_df) real_matrix = np.column_stack([_binary_missing_indicator(real_df[col]) for col in missing_targets]).astype(np.float32) syn_matrix = np.column_stack([_binary_missing_indicator(syn_df[col]) for col in missing_targets]).astype(np.float32) real_missing_counts = real_matrix.sum(axis=0) syn_missing_counts = syn_matrix.sum(axis=0) real_joint_missing_counts = real_matrix.T @ real_matrix syn_joint_missing_counts = syn_matrix.T @ syn_matrix
pair_scores: list[float] = [] for left_idx in range(len(missing_targets)): for right_idx in range(left_idx + 1, len(missing_targets)): left_given_right = _ordered_edge_score_from_counts( left_idx, right_idx, row_count, real_missing_counts, syn_missing_counts, real_joint_missing_counts, syn_joint_missing_counts, ) right_given_left = _ordered_edge_score_from_counts( right_idx, left_idx, row_count, real_missing_counts, syn_missing_counts, real_joint_missing_counts, syn_joint_missing_counts, ) pair_scores.append(float(mean([left_given_right, right_given_left])))
return { "strict_status": "ok", "strict_pairwise_score": round(float(mean(pair_scores)), 6), "strict_pair_count": len(pair_scores), "active_missing_target_count": len(missing_targets), "pair_rows": [], }
def _review_one_asset(row_dict: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]: result = _strict_pairwise_score_for_asset(str(row_dict["dataset_id"]), Path(str(row_dict["synthetic_csv_path"]))) payload = { "dataset_id": str(row_dict["dataset_id"]), "model_id": str(row_dict["model_id"]), "model_label": _model_label(str(row_dict["model_id"])), "current_broad_comissing_score": float(row_dict["co_missingness_pattern_consistency"]), "current_marginal_score": float(row_dict["marginal_missing_rate_consistency"]), "current_family_score": float(row_dict["missingness_structure_score"]), "strict_status": result["strict_status"], "strict_pairwise_comissing_score": result["strict_pairwise_score"], "strict_pair_count": int(result["strict_pair_count"]), "active_missing_target_count": int(result["active_missing_target_count"]), } if result["strict_pairwise_score"] is not None: payload["delta_strict_minus_current"] = round( float(result["strict_pairwise_score"]) - float(row_dict["co_missingness_pattern_consistency"]), 6 ) else: payload["delta_strict_minus_current"] = None
pair_rows = [ { "dataset_id": str(row_dict["dataset_id"]), "model_id": str(row_dict["model_id"]), "model_label": _model_label(str(row_dict["model_id"])), **pair_row, } for pair_row in result.get("pair_rows", []) ] return payload, pair_rows
def _build_review_outputs() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]: asset_df = pd.read_csv(CURRENT_ASSET_CSV, encoding="utf-8-sig") asset_df["model_id"] = asset_df["model_id"].map(_normalize_model) asset_df = asset_df.loc[ (asset_df["status"] == "ok") & (~asset_df["model_id"].isin(EXCLUDED_MODELS)) & asset_df["model_id"].isin(MODEL_ORDER) ].copy()
review_rows: list[dict[str, Any]] = [] pair_rows: list[dict[str, Any]] = []
row_dicts = asset_df.to_dict(orient="records") with ThreadPoolExecutor(max_workers=6) as executor: futures = [executor.submit(_review_one_asset, row_dict) for row_dict in row_dicts] for future in as_completed(futures): payload, pair_payloads = future.result() review_rows.append(payload) pair_rows.extend(pair_payloads)
review_df = pd.DataFrame(review_rows).sort_values(["dataset_id", "model_label"]).reset_index(drop=True) pair_df = pd.DataFrame(pair_rows)
overlap_df = review_df.loc[review_df["strict_pairwise_comissing_score"].notna()].copy() grouped = [] for model_id, group in overlap_df.groupby("model_id", sort=False): grouped.append( { "model_id": model_id, "model_label": _model_label(model_id), "dataset_count_overlap": int(group["dataset_id"].nunique()), "panel_count_overlap": int(group.shape[0]), "current_broad_comissing_score__mean": round(float(group["current_broad_comissing_score"].mean()), 6), "strict_pairwise_comissing_score__mean": round(float(group["strict_pairwise_comissing_score"].mean()), 6), "delta_strict_minus_current__mean": round(float(group["delta_strict_minus_current"].mean()), 6), } ) model_df = pd.DataFrame(grouped) if not model_df.empty: model_df["model_order"] = model_df["model_id"].map({m: i for i, m in enumerate(MODEL_ORDER)}) model_df = model_df.sort_values("model_order").drop(columns=["model_order"]).reset_index(drop=True)
coverage_rows = [] for dataset_id, group in review_df.groupby("dataset_id", sort=False): coverage_rows.append( { "dataset_id": dataset_id, "model_panel_count": int(group.shape[0]), "strict_applicable_panel_count": int(group["strict_pairwise_comissing_score"].notna().sum()), "active_missing_target_count": int(group["active_missing_target_count"].max()), "strict_pair_count": int(pd.to_numeric(group["strict_pair_count"], errors="coerce").fillna(0).max()), } ) coverage_df = pd.DataFrame(coverage_rows).sort_values("dataset_id").reset_index(drop=True) return review_df, pair_df, model_df, coverage_df
def _plot_review_figure(review_df: pd.DataFrame, model_df: pd.DataFrame, out_path: Path) -> None: overlap_df = review_df.loc[review_df["strict_pairwise_comissing_score"].notna()].copy()
fig, axes = plt.subplots(1, 2, figsize=(14.0, 6.2), constrained_layout=True) ax0, ax1 = axes
if not model_df.empty: y_positions = np.arange(len(model_df)) for idx, row in enumerate(model_df.itertuples()): current = float(row.current_broad_comissing_score__mean) strict = float(row.strict_pairwise_comissing_score__mean) color = MODEL_COLORS.get(str(row.model_id), "#777777") ax0.plot([current, strict], [idx, idx], color=color, linewidth=2.0, alpha=0.9) ax0.scatter(current, idx, s=60, color="white", edgecolor=color, linewidth=1.8, zorder=3) ax0.scatter(strict, idx, s=60, color=color, edgecolor=color, linewidth=1.2, zorder=4) ax0.set_yticks(y_positions) ax0.set_yticklabels(list(model_df["model_label"])) ax0.set_xlim(0.0, 1.02) ax0.set_xlabel("Mean co-missingness score on overlap panels") ax0.set_title("Model-level comparison\nhollow = current broad, solid = strict pairwise") ax0.grid(axis="x", alpha=0.25, linewidth=0.8) else: ax0.text(0.5, 0.5, "No overlap panels available", ha="center", va="center", transform=ax0.transAxes) ax0.set_axis_off()
if not overlap_df.empty: ax1.scatter( overlap_df["current_broad_comissing_score"], overlap_df["strict_pairwise_comissing_score"], s=34, color="#4C78A8", alpha=0.75, edgecolors="none", ) ax1.plot([0, 1], [0, 1], linestyle="--", color="#666666", linewidth=1.2) ax1.set_xlim(0.0, 1.02) ax1.set_ylim(0.0, 1.02) ax1.set_xlabel("Current broad co-missingness score") ax1.set_ylabel("Strict pairwise co-missingness score") ax1.set_title( "Dataset-model panels\n" f"overlap n={overlap_df.shape[0]}, datasets={overlap_df['dataset_id'].nunique()}" ) ax1.grid(alpha=0.25, linewidth=0.8) else: ax1.text(0.5, 0.5, "No strict-pairwise-applicable panels", ha="center", va="center", transform=ax1.transAxes) ax1.set_axis_off()
fig.suptitle( "Review audit: broad structured missingness vs strict pairwise co-missingness", fontsize=14, ) fig.savefig(out_path, dpi=220, bbox_inches="tight") fig.savefig(out_path.with_suffix(".pdf"), bbox_inches="tight") plt.close(fig)
def run_review() -> dict[str, Any]: _ensure_dirs() review_df, pair_df, model_df, coverage_df = _build_review_outputs()
_write_csv(review_df, DATA_DIR / "current_vs_strict_pairwise_asset_review.csv") _write_csv(pair_df, DATA_DIR / "strict_pairwise_pair_scores.csv") _write_csv(model_df, DATA_DIR / "current_vs_strict_pairwise_model_summary.csv") _write_csv(coverage_df, DATA_DIR / "strict_pairwise_dataset_coverage.csv")
figure_path = FIG_DIR / "current_vs_strict_pairwise_review.png" _plot_review_figure(review_df, model_df, figure_path)
overlap_df = review_df.loc[review_df["strict_pairwise_comissing_score"].notna()].copy() note_lines = [ "# Strict Pairwise Review", "", "This is a temporary audit only. It does not change the official missingness bundle.", "", "## Audit definition", "", "- Current broad score: official `co_missingness_pattern_consistency` from the direct evaluator.", "- Strict pairwise score: only use unordered pairs of active missing-target columns.", "- For each pair `(A, B)`, score `A | B_missing_indicator` and `B | A_missing_indicator` with the same 0.7 profile + 0.3 strength formula, then average the two directions.", "- Final strict pairwise score = mean over all unordered missing-target pairs.", "", "## Coverage", "", f"- Asset/panel rows reviewed: `{review_df.shape[0]}`", f"- Overlap rows with strict pairwise defined: `{overlap_df.shape[0]}`", f"- Datasets with strict pairwise defined: `{overlap_df['dataset_id'].nunique() if not overlap_df.empty else 0}`", f"- Models with strict pairwise defined: `{overlap_df['model_id'].nunique() if not overlap_df.empty else 0}`", "", "## Main caveat", "", "- Strict pairwise is undefined when a dataset has fewer than 2 active missing-target columns.", "- So this review is a support-reduced audit, not a drop-in replacement for the official broad score.", ] (NOTES_DIR / "review.md").write_text("\n".join(note_lines) + "\n", encoding="utf-8")
return { "review_csv": DATA_DIR / "current_vs_strict_pairwise_asset_review.csv", "pair_csv": DATA_DIR / "strict_pairwise_pair_scores.csv", "model_csv": DATA_DIR / "current_vs_strict_pairwise_model_summary.csv", "coverage_csv": DATA_DIR / "strict_pairwise_dataset_coverage.csv", "figure_png": figure_path, "figure_pdf": figure_path.with_suffix(".pdf"), "note_md": NOTES_DIR / "review.md", "panel_count": int(review_df.shape[0]), "overlap_panel_count": int(overlap_df.shape[0]), }
if __name__ == "__main__": outputs = run_review() for key, value in outputs.items(): print(f"{key}: {value}")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171#!/usr/bin/env python3"""Build a standardized missingness breakdown bundle.
This runner follows the same four-core-figure contract as the otherquery five-part breakdown tasks:
1. `missingness_tradeoff_scatter_main`2. `missingness_prefix_bars_appendix`3. `missingness_dataset_model_heatmap_appendix`4. `missingness_model_subitem_heatmap_appendix`
If the current unified analysis run still has no missingness query rows,the runner emits explicit placeholder artifacts instead of silentlyleaving the slot empty."""
from __future__ import annotations
import csvimport jsonimport mathimport subprocessimport sysimport argparsefrom collections import defaultdictfrom pathlib import Pathfrom typing import Any
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[4]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from src.eval.analytics_contract import annotate_query_row_with_contractfrom src.eval.query_fivepart_breakdown.common_final import render_final_readme, sync_final_outputsfrom src.eval.common import ( DEFAULT_SQL_SOURCE_VERSION, resolve_requested_sql_source_version, resolve_task_run_dir_for_sql_source, sql_source_label,)from src.eval.query_fivepart_breakdown.common_final import versioned_namefrom src.eval.query_fivepart_breakdown.common_heatmap_palette import ( format_heatmap_latex_cell, get_heatmap_cmap,)from src.eval.query_fivepart_breakdown.common_model_subitem_grouped_bars import ( plot_model_subitem_grouped_bar_preview, write_model_subitem_grouped_bar_tex,)from src.eval.query_fivepart_breakdown.common_model_subitem_heatmap import ( build_model_subitem_heatmap_df, plot_model_subitem_heatmap_preview, write_model_subitem_heatmap_tex,)
EVALUATION_ROOT = PROJECT_ROOT / "Evaluation"ANALYSIS_ROOT = EVALUATION_ROOT / "analysis"OUTPUT_ROOT = EVALUATION_ROOT / "query_fivepart_breakdown" / "missingness_breakdown"DATA_DIR = OUTPUT_ROOT / "data"FIG_DIR = OUTPUT_ROOT / "figures"FINAL_DIR = OUTPUT_ROOT / "final"OUTPUT_VERSION_TAG = resolve_requested_sql_source_version("analysis", DEFAULT_SQL_SOURCE_VERSION)
TARGET_FAMILY = "missingness_structure"REAL_MODEL_ID = "real"SUBITEM_ORDER = [ "marginal_missing_rate_consistency", "co_missingness_pattern_consistency",]EXTRA_INSIGHT_METRICS = [ "co_missing_strength_score", "co_missing_composite_score",]SUBITEM_LABELS = { "marginal_missing_rate_consistency": "Marginal missing-rate consistency", "co_missingness_pattern_consistency": "Co-missingness pattern consistency",}MODEL_LABELS = { "real": "REAL", "arf": "ARF", "bayesnet": "BayesNet", "cdtd": "CDTD", "codi": "CoDi", "ctgan": "CTGAN", "forestdiffusion": "ForestDiffusion", "goggle": "GOGGLE", "realtabformer": "RealTabFormer", "rtf": "RealTabFormer", "tabbyflow": "TabbyFlow", "tabddpm": "TabDDPM", "tabdiff": "TabDiff", "tabpfgen": "TabPFGen", "tabsyn": "TabSyn", "tvae": "TVAE",}MODEL_COLORS = { "real": "#000000", "realtabformer": "#332288", "tvae": "#4477AA", "forestdiffusion": "#228833", "tabddpm": "#EE7733", "tabsyn": "#66CCEE", "tabdiff": "#AA3377", "ctgan": "#EE6677", "arf": "#777777", "bayesnet": "#CCBB44", "tabpfgen": "#009988", "tabbyflow": "#882255",}MODEL_ORDER = [ "arf", "bayesnet", "ctgan", "forestdiffusion", "realtabformer", "tabbyflow", "tabddpm", "tabdiff", "tabpfgen", "tabsyn", "tvae",]EXCLUDED_MODELS = {"cdtd", "codi", "goggle"}MODEL_ALIASES = {"rtf": "realtabformer"}SERVER_PRIORITY = {"rtx_5090": 2, "rtx_pro_6000": 1}ROOT_PRIORITY = {"SynOutput-5090": 2, "SynOutput": 1}
def _ensure_dirs() -> None: for path in [OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR]: path.mkdir(parents=True, exist_ok=True)
def _normalize_model(model_id: Any) -> str: key = str(model_id or "").strip().lower() return MODEL_ALIASES.get(key, key)
def _model_label(model_id: str) -> str: return MODEL_LABELS.get(model_id, model_id)
def _model_sort_key(model_id: str) -> tuple[int, str]: if str(model_id).strip().lower() == REAL_MODEL_ID: return (0, _model_label(model_id)) return (1, _model_label(model_id).lower())
def _sorted_model_ids(model_ids: list[str] | set[str]) -> list[str]: return sorted({str(item) for item in model_ids}, key=_model_sort_key)
def _dataset_prefix(dataset_id: str) -> str: return str(dataset_id or "").strip().lower()[:1]
def _dataset_sort_key(dataset_id: str) -> tuple[int, int, str]: text = str(dataset_id or "").strip() if len(text) < 2 or not text[1:].isdigit(): return (99, 10**9, text) prefix_order = {"c": 0, "m": 1, "n": 2}.get(text[0].lower(), 50) return (prefix_order, int(text[1:]), text)
def _asset_sort_key(row: dict[str, Any]) -> tuple[int, int, str, str]: server = str(row.get("server_type") or "").strip().lower() root_name = str(row.get("root_name") or "").strip() run_id = str(row.get("run_id") or "").strip() asset_key = str(row.get("asset_key") or "").strip() return ( SERVER_PRIORITY.get(server, 0), ROOT_PRIORITY.get(root_name, 0), run_id, asset_key, )
def _find_primary_analysis_run() -> Path: resolved = resolve_task_run_dir_for_sql_source("analysis", OUTPUT_VERSION_TAG) if resolved is not None: return resolved raise FileNotFoundError(f"No analysis run found for sql_source_version={OUTPUT_VERSION_TAG!r}.")
def _run_direct_missingness_eval() -> dict[str, Path]: from tests.comissing_condition_eval import evaluate_all_synthetic_assets
direct_root = DATA_DIR / "_direct_eval" expected = { "dataset_context": direct_root / "co_missing_dataset_context.csv", "asset_scores": direct_root / "co_missing_asset_scores.csv", "target_scores": direct_root / "co_missing_target_scores.csv", "model_dataset_summary": direct_root / "co_missing_model_dataset_summary.csv", "model_overall_summary": direct_root / "co_missing_model_overall_summary.csv", } if all(path.exists() for path in expected.values()): try: asset_df = pd.read_csv(expected["asset_scores"], encoding="utf-8-sig", nrows=5) model_dataset_df = pd.read_csv(expected["model_dataset_summary"], encoding="utf-8-sig", nrows=5) required_columns = {"co_missing_strength_score", "co_missing_composite_score"} if required_columns.issubset(set(asset_df.columns)) and required_columns.issubset(set(model_dataset_df.columns)): return expected except Exception: pass return evaluate_all_synthetic_assets(direct_root)
def _load_primary_assets(asset_csv: Path) -> tuple[dict[tuple[str, str], dict[str, Any]], list[dict[str, Any]]]: with asset_csv.open("r", encoding="utf-8-sig", newline="") as handle: rows = [dict(row) for row in csv.DictReader(handle)]
grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) for row in rows: dataset_id = str(row.get("dataset_id") or "").strip() model_id = _normalize_model(row.get("model_id")) if not dataset_id or not model_id or model_id in EXCLUDED_MODELS: continue row["model_id"] = model_id row["model_label"] = _model_label(model_id) grouped[(dataset_id, model_id)].append(row)
chosen: dict[tuple[str, str], dict[str, Any]] = {} audit_rows: list[dict[str, Any]] = [] for key, items in grouped.items(): ranked = sorted(items, key=_asset_sort_key, reverse=True) chosen[key] = ranked[0] for dropped in ranked[1:]: audit_rows.append( { "dataset_id": key[0], "model_id": key[1], "kept_asset_key": ranked[0].get("asset_key"), "dropped_asset_key": dropped.get("asset_key"), "kept_run_id": ranked[0].get("run_id"), "dropped_run_id": dropped.get("run_id"), } ) return chosen, audit_rows
def _stream_missingness_query_rows( query_jsonl: Path, primary_assets: dict[tuple[str, str], dict[str, Any]],) -> list[dict[str, Any]]: chosen_keys = { (dataset_id, model_id): str(row.get("asset_key") or "") for (dataset_id, model_id), row in primary_assets.items() } out: list[dict[str, Any]] = [] with query_jsonl.open("r", encoding="utf-8") as handle: for raw in handle: line = raw.strip() if not line: continue row = json.loads(line) dataset_id = str(row.get("dataset_id") or "").strip() model_id = _normalize_model(row.get("model_id")) if not dataset_id or not model_id or model_id in EXCLUDED_MODELS: continue if chosen_keys.get((dataset_id, model_id)) != str(row.get("asset_key") or ""): continue if str(row.get("family_id") or "").strip().lower() != TARGET_FAMILY: continue annotated = dict(row) if not annotated.get("canonical_subitem_id"): annotated = annotate_query_row_with_contract(annotated) subitem_id = str(annotated.get("canonical_subitem_id") or "").strip() if subitem_id not in SUBITEM_ORDER: continue try: score_value = float(annotated.get("query_score")) except Exception: continue out.append( { "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "model_id": model_id, "model_label": _model_label(model_id), "asset_key": str(annotated.get("asset_key") or ""), "subitem_id": subitem_id, "subitem_label": SUBITEM_LABELS[subitem_id], "query_id": str(annotated.get("query_id") or ""), "query_score": score_value, "template_id": str(annotated.get("template_id") or ""), "template_name": str(annotated.get("template_name") or ""), "question": str(annotated.get("question") or ""), "sql_engine": str(annotated.get("sql_engine") or ""), } ) return out
def _inject_real_rows(query_rows: list[dict[str, Any]]) -> list[dict[str, Any]]: by_dataset_query: dict[tuple[str, str], dict[str, Any]] = {} for row in query_rows: key = (str(row["dataset_id"]), str(row["query_id"])) if key not in by_dataset_query: by_dataset_query[key] = row
real_rows: list[dict[str, Any]] = [] for (dataset_id, _query_id), row in sorted(by_dataset_query.items(), key=lambda item: (_dataset_sort_key(item[0][0]), item[0][1])): real_rows.append( { **row, "model_id": REAL_MODEL_ID, "model_label": _model_label(REAL_MODEL_ID), "asset_key": f"{dataset_id}__real_reference", "query_score": 1.0, "sql_engine": "real-reference", } ) return query_rows + real_rows
def _write_csv(df: pd.DataFrame, path: Path) -> None: df.to_csv(path, index=False, encoding="utf-8")
def _metric_stats(series: pd.Series) -> dict[str, float | int | None]: clean = pd.to_numeric(series, errors="coerce").dropna() n = int(clean.shape[0]) if n == 0: return { "n": 0, "mean": None, "std": None, "se": None, "ci95_low": None, "ci95_high": None, "ci95_radius": None, } mean_val = float(clean.mean()) std_val = float(clean.std(ddof=1)) if n > 1 else 0.0 se_val = float(std_val / math.sqrt(n)) if n > 1 else 0.0 ci_radius = 1.96 * se_val return { "n": n, "mean": round(mean_val, 6), "std": round(std_val, 6), "se": round(se_val, 6), "ci95_low": round(mean_val - ci_radius, 6), "ci95_high": round(mean_val + ci_radius, 6), "ci95_radius": round(ci_radius, 6), }
def _escape_tex(text: str) -> str: replacements = { "\\": r"\textbackslash{}", "&": r"\&", "%": r"\%", "$": r"\$", "#": r"\#", "_": r"\_", "{": r"\{", "}": r"\}", } out = str(text) for src, dst in replacements.items(): out = out.replace(src, dst) return out
def _tex_preamble() -> str: return "\n".join( [ r"\documentclass[tikz,border=4pt]{standalone}", r"\usepackage{pgfplots}", r"\usepgfplotslibrary{groupplots}", r"\usepackage{xcolor}", r"\pgfplotsset{compat=1.18}", "", ] )
def _build_dataset_model_scores(query_df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: subitems = ( query_df.groupby( ["dataset_id", "dataset_prefix", "model_id", "model_label", "subitem_id", "subitem_label"], as_index=False, ) .agg(query_count=("query_id", "count"), subitem_score=("query_score", "mean")) .reset_index(drop=True) ) pivot = ( subitems.pivot_table( index=["dataset_id", "dataset_prefix", "model_id", "model_label"], columns="subitem_id", values="subitem_score", aggfunc="mean", ) .reset_index() .rename_axis(None, axis=1) ) counts = ( subitems.pivot_table( index=["dataset_id", "dataset_prefix", "model_id", "model_label"], columns="subitem_id", values="query_count", aggfunc="sum", ) .reset_index() .rename_axis(None, axis=1) ) wide = pivot.merge(counts, on=["dataset_id", "dataset_prefix", "model_id", "model_label"], suffixes=("", "__query_count")) for metric in SUBITEM_ORDER: wide[metric] = pd.to_numeric(wide[metric], errors="coerce") wide["missingness_structure_score"] = wide[SUBITEM_ORDER].mean(axis=1, skipna=True) wide["marginal_minus_comissing"] = wide["marginal_missing_rate_consistency"] - wide["co_missingness_pattern_consistency"] wide["active_subitem_count"] = wide[SUBITEM_ORDER].notna().sum(axis=1) wide["dataset_sort"] = wide["dataset_id"].map(_dataset_sort_key) wide["model_sort"] = wide["model_id"].map(_model_sort_key) wide = wide.sort_values(["dataset_sort", "model_sort"]).drop(columns=["dataset_sort", "model_sort"]).reset_index(drop=True) return subitems, wide
def _build_dataset_model_scores_from_direct_summary(model_dataset_df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: if model_dataset_df.empty: return ( pd.DataFrame( columns=[ "dataset_id", "dataset_prefix", "model_id", "model_label", "subitem_id", "subitem_label", "query_count", "subitem_score", ] ), pd.DataFrame( columns=[ "dataset_id", "dataset_prefix", "model_id", "model_label", *SUBITEM_ORDER, *EXTRA_INSIGHT_METRICS, "missingness_structure_score", "marginal_minus_comissing", "profile_minus_strength", "active_subitem_count", "asset_count", "applicable_asset_count", ] ), )
df = model_dataset_df.copy() df["model_id"] = df["model_id"].map(_normalize_model) df = df.loc[~df["model_id"].isin(EXCLUDED_MODELS)].copy() df["model_label"] = df["model_id"].map(_model_label) df["dataset_prefix"] = df["dataset_id"].map(_dataset_prefix) for metric in SUBITEM_ORDER + EXTRA_INSIGHT_METRICS + ["missingness_structure_score"]: if metric not in df.columns: df[metric] = pd.NA df[metric] = pd.to_numeric(df[metric], errors="coerce") df["marginal_minus_comissing"] = df["marginal_missing_rate_consistency"] - df["co_missingness_pattern_consistency"] df["profile_minus_strength"] = df["co_missingness_pattern_consistency"] - df["co_missing_strength_score"] df["active_subitem_count"] = df[SUBITEM_ORDER].notna().sum(axis=1) df["dataset_sort"] = df["dataset_id"].map(_dataset_sort_key) df["model_sort"] = df["model_id"].map(_model_sort_key) wide = ( df.sort_values(["dataset_sort", "model_sort"])[ [ "dataset_id", "dataset_prefix", "model_id", "model_label", *SUBITEM_ORDER, *EXTRA_INSIGHT_METRICS, "missingness_structure_score", "marginal_minus_comissing", "profile_minus_strength", "active_subitem_count", "asset_count", "applicable_asset_count", ] ] .reset_index(drop=True) )
subitem_rows: list[dict[str, Any]] = [] for row in wide.itertuples(index=False): applicable_count = int(getattr(row, "applicable_asset_count", 0) or 0) for subitem_id in SUBITEM_ORDER: subitem_rows.append( { "dataset_id": row.dataset_id, "dataset_prefix": row.dataset_prefix, "model_id": row.model_id, "model_label": row.model_label, "subitem_id": subitem_id, "subitem_label": SUBITEM_LABELS[subitem_id], "query_count": applicable_count, "subitem_score": getattr(row, subitem_id, None), } ) return pd.DataFrame(subitem_rows), wide
def _build_model_summary(dataset_model_df: pd.DataFrame) -> pd.DataFrame: rows: list[dict[str, Any]] = [] metrics = SUBITEM_ORDER + EXTRA_INSIGHT_METRICS + ["missingness_structure_score", "marginal_minus_comissing", "profile_minus_strength"] for model_id, group in dataset_model_df.groupby("model_id", sort=False): payload = { "model_id": model_id, "model_label": _model_label(model_id), "dataset_count": int(group["dataset_id"].nunique()), "dataset_prefixes": ",".join(sorted(group["dataset_prefix"].dropna().astype(str).unique())), } for metric in metrics: stats = _metric_stats(group[metric]) payload[f"{metric}__mean"] = stats["mean"] payload[f"{metric}__std"] = stats["std"] payload[f"{metric}__se"] = stats["se"] payload[f"{metric}__ci95_low"] = stats["ci95_low"] payload[f"{metric}__ci95_high"] = stats["ci95_high"] payload[f"{metric}__ci95_radius"] = stats["ci95_radius"] rows.append(payload)
summary = pd.DataFrame(rows) if summary.empty: return summary summary["model_sort"] = summary["model_id"].map(_model_sort_key) return summary.sort_values(["model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True)
def _build_prefix_summary(dataset_model_df: pd.DataFrame) -> pd.DataFrame: rows: list[dict[str, Any]] = [] for (model_id, prefix), group in dataset_model_df.groupby(["model_id", "dataset_prefix"], sort=False): rows.append( { "model_id": model_id, "model_label": _model_label(model_id), "dataset_prefix": prefix, "dataset_count": int(group["dataset_id"].nunique()), "marginal_missing_rate_consistency": round(float(pd.to_numeric(group["marginal_missing_rate_consistency"], errors="coerce").dropna().mean()), 6), "co_missingness_pattern_consistency": round(float(pd.to_numeric(group["co_missingness_pattern_consistency"], errors="coerce").dropna().mean()), 6), "co_missing_strength_score": round(float(pd.to_numeric(group["co_missing_strength_score"], errors="coerce").dropna().mean()), 6), "missingness_structure_score": round(float(pd.to_numeric(group["missingness_structure_score"], errors="coerce").dropna().mean()), 6), } ) summary = pd.DataFrame(rows) if summary.empty: return summary summary["model_sort"] = summary["model_id"].map(_model_sort_key) return summary.sort_values(["dataset_prefix", "model_sort"]).drop(columns=["model_sort"]).reset_index(drop=True)
def _build_dataset_summary(dataset_model_df: pd.DataFrame) -> pd.DataFrame: rows: list[dict[str, Any]] = [] for dataset_id, group in dataset_model_df.groupby("dataset_id", sort=False): rows.append( { "dataset_id": dataset_id, "dataset_prefix": _dataset_prefix(dataset_id), "model_count": int(group["model_id"].nunique()), "missingness_structure_score": round(float(pd.to_numeric(group["missingness_structure_score"], errors="coerce").dropna().mean()), 6), } ) summary = pd.DataFrame(rows) if summary.empty: return summary summary["dataset_sort"] = summary["dataset_id"].map(_dataset_sort_key) return summary.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True)
def _build_heatmap_data(dataset_model_df: pd.DataFrame) -> pd.DataFrame: heatmap = ( dataset_model_df.pivot_table( index="dataset_id", columns="model_id", values="missingness_structure_score", aggfunc="mean", ) .reset_index() .rename_axis(None, axis=1) ) if heatmap.empty: return heatmap ordered_models = [item for item in _sorted_model_ids(dataset_model_df["model_id"].tolist()) if item in heatmap.columns] heatmap["dataset_sort"] = heatmap["dataset_id"].map(_dataset_sort_key) heatmap = heatmap.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True) return heatmap[["dataset_id"] + ordered_models]
def _build_prefix_plot_data(prefix_summary_df: pd.DataFrame) -> pd.DataFrame: rows: list[dict[str, Any]] = [] for model_id in _sorted_model_ids(prefix_summary_df["model_id"].tolist()): payload: dict[str, Any] = {"model_id": model_id, "model_label": _model_label(model_id)} subset = prefix_summary_df.loc[prefix_summary_df["model_id"] == model_id] for prefix in ["c", "m", "n"]: match = subset.loc[subset["dataset_prefix"] == prefix, "missingness_structure_score"] payload[prefix] = float(match.iloc[0]) if not match.empty else None rows.append(payload) return pd.DataFrame(rows)
def _write_tradeoff_tex(model_summary_df: pd.DataFrame, path: Path) -> None: color_defs = [ rf"\definecolor{{model{row.model_id}}}{{HTML}}{{{MODEL_COLORS[row.model_id].replace('#', '')}}}" for row in model_summary_df.itertuples() if row.model_id in MODEL_COLORS ] lines = [ _tex_preamble(), *color_defs, r"\begin{document}", r"\begin{tikzpicture}", r"""\begin{axis}[width=11.2cm,height=8.4cm,xmin=0, xmax=1.02,ymin=0, ymax=1.02,xlabel={Marginal missing-rate consistency},ylabel={Co-missingness pattern consistency},grid=major,grid style={gray!20},]""", ] for row in model_summary_df.itertuples(): x = getattr(row, "marginal_missing_rate_consistency__mean") y = getattr(row, "co_missingness_pattern_consistency__mean") if x is None or y is None: continue color_name = f"model{row.model_id}" lines.append( rf"\addplot[only marks, mark=*, mark size=2.2pt, {color_name}] coordinates {{({float(x):.6f},{float(y):.6f})}};" ) lines.append( rf"\node[anchor=west, font=\scriptsize, text={color_name}] at (axis cs:{float(x):.6f},{float(y):.6f}) {{{_escape_tex(row.model_label)}}};" ) lines.extend([r"\end{axis}", r"\end{tikzpicture}", r"\end{document}", ""]) path.write_text("\n".join(lines), encoding="utf-8")
def _write_prefix_bar_tex(prefix_plot_df: pd.DataFrame, path: Path) -> None: model_labels = [_escape_tex(str(item)) for item in prefix_plot_df["model_label"].tolist()] xticklabels = ",".join(model_labels) color_defs = [ rf"\definecolor{{model{row.model_id}}}{{HTML}}{{{MODEL_COLORS[row.model_id].replace('#', '')}}}" for row in prefix_plot_df.itertuples() if row.model_id in MODEL_COLORS ] lines = [ _tex_preamble(), *color_defs, r"\begin{document}", r"\begin{tikzpicture}", r"""\begin{groupplot}[group style={group size=3 by 1, horizontal sep=1.0cm},width=0.31\textwidth,height=0.46\textwidth,ymin=0, ymax=1.02,xtick={1,...,%d},xticklabels={%s},x tick label style={rotate=60, anchor=east, font=\scriptsize},grid=major,grid style={gray!20},]""" % (len(model_labels), xticklabels), ] for prefix in ["c", "m", "n"]: lines.append(rf"\nextgroupplot[title={{{prefix.upper()} datasets}}, ylabel={{Mean score}}]") for idx, row in enumerate(prefix_plot_df.itertuples(), start=1): value = getattr(row, prefix, None) if value is None or pd.isna(value): continue color_name = f"model{row.model_id}" if row.model_id in MODEL_COLORS else "gray" lines.append(rf"\addplot[ybar, draw={color_name}, fill={color_name}] coordinates {{({idx},{float(value):.6f})}};") lines.extend([r"\end{groupplot}", r"\end{tikzpicture}", r"\end{document}", ""]) path.write_text("\n".join(lines), encoding="utf-8")
def _write_heatmap_tex(heatmap_df: pd.DataFrame, path: Path) -> None: ordered = heatmap_df.copy() model_cols = [column for column in ordered.columns if column != "dataset_id"] display = ordered[["dataset_id"] + model_cols].copy().fillna("") lines = [ r"\documentclass{standalone}", r"\usepackage[table]{xcolor}", r"\usepackage{xcolor}", r"\usepackage{booktabs}", r"\begin{document}", r"\scriptsize", r"\textbf{Missingness dataset-model heatmap}\\[0.4em]", r"\emph{Score, 0--1; missing cells stay white.}\\[0.5em]", r"\setlength{\tabcolsep}{4pt}", rf"\begin{{tabular}}{{l{'c' * len(model_cols)}}}", r"\toprule", "Dataset & " + " & ".join(_escape_tex(column) for column in model_cols) + r" \\", r"\midrule", ] for row in display.itertuples(index=False): cells = [_escape_tex(str(getattr(row, "dataset_id")))] for model in model_cols: cells.append(format_heatmap_latex_cell(getattr(row, model))) lines.append(" & ".join(cells) + r" \\") lines.extend([r"\bottomrule", r"\end{tabular}", r"\end{document}", ""]) path.write_text("\n".join(lines), encoding="utf-8")
def _plot_tradeoff_preview(model_summary_df: pd.DataFrame, pdf_path: Path, png_path: Path) -> None: fig, ax = plt.subplots(figsize=(8.2, 6.0)) for row in model_summary_df.itertuples(): x = getattr(row, "marginal_missing_rate_consistency__mean") y = getattr(row, "co_missingness_pattern_consistency__mean") if x is None or y is None: continue color = MODEL_COLORS.get(str(row.model_id), "#777777") ax.scatter(float(x), float(y), s=56, color=color) ax.text(float(x) + 0.012, float(y) + 0.008, str(row.model_label), fontsize=8, color=color) ax.set_xlim(0.0, 1.02) ax.set_ylim(0.0, 1.02) ax.set_xlabel("Marginal missing-rate consistency") ax.set_ylabel("Co-missingness pattern consistency") ax.set_title("Missingness trade-off scatter") ax.grid(alpha=0.25) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") plt.close(fig)
def _plot_prefix_bar_preview(prefix_plot_df: pd.DataFrame, pdf_path: Path, png_path: Path) -> None: fig, axes = plt.subplots(1, 3, figsize=(14.4, 6.2), sharey=True) for ax, prefix in zip(axes, ["c", "m", "n"]): values = pd.to_numeric(prefix_plot_df[prefix], errors="coerce") colors = [MODEL_COLORS.get(model_id, "#777777") for model_id in prefix_plot_df["model_id"]] ax.bar(range(len(prefix_plot_df)), values, color=colors) ax.set_title(f"{prefix.upper()} datasets") ax.set_ylim(0.0, 1.02) ax.set_xticks(range(len(prefix_plot_df))) ax.set_xticklabels(prefix_plot_df["model_label"], rotation=60, ha="right", fontsize=8) ax.grid(axis="y", alpha=0.25) axes[0].set_ylabel("Mean score") fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") plt.close(fig)
def _plot_heatmap_preview(heatmap_df: pd.DataFrame, pdf_path: Path, png_path: Path) -> None: ordered = heatmap_df.copy() model_cols = [column for column in ordered.columns if column != "dataset_id"] matrix = ordered[model_cols].to_numpy(dtype=float) fig_height = max(7.2, 0.22 * len(ordered) + 1.8) fig, ax = plt.subplots(figsize=(10.4, fig_height)) im = ax.imshow(matrix, vmin=0.0, vmax=1.0, aspect="auto", cmap=get_heatmap_cmap()) ax.set_xticks(range(len(model_cols))) ax.set_xticklabels(model_cols, rotation=60, ha="right", fontsize=8) ax.set_yticks(range(len(ordered))) ax.set_yticklabels(ordered["dataset_id"], fontsize=7) ax.set_title("Missingness dataset-model heatmap") fig.colorbar(im, ax=ax, fraction=0.035, pad=0.02) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") plt.close(fig)
def _write_placeholder_tex(path: Path, title: str, message: str) -> None: content = "\n".join( [ _tex_preamble(), r"\begin{document}", r"\begin{tikzpicture}", r"\node[draw=gray!60, rounded corners=4pt, fill=gray!8, text width=11.5cm, align=center, inner sep=12pt] {", rf"\textbf{{{_escape_tex(title)}}}\\[0.7em]{_escape_tex(message)}", r"};", r"\end{tikzpicture}", r"\end{document}", "", ] ) path.write_text(content, encoding="utf-8")
def _plot_placeholder_preview(pdf_path: Path, png_path: Path, title: str, message: str) -> None: fig, ax = plt.subplots(figsize=(8.6, 4.8)) ax.axis("off") ax.text( 0.5, 0.62, title, ha="center", va="center", fontsize=15, fontweight="bold", ) ax.text( 0.5, 0.38, message, ha="center", va="center", fontsize=11, wrap=True, ) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") plt.close(fig)
def _try_compile_tex(tex_path: Path) -> tuple[bool, str]: try: proc = subprocess.run( ["latexmk", "-pdf", tex_path.name], cwd=tex_path.parent, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, ) except FileNotFoundError: return False, "latexmk not available" return proc.returncode == 0, proc.stdout[-1200:]
def _write_placeholder_bundle(run_dir: Path, audit_rows: list[dict[str, Any]]) -> dict[str, Any]: message = ( "No `missingness_structure` query rows were found in the current unified analysis run. " "These standardized placeholders keep the five-part appendix structure stable until missingness queries are emitted." ) placeholder_specs = [ ("missingness_tradeoff_scatter_main", "Missingness Trade-Off Placeholder"), ("missingness_prefix_bars_appendix", "Missingness Prefix Placeholder"), ("missingness_dataset_model_heatmap_appendix", "Missingness Heatmap Placeholder"), ("missingness_model_subitem_heatmap_appendix", "Missingness Model-Subitem Placeholder"), ("missingness_family_subitem_bars_appendix", "Missingness Family/Subitem Bars Placeholder"), ] final_files: list[Path] = [DATA_DIR / "duplicate_asset_audit.csv", DATA_DIR / "missingness_query_rows.csv", OUTPUT_ROOT / "analysis_report.md"] must_do_aliases: dict[str, Path] = {} compile_notes: dict[str, tuple[bool, str]] = {} for stem, title in placeholder_specs: tex_path = FIG_DIR / f"{stem}.tex" pdf_path = FIG_DIR / f"{stem}.pdf" png_path = FIG_DIR / f"{stem}.png" _write_placeholder_tex(tex_path, title, message) _plot_placeholder_preview(pdf_path, png_path, title, message) compile_notes[stem] = _try_compile_tex(tex_path) final_files.extend([tex_path, pdf_path, png_path]) must_do_aliases[f"{stem}.tex"] = tex_path must_do_aliases[f"{stem}.pdf"] = pdf_path must_do_aliases[f"{stem}.png"] = png_path
_write_csv(pd.DataFrame(audit_rows), DATA_DIR / "duplicate_asset_audit.csv") _write_csv(pd.DataFrame(columns=["dataset_id", "model_id", "subitem_id", "query_id", "query_score"]), DATA_DIR / "missingness_query_rows.csv") (OUTPUT_ROOT / "analysis_report.md").write_text( "\n".join( [ "# Missingness Breakdown", "", f"- Source analysis run: `{run_dir.name}`", "- Current status: no missingness query rows available in the unified analysis export.", "- Action taken: emitted standardized placeholder must-do figures so the five-part appendix structure stays complete.", "", ] ), encoding="utf-8", ) version_tag = OUTPUT_VERSION_TAG readme = render_final_readme( title="Missingness Breakdown Final", summary=f"This directory contains the standardized missingness slot for `{sql_source_label(version_tag)}` (`{version_tag}`). The current repository run has no missingness query rows yet, so `must_do/` contains explicit placeholders rather than silent gaps.", primary_files=[versioned_name(name, version_tag) for name in [ "missingness_tradeoff_scatter_main.tex", "missingness_tradeoff_scatter_main.pdf", "missingness_tradeoff_scatter_main.png", "missingness_prefix_bars_appendix.tex", "missingness_prefix_bars_appendix.pdf", "missingness_prefix_bars_appendix.png", "missingness_dataset_model_heatmap_appendix.tex", "missingness_dataset_model_heatmap_appendix.pdf", "missingness_dataset_model_heatmap_appendix.png", "missingness_model_subitem_heatmap_appendix.tex", "missingness_model_subitem_heatmap_appendix.pdf", "missingness_model_subitem_heatmap_appendix.png", "missingness_family_subitem_bars_appendix.tex", "missingness_family_subitem_bars_appendix.pdf", "missingness_family_subitem_bars_appendix.png", ]], must_do_files=[versioned_name(name, version_tag) for name in must_do_aliases.keys()], support_files=[ *[versioned_name(name, version_tag) for name in [ "analysis_report.md", "missingness_query_rows.csv", "duplicate_asset_audit.csv", ]], ], notes=[ "These placeholders are intentional and should be replaced automatically once missingness queries are present in the unified analysis run.", ], ) sync_final_outputs(FINAL_DIR, final_files, must_do_aliases, version_tag=version_tag, copy_plain_files=False) (FINAL_DIR / "README.md").write_text(readme, encoding="utf-8") manifest = { "task": "missingness_breakdown", "sql_source_version": version_tag, "sql_source_label": sql_source_label(version_tag), "source_analysis_run": run_dir.name, "query_row_count": 0, "status": "placeholder_no_query_rows", "compile_notes": {key: {"success": value[0], "note": value[1]} for key, value in compile_notes.items()}, } (OUTPUT_ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") return manifest
def run_missingness_breakdown(*, analysis_run_dir: Path | None = None) -> dict[str, Any]: _ensure_dirs() analysis_run_dir = analysis_run_dir.resolve() if analysis_run_dir is not None else _find_primary_analysis_run() audit_rows: list[dict[str, Any]] = [] direct_outputs = _run_direct_missingness_eval() direct_dataset_context_df = pd.read_csv(direct_outputs["dataset_context"], encoding="utf-8-sig") direct_asset_scores_df = pd.read_csv(direct_outputs["asset_scores"], encoding="utf-8-sig") direct_target_scores_df = pd.read_csv(direct_outputs["target_scores"], encoding="utf-8-sig") direct_model_dataset_df = pd.read_csv(direct_outputs["model_dataset_summary"], encoding="utf-8-sig") direct_model_overall_df = pd.read_csv(direct_outputs["model_overall_summary"], encoding="utf-8-sig")
subitem_df, dataset_model_df = _build_dataset_model_scores_from_direct_summary(direct_model_dataset_df) if dataset_model_df.empty: return _write_placeholder_bundle(analysis_run_dir, audit_rows)
model_summary_df = _build_model_summary(dataset_model_df) prefix_summary_df = _build_prefix_summary(dataset_model_df) dataset_summary_df = _build_dataset_summary(dataset_model_df) heatmap_df = _build_heatmap_data(dataset_model_df) prefix_plot_df = _build_prefix_plot_data(prefix_summary_df) model_subitem_heatmap_df = build_model_subitem_heatmap_df( model_summary_df.loc[model_summary_df["model_id"].isin(MODEL_ORDER)].copy(), model_id_col="model_id", model_order=MODEL_ORDER, subitem_specs=[ (subitem_id, SUBITEM_LABELS[subitem_id], f"{subitem_id}__mean") for subitem_id in SUBITEM_ORDER ], summary_row_spec=("family_mean", "Family mean", "missingness_structure_score__mean"), )
_write_csv(pd.DataFrame(audit_rows), DATA_DIR / "duplicate_asset_audit.csv") _write_csv( dataset_model_df[ [ "dataset_id", "dataset_prefix", "model_id", "model_label", "marginal_missing_rate_consistency", "co_missingness_pattern_consistency", "co_missing_strength_score", "co_missing_composite_score", "missingness_structure_score", "profile_minus_strength", "asset_count", "applicable_asset_count", ] ], DATA_DIR / "missingness_query_rows.csv", ) _write_csv(subitem_df, DATA_DIR / "dataset_model_subitems.csv") _write_csv(dataset_model_df, DATA_DIR / "dataset_model_scores.csv") _write_csv(model_summary_df, DATA_DIR / "model_summary.csv") _write_csv(prefix_summary_df, DATA_DIR / "prefix_summary.csv") _write_csv(dataset_summary_df, DATA_DIR / "dataset_summary.csv") _write_csv(heatmap_df, DATA_DIR / "dataset_model_heatmap.csv") _write_csv(prefix_plot_df, DATA_DIR / "prefix_plot_data.csv") _write_csv(model_subitem_heatmap_df, DATA_DIR / "model_subitem_heatmap.csv") _write_csv(direct_dataset_context_df, DATA_DIR / "direct_dataset_context.csv") _write_csv(direct_asset_scores_df, DATA_DIR / "direct_asset_scores.csv") _write_csv(direct_target_scores_df, DATA_DIR / "direct_target_scores.csv") _write_csv(direct_model_dataset_df, DATA_DIR / "direct_model_dataset_summary.csv") _write_csv(direct_model_overall_df, DATA_DIR / "direct_model_overall_summary.csv")
tradeoff_tex = FIG_DIR / "missingness_tradeoff_scatter_main.tex" tradeoff_pdf = FIG_DIR / "missingness_tradeoff_scatter_main.pdf" tradeoff_png = FIG_DIR / "missingness_tradeoff_scatter_main.png" prefix_tex = FIG_DIR / "missingness_prefix_bars_appendix.tex" prefix_pdf = FIG_DIR / "missingness_prefix_bars_appendix.pdf" prefix_png = FIG_DIR / "missingness_prefix_bars_appendix.png" heatmap_tex = FIG_DIR / "missingness_dataset_model_heatmap_appendix.tex" heatmap_pdf = FIG_DIR / "missingness_dataset_model_heatmap_appendix.pdf" heatmap_png = FIG_DIR / "missingness_dataset_model_heatmap_appendix.png" model_subitem_heatmap_tex = FIG_DIR / "missingness_model_subitem_heatmap_appendix.tex" model_subitem_heatmap_pdf = FIG_DIR / "missingness_model_subitem_heatmap_appendix.pdf" model_subitem_heatmap_png = FIG_DIR / "missingness_model_subitem_heatmap_appendix.png" grouped_bars_tex = FIG_DIR / "missingness_family_subitem_bars_appendix.tex" grouped_bars_pdf = FIG_DIR / "missingness_family_subitem_bars_appendix.pdf" grouped_bars_png = FIG_DIR / "missingness_family_subitem_bars_appendix.png"
_write_tradeoff_tex(model_summary_df, tradeoff_tex) _write_prefix_bar_tex(prefix_plot_df, prefix_tex) _write_heatmap_tex(heatmap_df, heatmap_tex) write_model_subitem_heatmap_tex( model_subitem_heatmap_df, model_order=MODEL_ORDER, model_label_map=MODEL_LABELS, title="Missingness model-subitem heatmap", colorbar_title="Mean score", path=model_subitem_heatmap_tex, ) write_model_subitem_grouped_bar_tex( model_subitem_heatmap_df, model_order=MODEL_ORDER, model_label_map=MODEL_LABELS, model_color_map=MODEL_COLORS, title="Missingness family and subitem bars", y_label="Score", path=grouped_bars_tex, ) _plot_tradeoff_preview(model_summary_df, tradeoff_pdf, tradeoff_png) _plot_prefix_bar_preview(prefix_plot_df, prefix_pdf, prefix_png) _plot_heatmap_preview(heatmap_df, heatmap_pdf, heatmap_png) plot_model_subitem_heatmap_preview( model_subitem_heatmap_df, model_order=MODEL_ORDER, model_label_map=MODEL_LABELS, title="Missingness model-subitem heatmap", pdf_path=model_subitem_heatmap_pdf, png_path=model_subitem_heatmap_png, ) plot_model_subitem_grouped_bar_preview( model_subitem_heatmap_df, model_order=MODEL_ORDER, model_label_map=MODEL_LABELS, model_color_map=MODEL_COLORS, title="Missingness family and subitem bars", y_label="Score", pdf_path=grouped_bars_pdf, png_path=grouped_bars_png, )
compile_notes = { "tradeoff": _try_compile_tex(tradeoff_tex), "prefix": _try_compile_tex(prefix_tex), "heatmap": _try_compile_tex(heatmap_tex), "model_subitem_heatmap": _try_compile_tex(model_subitem_heatmap_tex), "family_subitem_bars": _try_compile_tex(grouped_bars_tex), } (OUTPUT_ROOT / "analysis_report.md").write_text( "\n".join( [ "# Missingness Breakdown", "", "- Source mode: `direct_missingness_evaluator`", f"- Reference analysis run: `{analysis_run_dir.name}`", f"- Included models: `{model_summary_df.shape[0]}`", f"- Deduplicated dataset-model panels: `{dataset_model_df.shape[0]}`", f"- Direct model-dataset rows used: `{dataset_model_df.shape[0]}`", f"- Direct target rows used: `{direct_target_scores_df.shape[0]}`", "", "## Canonical decomposition", "", "- `missingness_structure = 0.5 * marginal_missing_rate_consistency + 0.5 * co_missingness_pattern_consistency`", "- Canonical `co_missingness_pattern_consistency` now uses profile-only edge averaging.", "- `co_missing_strength_score` is exported separately as an auxiliary diagnostic and is not folded into the two-subitem family score.", "- `co_missing_composite_score` preserves the previous 0.7-profile / 0.3-strength blend for sensitivity analysis only.", "- This bundle bypasses SQL query analysis and uses the canonical direct co-missing evaluator over real-train vs synthetic CSV pairs.", "- The standardized appendix bundle now mirrors tradeoff, prefix, and heatmap views just like the other query families.", "", ] ), encoding="utf-8", )
final_files = [ tradeoff_tex, tradeoff_pdf, tradeoff_png, prefix_tex, prefix_pdf, prefix_png, heatmap_tex, heatmap_pdf, heatmap_png, model_subitem_heatmap_tex, model_subitem_heatmap_pdf, model_subitem_heatmap_png, grouped_bars_tex, grouped_bars_pdf, grouped_bars_png, DATA_DIR / "model_summary.csv", DATA_DIR / "prefix_summary.csv", OUTPUT_ROOT / "analysis_report.md", ] must_do_aliases = { f"{stem}.{suffix}": FIG_DIR / f"{stem}.{suffix}" for stem in [ "missingness_tradeoff_scatter_main", "missingness_prefix_bars_appendix", "missingness_dataset_model_heatmap_appendix", "missingness_model_subitem_heatmap_appendix", "missingness_family_subitem_bars_appendix", ] for suffix in ["tex", "pdf", "png"] } version_tag = OUTPUT_VERSION_TAG sync_final_outputs(FINAL_DIR, final_files, must_do_aliases, version_tag=version_tag, copy_plain_files=False) final_readme = render_final_readme( title="Missingness Breakdown Final", summary=f"This directory contains the paper-facing missingness breakdown artifacts published under `{sql_source_label(version_tag)}` (`{version_tag}`), with the standardized must-do bundle mirrored into `final/must_do/` and `final/{version_tag}/must_do/`.", primary_files=[versioned_name(name, version_tag) for name in [ "missingness_tradeoff_scatter_main.tex", "missingness_tradeoff_scatter_main.pdf", "missingness_tradeoff_scatter_main.png", "missingness_prefix_bars_appendix.tex", "missingness_prefix_bars_appendix.pdf", "missingness_prefix_bars_appendix.png", "missingness_dataset_model_heatmap_appendix.tex", "missingness_dataset_model_heatmap_appendix.pdf", "missingness_dataset_model_heatmap_appendix.png", "missingness_model_subitem_heatmap_appendix.tex", "missingness_model_subitem_heatmap_appendix.pdf", "missingness_model_subitem_heatmap_appendix.png", "missingness_family_subitem_bars_appendix.tex", "missingness_family_subitem_bars_appendix.pdf", "missingness_family_subitem_bars_appendix.png", "model_summary.csv", "prefix_summary.csv", ]], must_do_files=[versioned_name(name, version_tag) for name in must_do_aliases.keys()], support_files=[versioned_name("analysis_report.md", version_tag)], notes=[ f"The active published version tag for this bundle is `{sql_source_label(version_tag)}` (`{version_tag}`).", "The `.tex` files are standalone LaTeX sources. The `.pdf/.png` files are immediate previews for reading in the current environment.", ], ) (FINAL_DIR / "README.md").write_text(final_readme, encoding="utf-8")
manifest = { "task": "missingness_breakdown", "sql_source_version": version_tag, "sql_source_label": sql_source_label(version_tag), "source_mode": "direct_missingness_evaluator", "reference_analysis_run": analysis_run_dir.name, "included_models": model_summary_df["model_id"].tolist(), "dataset_panel_count": int(dataset_model_df.shape[0]), "query_row_count": int(dataset_model_df.shape[0]), "status": "implemented_direct", "compile_notes": {key: {"success": value[0], "note": value[1]} for key, value in compile_notes.items()}, } (OUTPUT_ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") return manifest
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Build the missingness breakdown bundle.") parser.add_argument("--analysis-run-dir", type=Path, default=None, help="Optional analysis run dir.") return parser.parse_args()
def main() -> None: args = parse_args() manifest = run_missingness_breakdown(analysis_run_dir=args.analysis_run_dir) print(json.dumps(manifest, indent=2))
if __name__ == "__main__": main()12"""Strength diagnostic for missingness breakdown."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463#!/usr/bin/env python3"""Paper-facing auxiliary diagnostic for missingness relation-strength fidelity."""
from __future__ import annotations
from pathlib import Pathimport sysfrom typing import Any
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patch, Rectangleimport numpy as npimport pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[5]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from src.eval.query_fivepart_breakdown.common_final import render_final_readme, sync_final_outputsfrom src.eval.query_fivepart_breakdown.common_heatmap_palette import get_heatmap_cmap
MISSINGNESS_ROOT = PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown"INPUT_DATA_DIR = MISSINGNESS_ROOT / "data"OUTPUT_ROOT = MISSINGNESS_ROOT / "strength_diagnostic"DATA_DIR = OUTPUT_ROOT / "data"FIG_DIR = OUTPUT_ROOT / "figures"FINAL_DIR = OUTPUT_ROOT / "final"
MODEL_ORDER = [ "arf", "bayesnet", "ctgan", "forestdiffusion", "realtabformer", "tabbyflow", "tabddpm", "tabdiff", "tabpfgen", "tabsyn", "tvae",]MODEL_LABELS = { "arf": "ARF", "bayesnet": "BayesNet", "ctgan": "CTGAN", "forestdiffusion": "ForestDiffusion", "realtabformer": "RealTabFormer", "tabbyflow": "TabbyFlow", "tabddpm": "TabDDPM", "tabdiff": "TabDiff", "tabpfgen": "TabPFGen", "tabsyn": "TabSyn", "tvae": "TVAE",}MODEL_COLORS = { "realtabformer": "#332288", "tvae": "#4477AA", "forestdiffusion": "#228833", "tabddpm": "#EE7733", "tabsyn": "#66CCEE", "tabdiff": "#AA3377", "ctgan": "#EE6677", "arf": "#777777", "bayesnet": "#CCBB44", "tabpfgen": "#009988", "tabbyflow": "#882255",}PROFILE_COLOR = "#E76F51"STRENGTH_COLOR = "#2A9D8F"
def _ensure_dirs() -> None: for path in (OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR): path.mkdir(parents=True, exist_ok=True)
def _model_label(model_id: str) -> str: return MODEL_LABELS.get(model_id, model_id)
def _dataset_sort_key(dataset_id: str) -> tuple[int, int, str]: text = str(dataset_id or "").strip() if len(text) < 2 or not text[1:].isdigit(): return (99, 10**9, text) prefix_order = {"c": 0, "m": 1, "n": 2}.get(text[0].lower(), 50) return (prefix_order, int(text[1:]), text)
def _write_csv(df: pd.DataFrame, path: Path) -> None: df.to_csv(path, index=False, encoding="utf-8-sig")
def _write_include_tex(path: Path, title: str, pdf_name: str) -> None: path.write_text( "\n".join( [ r"\documentclass[border=4pt]{standalone}", r"\usepackage{graphicx}", r"\begin{document}", rf"\textbf{{{title}}}\\[0.5em]", rf"\includegraphics[width=\textwidth]{{{pdf_name}}}", r"\end{document}", "", ] ), encoding="utf-8", )
def _load_inputs() -> tuple[pd.DataFrame, pd.DataFrame]: dataset_model_df = pd.read_csv(INPUT_DATA_DIR / "dataset_model_scores.csv", encoding="utf-8-sig") model_summary_df = pd.read_csv(INPUT_DATA_DIR / "model_summary.csv", encoding="utf-8-sig") for column in [ "co_missingness_pattern_consistency", "co_missing_strength_score", "co_missing_composite_score", "profile_minus_strength", ]: if column in dataset_model_df.columns: dataset_model_df[column] = pd.to_numeric(dataset_model_df[column], errors="coerce") return dataset_model_df, model_summary_df
def _build_dataset_model_strength_df(dataset_model_df: pd.DataFrame) -> pd.DataFrame: df = dataset_model_df.copy() df = df.loc[df["co_missing_strength_score"].notna()].copy() df["strength_minus_profile"] = df["co_missing_strength_score"] - df["co_missingness_pattern_consistency"] df["dataset_sort"] = df["dataset_id"].map(_dataset_sort_key) df["model_order"] = df["model_id"].map({model_id: idx for idx, model_id in enumerate(MODEL_ORDER)}) df = df.sort_values(["dataset_sort", "model_order"]).drop(columns=["dataset_sort", "model_order"]).reset_index(drop=True) return df[ [ "dataset_id", "dataset_prefix", "model_id", "model_label", "co_missingness_pattern_consistency", "co_missing_strength_score", "co_missing_composite_score", "profile_minus_strength", "strength_minus_profile", "asset_count", "applicable_asset_count", ] ]
def _build_model_strength_summary(dataset_model_strength_df: pd.DataFrame) -> pd.DataFrame: rows: list[dict[str, Any]] = [] for model_id in MODEL_ORDER: subset = dataset_model_strength_df.loc[dataset_model_strength_df["model_id"] == model_id].copy() if subset.empty: continue rows.append( { "model_id": model_id, "model_label": _model_label(model_id), "dataset_count": int(subset["dataset_id"].nunique()), "panel_count": int(subset.shape[0]), "profile_score_mean": round(float(subset["co_missingness_pattern_consistency"].mean()), 6), "strength_score_mean": round(float(subset["co_missing_strength_score"].mean()), 6), "composite_score_mean": round(float(subset["co_missing_composite_score"].mean()), 6), "strength_minus_profile_mean": round(float(subset["strength_minus_profile"].mean()), 6), } ) return pd.DataFrame(rows)
def _plot_model_dumbbell(summary_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: fig, ax = plt.subplots(figsize=(9.4, 6.8)) y_positions = list(range(len(summary_df))) for idx, row in enumerate(summary_df.itertuples()): model_id = str(row.model_id) color = MODEL_COLORS.get(model_id, "#777777") profile = float(row.profile_score_mean) strength = float(row.strength_score_mean) ax.plot([profile, strength], [idx, idx], color=color, linewidth=2.2, alpha=0.95) ax.scatter(profile, idx, s=70, facecolors="white", edgecolors=color, linewidth=1.8, zorder=3) ax.scatter(strength, idx, s=70, facecolors=color, edgecolors=color, marker="s", linewidth=1.0, zorder=4) ax.set_yticks(y_positions) ax.set_yticklabels(summary_df["model_label"]) ax.set_xlim(0.0, 1.02) ax.set_xlabel("Mean score over applicable dataset-model panels") ax.set_title("Missingness auxiliary insight: profile vs strength") ax.grid(axis="x", alpha=0.25) ax.text(0.01, 1.01, "Hollow circle = canonical profile-only score; filled square = strength-only score", transform=ax.transAxes, fontsize=8.5) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def _plot_gap_bars(summary_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: fig, ax = plt.subplots(figsize=(10.4, 5.8)) colors = [MODEL_COLORS.get(str(model_id), "#777777") for model_id in summary_df["model_id"]] values = pd.to_numeric(summary_df["strength_minus_profile_mean"], errors="coerce").fillna(0.0) ax.bar(range(len(summary_df)), values, color=colors, edgecolor=colors) ax.axhline(0.0, color="#444444", linewidth=1.0) ax.set_xticks(range(len(summary_df))) ax.set_xticklabels(summary_df["model_label"], rotation=60, ha="right", fontsize=8) ax.set_ylabel("Strength minus profile") ax.set_title("How much relation-strength fidelity differs from canonical profile fidelity") ax.grid(axis="y", alpha=0.25) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def _plot_strength_heatmap(dataset_model_strength_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: pivot = ( dataset_model_strength_df.pivot_table( index="dataset_id", columns="model_id", values="co_missing_strength_score", aggfunc="mean", ) .reset_index() .rename_axis(None, axis=1) ) ordered_models = [model_id for model_id in MODEL_ORDER if model_id in pivot.columns] pivot["dataset_sort"] = pivot["dataset_id"].map(_dataset_sort_key) pivot = pivot.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True) matrix = pivot[ordered_models].to_numpy(dtype=float) fig_height = max(5.8, 0.35 * len(pivot) + 1.8) fig, ax = plt.subplots(figsize=(9.8, fig_height)) im = ax.imshow(matrix, vmin=0.0, vmax=1.0, aspect="auto", cmap=get_heatmap_cmap()) ax.set_xticks(range(len(ordered_models))) ax.set_xticklabels([_model_label(model_id) for model_id in ordered_models], rotation=60, ha="right", fontsize=8) ax.set_yticks(range(len(pivot))) ax.set_yticklabels(pivot["dataset_id"], fontsize=7) ax.set_title("Dataset-model heatmap of missingness relation-strength fidelity") fig.colorbar(im, ax=ax, fraction=0.035, pad=0.02) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def _draw_distribution_summary( ax: plt.Axes, center: float, values: list[float], color: str, offset: float, box_width: float = 0.18,) -> None: cleaned = [float(value) for value in values if pd.notna(value)] if not cleaned: return arr = np.asarray(cleaned, dtype=float) mean = float(arr.mean()) q1 = float(np.quantile(arr, 0.25)) q3 = float(np.quantile(arr, 0.75)) ymin = float(arr.min()) ymax = float(arr.max()) xpos = center + offset ax.vlines(xpos, ymin, ymax, color=color, linewidth=1.1, alpha=0.95, zorder=2) ax.hlines([ymin, ymax], xpos - box_width * 0.26, xpos + box_width * 0.26, color=color, linewidth=1.1, alpha=0.95, zorder=2) ax.add_patch( Rectangle( (xpos - box_width / 2, q1), box_width, max(0.0, q3 - q1), facecolor=color, edgecolor="none", alpha=0.24, zorder=1, ) ) ax.scatter([xpos], [mean], s=28, marker="s", facecolor=color, edgecolor=color, linewidth=0.8, zorder=3)
def _plot_profile_strength_distribution(dataset_model_strength_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: fig, ax = plt.subplots(figsize=(11.8, 4.8)) x_positions = list(range(len(MODEL_ORDER))) profile_offset = -0.17 strength_offset = 0.17
for idx, model_id in enumerate(MODEL_ORDER): subset = dataset_model_strength_df.loc[dataset_model_strength_df["model_id"] == model_id].copy() if subset.empty: continue _draw_distribution_summary( ax, center=float(idx), values=subset["co_missingness_pattern_consistency"].tolist(), color=PROFILE_COLOR, offset=profile_offset, ) _draw_distribution_summary( ax, center=float(idx), values=subset["co_missing_strength_score"].tolist(), color=STRENGTH_COLOR, offset=strength_offset, )
ax.set_xlim(-0.6, len(MODEL_ORDER) - 0.4) ax.set_ylim(0.0, 1.02) ax.set_xticks(x_positions) ax.set_xticklabels([_model_label(model_id) for model_id in MODEL_ORDER], rotation=35, ha="right") ax.set_ylabel("Score") ax.set_xlabel("Model") ax.set_title("Co-missingness: profile vs strength across dataset-model panels") ax.grid(axis="y", alpha=0.28, linestyle=":") ax.grid(axis="x", alpha=0.12)
legend_handles = [ Patch(facecolor=PROFILE_COLOR, edgecolor="none", alpha=0.6, label="Profile-only co-missing"), Patch(facecolor=STRENGTH_COLOR, edgecolor="none", alpha=0.6, label="Strength-only co-missing"), Line2D([0], [0], marker="s", color="#444444", markerfacecolor="#444444", markersize=5, linewidth=0, label="Mean over datasets"), Line2D([0], [0], color="#444444", linewidth=1.1, label="Min-max over datasets"), Patch(facecolor="#999999", edgecolor="none", alpha=0.24, label="IQR over datasets"), ] ax.legend(handles=legend_handles, loc="upper center", bbox_to_anchor=(0.5, 1.12), ncol=3, frameon=False, fontsize=8.5, handletextpad=0.5, columnspacing=1.4)
fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def run_strength_diagnostic() -> dict[str, Any]: _ensure_dirs() dataset_model_df, _ = _load_inputs() dataset_model_strength_df = _build_dataset_model_strength_df(dataset_model_df) model_strength_summary_df = _build_model_strength_summary(dataset_model_strength_df)
_write_csv(dataset_model_strength_df, DATA_DIR / "dataset_model_strength_scores.csv") _write_csv(model_strength_summary_df, DATA_DIR / "model_strength_summary.csv")
main_pdf = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.pdf" main_png = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.png" main_svg = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.svg" main_tex = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.tex" gap_pdf = FIG_DIR / "missing_strength_gap_bars_appendix.pdf" gap_png = FIG_DIR / "missing_strength_gap_bars_appendix.png" gap_svg = FIG_DIR / "missing_strength_gap_bars_appendix.svg" gap_tex = FIG_DIR / "missing_strength_gap_bars_appendix.tex" heat_pdf = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.pdf" heat_png = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.png" heat_svg = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.svg" heat_tex = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.tex" dist_pdf = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.pdf" dist_png = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.png" dist_svg = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.svg" dist_tex = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.tex"
_plot_model_dumbbell(model_strength_summary_df, main_pdf, main_png, main_svg) _plot_gap_bars(model_strength_summary_df, gap_pdf, gap_png, gap_svg) _plot_strength_heatmap(dataset_model_strength_df, heat_pdf, heat_png, heat_svg) _plot_profile_strength_distribution(dataset_model_strength_df, dist_pdf, dist_png, dist_svg) _write_include_tex(main_tex, "Missingness auxiliary insight: profile vs strength", main_pdf.name) _write_include_tex(gap_tex, "Strength minus profile", gap_pdf.name) _write_include_tex(heat_tex, "Dataset-model strength heatmap", heat_pdf.name) _write_include_tex(dist_tex, "Co-missing profile vs strength distribution", dist_pdf.name)
report_lines = [ "# Missingness Strength Diagnostic", "", "- Canonical missingness family score now keeps `co_missingness_pattern_consistency` as profile-only.", "- This auxiliary diagnostic isolates `co_missing_strength_score` so we can study whether models preserve the strength of structured missingness relations even when detailed profiles differ.", f"- Applicable dataset-model panels: `{dataset_model_strength_df.shape[0]}`", f"- Applicable datasets: `{dataset_model_strength_df['dataset_id'].nunique() if not dataset_model_strength_df.empty else 0}`", "", ] (OUTPUT_ROOT / "analysis_report.md").write_text("\n".join(report_lines), encoding="utf-8") (OUTPUT_ROOT / "paper_caption.txt").write_text( "Auxiliary missingness diagnostic comparing canonical profile-only co-missing fidelity against relation-strength fidelity. " "The hollow-circle endpoint shows how well each model preserves detailed conditional missingness profiles, while the filled-square endpoint shows whether the overall dependence strength of missingness on related variables is retained.", encoding="utf-8", ) (OUTPUT_ROOT / "paper_paragraphs.md").write_text( "\n".join( [ "Structured missingness can fail in two different ways: a model may distort the detailed profile of conditional missingness rates, or it may alter how strongly missingness depends on related variables.", "", "To separate these effects, we keep profile-only fidelity as the canonical co-missing subitem and report relation-strength fidelity as an auxiliary diagnostic. Differences between the two indicate whether a model preserves broad dependence amplitude more easily than fine-grained missingness profiles.", "", ] ), encoding="utf-8", )
final_files = [ DATA_DIR / "dataset_model_strength_scores.csv", DATA_DIR / "model_strength_summary.csv", OUTPUT_ROOT / "analysis_report.md", OUTPUT_ROOT / "paper_caption.txt", OUTPUT_ROOT / "paper_paragraphs.md", main_pdf, main_png, main_svg, main_tex, dist_pdf, dist_png, dist_svg, dist_tex, gap_pdf, gap_png, gap_svg, gap_tex, heat_pdf, heat_png, heat_svg, heat_tex, ] must_do = { main_pdf.name: main_pdf, main_png.name: main_png, main_svg.name: main_svg, main_tex.name: main_tex, dist_pdf.name: dist_pdf, dist_png.name: dist_png, dist_svg.name: dist_svg, dist_tex.name: dist_tex, gap_pdf.name: gap_pdf, gap_png.name: gap_png, gap_svg.name: gap_svg, gap_tex.name: gap_tex, heat_pdf.name: heat_pdf, heat_png.name: heat_png, heat_svg.name: heat_svg, heat_tex.name: heat_tex, } sync_final_outputs(FINAL_DIR, final_files, must_do) (FINAL_DIR / "README.md").write_text( render_final_readme( title="Missingness Strength Diagnostic", summary="Auxiliary paper-facing bundle isolating relation-strength fidelity from the canonical profile-only co-missing score.", primary_files=[item.name for item in final_files if item.name.endswith((".png", ".pdf", ".tex"))][:12], must_do_files=list(must_do.keys()), support_files=[ "dataset_model_strength_scores.csv", "model_strength_summary.csv", "analysis_report.md", "paper_caption.txt", "paper_paragraphs.md", ], ), encoding="utf-8", ) return { "dataset_model_strength_scores": DATA_DIR / "dataset_model_strength_scores.csv", "model_strength_summary": DATA_DIR / "model_strength_summary.csv", "main_figure_png": main_png, "heatmap_png": heat_png, }
if __name__ == "__main__": outputs = run_strength_diagnostic() for key, value in outputs.items(): print(f"{key}: {value}")12"""Strict pairwise co-missing diagnostic for missingness breakdown."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521#!/usr/bin/env python3"""Paper-facing auxiliary diagnostic for strict missing-only pairwise co-missingness."""
from __future__ import annotations
from collections import defaultdictfrom pathlib import Pathimport sysfrom typing import Any
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dfrom matplotlib.patches import Patch, Rectangleimport numpy as npimport pandas as pd
PROJECT_ROOT = Path(__file__).resolve().parents[5]if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT))
from src.eval.query_fivepart_breakdown.common_final import render_final_readme, sync_final_outputsfrom src.eval.query_fivepart_breakdown.missingness_breakdown.review_strict_pairwise import _strict_pairwise_score_for_asset
MISSINGNESS_ROOT = PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown"INPUT_DATA_DIR = MISSINGNESS_ROOT / "data"OUTPUT_ROOT = MISSINGNESS_ROOT / "strict_pairwise_diagnostic"DATA_DIR = OUTPUT_ROOT / "data"FIG_DIR = OUTPUT_ROOT / "figures"FINAL_DIR = OUTPUT_ROOT / "final"
MODEL_ORDER = [ "arf", "bayesnet", "ctgan", "forestdiffusion", "realtabformer", "tabbyflow", "tabddpm", "tabdiff", "tabpfgen", "tabsyn", "tvae",]MODEL_LABELS = { "arf": "ARF", "bayesnet": "BayesNet", "ctgan": "CTGAN", "forestdiffusion": "ForestDiffusion", "realtabformer": "RealTabFormer", "tabbyflow": "TabbyFlow", "tabddpm": "TabDDPM", "tabdiff": "TabDiff", "tabpfgen": "TabPFGen", "tabsyn": "TabSyn", "tvae": "TVAE",}MODEL_COLORS = { "realtabformer": "#332288", "tvae": "#4477AA", "forestdiffusion": "#228833", "tabddpm": "#EE7733", "tabsyn": "#66CCEE", "tabdiff": "#AA3377", "ctgan": "#EE6677", "arf": "#777777", "bayesnet": "#CCBB44", "tabpfgen": "#009988", "tabbyflow": "#882255",}EXCLUDED_MODELS = {"cdtd", "codi", "goggle"}MODEL_ALIASES = {"rtf": "realtabformer"}SERVER_PRIORITY = {"rtx_5090": 2, "rtx_pro_6000": 1}ROOT_PRIORITY = {"SynOutput-5090": 2, "SynOutput": 1}BROAD_PROFILE_COLOR = "#E76F51"STRICT_PAIRWISE_COLOR = "#6D597A"
def _ensure_dirs() -> None: for path in (OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR): path.mkdir(parents=True, exist_ok=True)
def _normalize_model(model_id: Any) -> str: key = str(model_id or "").strip().lower() return MODEL_ALIASES.get(key, key)
def _model_label(model_id: str) -> str: return MODEL_LABELS.get(model_id, model_id)
def _dataset_sort_key(dataset_id: str) -> tuple[int, int, str]: text = str(dataset_id or "").strip() if len(text) < 2 or not text[1:].isdigit(): return (99, 10**9, text) prefix_order = {"c": 0, "m": 1, "n": 2}.get(text[0].lower(), 50) return (prefix_order, int(text[1:]), text)
def _write_csv(df: pd.DataFrame, path: Path) -> None: df.to_csv(path, index=False, encoding="utf-8-sig")
def _write_include_tex(path: Path, title: str, pdf_name: str) -> None: path.write_text( "\n".join( [ r"\documentclass[border=4pt]{standalone}", r"\usepackage{graphicx}", r"\begin{document}", rf"\textbf{{{title}}}\\[0.5em]", rf"\includegraphics[width=\textwidth]{{{pdf_name}}}", r"\end{document}", "", ] ), encoding="utf-8", )
def _asset_sort_key(row: dict[str, Any]) -> tuple[int, int, str, str]: server = str(row.get("server_type") or "").strip().lower() root_name = str(row.get("root_name") or "").strip() run_id = str(row.get("run_id") or "").strip() asset_key = str(row.get("asset_key") or "").strip() return ( SERVER_PRIORITY.get(server, 0), ROOT_PRIORITY.get(root_name, 0), run_id, asset_key, )
def _load_primary_asset_rows() -> pd.DataFrame: asset_df = pd.read_csv(INPUT_DATA_DIR / "direct_asset_scores.csv", encoding="utf-8-sig") asset_df["model_id"] = asset_df["model_id"].map(_normalize_model) asset_df = asset_df.loc[ (asset_df["status"] == "ok") & (~asset_df["model_id"].isin(EXCLUDED_MODELS)) & asset_df["model_id"].isin(MODEL_ORDER) ].copy()
grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list) for row in asset_df.to_dict(orient="records"): grouped[(str(row["dataset_id"]), str(row["model_id"]))].append(row)
chosen_rows: list[dict[str, Any]] = [] for key, items in grouped.items(): ranked = sorted(items, key=_asset_sort_key, reverse=True) chosen_rows.append(ranked[0]) return pd.DataFrame(chosen_rows)
def _build_strict_panel_df(asset_df: pd.DataFrame) -> pd.DataFrame: rows: list[dict[str, Any]] = [] for row in asset_df.itertuples(index=False): strict = _strict_pairwise_score_for_asset(str(row.dataset_id), Path(str(row.synthetic_csv_path))) rows.append( { "dataset_id": str(row.dataset_id), "dataset_prefix": str(row.dataset_id)[0].lower(), "model_id": str(row.model_id), "model_label": _model_label(str(row.model_id)), "current_broad_profile_score": float(row.co_missingness_pattern_consistency), "current_strength_score": float(getattr(row, "co_missing_strength_score", float("nan"))), "strict_status": strict["strict_status"], "strict_pairwise_score": strict["strict_pairwise_score"], "strict_pair_count": int(strict["strict_pair_count"]), "active_missing_target_count": int(strict["active_missing_target_count"]), } ) df = pd.DataFrame(rows) df["delta_strict_minus_broad"] = pd.to_numeric(df["strict_pairwise_score"], errors="coerce") - pd.to_numeric(df["current_broad_profile_score"], errors="coerce") df["dataset_sort"] = df["dataset_id"].map(_dataset_sort_key) df["model_order"] = df["model_id"].map({model_id: idx for idx, model_id in enumerate(MODEL_ORDER)}) df = df.sort_values(["dataset_sort", "model_order"]).drop(columns=["dataset_sort", "model_order"]).reset_index(drop=True) return df
def _build_model_summary(panel_df: pd.DataFrame) -> pd.DataFrame: overlap_df = panel_df.loc[panel_df["strict_pairwise_score"].notna()].copy() rows: list[dict[str, Any]] = [] for model_id in MODEL_ORDER: subset = overlap_df.loc[overlap_df["model_id"] == model_id].copy() if subset.empty: continue rows.append( { "model_id": model_id, "model_label": _model_label(model_id), "dataset_count_overlap": int(subset["dataset_id"].nunique()), "panel_count_overlap": int(subset.shape[0]), "broad_profile_score_mean": round(float(subset["current_broad_profile_score"].mean()), 6), "strict_pairwise_score_mean": round(float(subset["strict_pairwise_score"].mean()), 6), "delta_strict_minus_broad_mean": round(float(subset["delta_strict_minus_broad"].mean()), 6), } ) return pd.DataFrame(rows)
def _build_coverage_summary(panel_df: pd.DataFrame) -> pd.DataFrame: rows: list[dict[str, Any]] = [] for dataset_id, group in panel_df.groupby("dataset_id", sort=False): rows.append( { "dataset_id": dataset_id, "model_panel_count": int(group.shape[0]), "strict_applicable_panel_count": int(group["strict_pairwise_score"].notna().sum()), "active_missing_target_count": int(pd.to_numeric(group["active_missing_target_count"], errors="coerce").fillna(0).max()), "strict_pair_count": int(pd.to_numeric(group["strict_pair_count"], errors="coerce").fillna(0).max()), } ) coverage_df = pd.DataFrame(rows) if coverage_df.empty: return coverage_df coverage_df["dataset_sort"] = coverage_df["dataset_id"].map(_dataset_sort_key) return coverage_df.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True)
def _plot_model_dumbbell(summary_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: fig, ax = plt.subplots(figsize=(9.5, 6.8)) y_positions = list(range(len(summary_df))) for idx, row in enumerate(summary_df.itertuples()): model_id = str(row.model_id) color = MODEL_COLORS.get(model_id, "#777777") broad = float(row.broad_profile_score_mean) strict = float(row.strict_pairwise_score_mean) ax.plot([broad, strict], [idx, idx], color=color, linewidth=2.2, alpha=0.95) ax.scatter(broad, idx, s=70, facecolors="white", edgecolors=color, linewidth=1.8, zorder=3) ax.scatter(strict, idx, s=70, facecolors=color, edgecolors=color, marker="D", linewidth=1.0, zorder=4) ax.set_yticks(y_positions) ax.set_yticklabels(summary_df["model_label"]) ax.set_xlim(0.0, 1.02) ax.set_xlabel("Mean score over strict-overlap panels") ax.set_title("Broad structured missingness vs strict missing-only pairwise co-missingness") ax.grid(axis="x", alpha=0.25) ax.text(0.01, 1.01, "Hollow circle = broad profile-only score; filled diamond = strict missing-only pairwise score", transform=ax.transAxes, fontsize=8.5) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def _plot_panel_scatter(panel_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: overlap_df = panel_df.loc[panel_df["strict_pairwise_score"].notna()].copy() fig, ax = plt.subplots(figsize=(7.8, 6.8)) ax.scatter( overlap_df["current_broad_profile_score"], overlap_df["strict_pairwise_score"], s=34, color="#4C78A8", alpha=0.78, edgecolors="none", ) ax.plot([0.0, 1.0], [0.0, 1.0], linestyle="--", color="#666666", linewidth=1.1) ax.set_xlim(0.0, 1.02) ax.set_ylim(0.0, 1.02) ax.set_xlabel("Broad profile-only co-missing score") ax.set_ylabel("Strict missing-only pairwise score") ax.set_title( "Dataset-model overlap panels\n" f"n={overlap_df.shape[0]}, datasets={overlap_df['dataset_id'].nunique() if not overlap_df.empty else 0}" ) ax.grid(alpha=0.25) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def _plot_coverage_bars(coverage_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: x = range(len(coverage_df)) width = 0.38 fig, ax = plt.subplots(figsize=(11.8, 5.8)) ax.bar([item - width / 2 for item in x], coverage_df["model_panel_count"], width=width, color="#BDBDBD", edgecolor="#777777", label="All available model panels") ax.bar([item + width / 2 for item in x], coverage_df["strict_applicable_panel_count"], width=width, color="#4C78A8", edgecolor="#2C5A88", label="Strict-pairwise applicable panels") ax.set_xticks(list(x)) ax.set_xticklabels(coverage_df["dataset_id"], rotation=60, ha="right", fontsize=8) ax.set_ylabel("Panel count") ax.set_title("Coverage shrinkage when only missing-only pairs are retained") ax.grid(axis="y", alpha=0.25) ax.legend(frameon=False, fontsize=8) fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def _draw_distribution_summary( ax: plt.Axes, center: float, values: list[float], color: str, offset: float, box_width: float = 0.18,) -> None: cleaned = [float(value) for value in values if pd.notna(value)] if not cleaned: return arr = np.asarray(cleaned, dtype=float) mean = float(arr.mean()) q1 = float(np.quantile(arr, 0.25)) q3 = float(np.quantile(arr, 0.75)) ymin = float(arr.min()) ymax = float(arr.max()) xpos = center + offset ax.vlines(xpos, ymin, ymax, color=color, linewidth=1.1, alpha=0.95, zorder=2) ax.hlines([ymin, ymax], xpos - box_width * 0.26, xpos + box_width * 0.26, color=color, linewidth=1.1, alpha=0.95, zorder=2) ax.add_patch( Rectangle( (xpos - box_width / 2, q1), box_width, max(0.0, q3 - q1), facecolor=color, edgecolor="none", alpha=0.24, zorder=1, ) ) ax.scatter([xpos], [mean], s=28, marker="s", facecolor=color, edgecolor=color, linewidth=0.8, zorder=3)
def _plot_broad_vs_strict_distribution(panel_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None: overlap_df = panel_df.loc[panel_df["strict_pairwise_score"].notna()].copy() fig, ax = plt.subplots(figsize=(11.8, 4.8)) x_positions = list(range(len(MODEL_ORDER))) broad_offset = -0.17 strict_offset = 0.17
for idx, model_id in enumerate(MODEL_ORDER): subset = overlap_df.loc[overlap_df["model_id"] == model_id].copy() if subset.empty: continue _draw_distribution_summary( ax, center=float(idx), values=subset["current_broad_profile_score"].tolist(), color=BROAD_PROFILE_COLOR, offset=broad_offset, ) _draw_distribution_summary( ax, center=float(idx), values=subset["strict_pairwise_score"].tolist(), color=STRICT_PAIRWISE_COLOR, offset=strict_offset, )
ax.set_xlim(-0.6, len(MODEL_ORDER) - 0.4) ax.set_ylim(0.0, 1.02) ax.set_xticks(x_positions) ax.set_xticklabels([_model_label(model_id) for model_id in MODEL_ORDER], rotation=35, ha="right") ax.set_ylabel("Score") ax.set_xlabel("Model") ax.set_title("Profile-only co-missing: broad vs missing-only pairwise") ax.grid(axis="y", alpha=0.28, linestyle=":") ax.grid(axis="x", alpha=0.12)
legend_handles = [ Patch(facecolor=BROAD_PROFILE_COLOR, edgecolor="none", alpha=0.6, label="Broad co-missing profile"), Patch(facecolor=STRICT_PAIRWISE_COLOR, edgecolor="none", alpha=0.6, label="Missing-only pairwise profile"), Line2D([0], [0], marker="s", color="#444444", markerfacecolor="#444444", markersize=5, linewidth=0, label="Mean over overlap datasets"), Line2D([0], [0], color="#444444", linewidth=1.1, label="Min-max over overlap datasets"), Patch(facecolor="#999999", edgecolor="none", alpha=0.24, label="IQR over overlap datasets"), ] ax.legend(handles=legend_handles, loc="upper center", bbox_to_anchor=(0.5, 1.12), ncol=3, frameon=False, fontsize=8.5, handletextpad=0.5, columnspacing=1.4)
fig.tight_layout() fig.savefig(pdf_path, bbox_inches="tight") fig.savefig(png_path, dpi=220, bbox_inches="tight") fig.savefig(svg_path, bbox_inches="tight") plt.close(fig)
def run_strict_pairwise_diagnostic() -> dict[str, Any]: _ensure_dirs() asset_df = _load_primary_asset_rows() panel_df = _build_strict_panel_df(asset_df) model_df = _build_model_summary(panel_df) coverage_df = _build_coverage_summary(panel_df)
_write_csv(panel_df, DATA_DIR / "strict_pairwise_panel_scores.csv") _write_csv(model_df, DATA_DIR / "strict_pairwise_model_summary.csv") _write_csv(coverage_df, DATA_DIR / "strict_pairwise_coverage_summary.csv")
main_pdf = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.pdf" main_png = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.png" main_svg = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.svg" main_tex = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.tex" scatter_pdf = FIG_DIR / "strict_pairwise_panel_scatter_appendix.pdf" scatter_png = FIG_DIR / "strict_pairwise_panel_scatter_appendix.png" scatter_svg = FIG_DIR / "strict_pairwise_panel_scatter_appendix.svg" scatter_tex = FIG_DIR / "strict_pairwise_panel_scatter_appendix.tex" coverage_pdf = FIG_DIR / "strict_pairwise_coverage_bars_appendix.pdf" coverage_png = FIG_DIR / "strict_pairwise_coverage_bars_appendix.png" coverage_svg = FIG_DIR / "strict_pairwise_coverage_bars_appendix.svg" coverage_tex = FIG_DIR / "strict_pairwise_coverage_bars_appendix.tex" dist_pdf = FIG_DIR / "strict_pairwise_profile_distribution_main.pdf" dist_png = FIG_DIR / "strict_pairwise_profile_distribution_main.png" dist_svg = FIG_DIR / "strict_pairwise_profile_distribution_main.svg" dist_tex = FIG_DIR / "strict_pairwise_profile_distribution_main.tex"
_plot_model_dumbbell(model_df, main_pdf, main_png, main_svg) _plot_panel_scatter(panel_df, scatter_pdf, scatter_png, scatter_svg) _plot_coverage_bars(coverage_df, coverage_pdf, coverage_png, coverage_svg) _plot_broad_vs_strict_distribution(panel_df, dist_pdf, dist_png, dist_svg) _write_include_tex(main_tex, "Strict pairwise vs broad co-missingness", main_pdf.name) _write_include_tex(scatter_tex, "Strict pairwise overlap scatter", scatter_pdf.name) _write_include_tex(coverage_tex, "Strict pairwise coverage shrinkage", coverage_pdf.name) _write_include_tex(dist_tex, "Profile-only broad vs strict pairwise distribution", dist_pdf.name)
status_counts = panel_df["strict_status"].value_counts(dropna=False).to_dict() report_lines = [ "# Strict Pairwise Co-Missing Diagnostic", "", "- Canonical missingness family score keeps the broader profile-only structured-missingness view.", "- This auxiliary diagnostic restricts the second axis to missing-only column pairs.", f"- Primary asset panels reviewed: `{panel_df.shape[0]}`", f"- Strict-overlap panels: `{int(panel_df['strict_pairwise_score'].notna().sum())}`", f"- Strict-overlap datasets: `{int(panel_df.loc[panel_df['strict_pairwise_score'].notna(), 'dataset_id'].nunique())}`", "", "## Status counts", "", ] report_lines.extend([f"- `{key}`: `{value}`" for key, value in status_counts.items()]) (OUTPUT_ROOT / "analysis_report.md").write_text("\n".join(report_lines) + "\n", encoding="utf-8") (OUTPUT_ROOT / "paper_caption.txt").write_text( "Auxiliary missingness diagnostic comparing the broad profile-only co-missing score against a stricter version that only retains pairs of columns that both exhibit meaningful native missingness. " "Coverage bars show that the stricter definition is more selective because datasets with only one active missing target column become inapplicable.", encoding="utf-8", ) (OUTPUT_ROOT / "paper_paragraphs.md").write_text( "\n".join( [ "The canonical missingness family intentionally keeps a broad structured-missingness view, where the missingness of one target column can depend on the states of any other usable column.", "", "As a sensitivity analysis, we also evaluate a strict pairwise variant that only retains pairs of columns that both carry meaningful native missingness. Differences between the two reveal whether a model preserves general conditional missingness structure more easily than direct co-missing behavior among missing columns themselves.", "", ] ), encoding="utf-8", )
final_files = [ DATA_DIR / "strict_pairwise_panel_scores.csv", DATA_DIR / "strict_pairwise_model_summary.csv", DATA_DIR / "strict_pairwise_coverage_summary.csv", OUTPUT_ROOT / "analysis_report.md", OUTPUT_ROOT / "paper_caption.txt", OUTPUT_ROOT / "paper_paragraphs.md", main_pdf, main_png, main_svg, main_tex, dist_pdf, dist_png, dist_svg, dist_tex, scatter_pdf, scatter_png, scatter_svg, scatter_tex, coverage_pdf, coverage_png, coverage_svg, coverage_tex, ] must_do = { main_pdf.name: main_pdf, main_png.name: main_png, main_svg.name: main_svg, main_tex.name: main_tex, dist_pdf.name: dist_pdf, dist_png.name: dist_png, dist_svg.name: dist_svg, dist_tex.name: dist_tex, scatter_pdf.name: scatter_pdf, scatter_png.name: scatter_png, scatter_svg.name: scatter_svg, scatter_tex.name: scatter_tex, coverage_pdf.name: coverage_pdf, coverage_png.name: coverage_png, coverage_svg.name: coverage_svg, coverage_tex.name: coverage_tex, } sync_final_outputs(FINAL_DIR, final_files, must_do) (FINAL_DIR / "README.md").write_text( render_final_readme( title="Strict Pairwise Co-Missing Diagnostic", summary="Auxiliary paper-facing bundle that restricts co-missingness to missing-only column pairs and reports the resulting coverage shrinkage.", primary_files=[item.name for item in final_files if item.name.endswith((".png", ".pdf", ".tex"))][:12], must_do_files=list(must_do.keys()), support_files=[ "strict_pairwise_panel_scores.csv", "strict_pairwise_model_summary.csv", "strict_pairwise_coverage_summary.csv", "analysis_report.md", "paper_caption.txt", "paper_paragraphs.md", ], ), encoding="utf-8", ) return { "strict_pairwise_panel_scores": DATA_DIR / "strict_pairwise_panel_scores.csv", "strict_pairwise_model_summary": DATA_DIR / "strict_pairwise_model_summary.csv", "main_figure_png": main_png, "coverage_png": coverage_png, }
if __name__ == "__main__": outputs = run_strict_pairwise_diagnostic() for key, value in outputs.items(): print(f"{key}: {value}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663from __future__ import annotations
import csvimport mathfrom collections import defaultdictfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclassfrom os import cpu_countfrom pathlib import Pathfrom statistics import meanfrom typing import Any
import numpy as npimport pandas as pd
from src.eval.common import ( SyntheticAsset, discover_synthetic_assets, list_dataset_ids, load_field_type_hints, normalize_missing, resolve_real_split_path, write_csv,)
STATE_OTHER = "__OTHER__"STATE_MISSING = "__Z_MISSING__"CANONICAL_MARGINAL_AGGREGATION = "direct_mean_over_missing_targets"CANONICAL_COMISSING_AGGREGATION = "direct_mean_over_edge_profiles"COMPARISON_COMISSING_AGGREGATION = "weighted_by_real_relation_strength"COMPOSITE_COMISSING_AGGREGATION = "direct_mean_over_edge_composites_0p7profile_0p3strength"EPS = 1e-12TOP_CATEGORIES = 8NUMERIC_BINS = 5MIN_MISSING_COUNT_ABS = 5MIN_MISSING_RATE = 0.005
@dataclass(frozen=True)class ColumnStateEncoder: column: str kind: str states: tuple[str, ...] top_categories: tuple[str, ...] = () bin_edges: tuple[float, ...] = ()
@dataclass(frozen=True)class EdgeDefinition: missing_target: str related_column: str encoder: ColumnStateEncoder real_missing_rate: float supported_state_indices: tuple[int, ...] real_state_probabilities: tuple[float, ...] real_conditional_missing_rates: tuple[float, ...] real_relation_strength: float
@dataclass(frozen=True)class TargetDefinition: column: str missing_count: int missing_rate: float info_weight: float edges: tuple[EdgeDefinition, ...]
@dataclass(frozen=True)class DatasetContext: dataset_id: str row_count: int columns: tuple[str, ...] column_kinds: dict[str, str] encoders: dict[str, ColumnStateEncoder] missing_targets: tuple[TargetDefinition, ...]
def _clip01(value: float) -> float: return max(0.0, min(1.0, float(value)))
def _binary_entropy(p: float) -> float: p = min(max(float(p), 0.0), 1.0) if p <= 0.0 or p >= 1.0: return 0.0 return -(p * math.log2(p) + (1.0 - p) * math.log2(1.0 - p))
def _load_real_df(dataset_id: str) -> pd.DataFrame: real_path = resolve_real_split_path(dataset_id, split="train") if not real_path.exists(): raise FileNotFoundError(f"Train split missing for {dataset_id}: {real_path}") try: return pd.read_csv(real_path, dtype=str, keep_default_na=False) except pd.errors.ParserError: sample = real_path.read_text(encoding="utf-8", errors="replace")[:8192] try: dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|") delimiter = dialect.delimiter except csv.Error: delimiter = "," return pd.read_csv(real_path, dtype=str, keep_default_na=False, sep=delimiter)
def _load_syn_df(synthetic_csv_path: Path, expected_columns: list[str]) -> pd.DataFrame: syn_df = pd.read_csv(synthetic_csv_path, dtype=str, keep_default_na=False) for column in expected_columns: if column not in syn_df.columns: syn_df[column] = "" syn_df = syn_df[expected_columns] return syn_df
def _infer_column_kind(series: pd.Series, hint: str) -> str: token = (hint or "").lower() if any(word in token for word in ["numeric", "integer", "float", "double", "decimal", "continuous"]): return "numeric" if any(word in token for word in ["categorical", "string", "text", "boolean", "ordinal"]): return "categorical" non_missing = series[~series.map(normalize_missing)] if non_missing.empty: return "categorical" parsed = pd.to_numeric(non_missing, errors="coerce") ratio = float(parsed.notna().mean()) if len(parsed) else 0.0 return "numeric" if ratio >= 0.95 else "categorical"
def _build_categorical_encoder(column: str, real_series: pd.Series) -> ColumnStateEncoder: non_missing = real_series[~real_series.map(normalize_missing)].astype(str) counts = non_missing.value_counts(dropna=False) top_categories = tuple(str(item) for item in counts.head(TOP_CATEGORIES).index.tolist()) states = list(top_categories) if len(counts) > len(top_categories): states.append(STATE_OTHER) if bool(real_series.map(normalize_missing).any()): states.append(STATE_MISSING) return ColumnStateEncoder( column=column, kind="categorical", states=tuple(states), top_categories=top_categories, )
def _build_numeric_encoder(column: str, real_series: pd.Series) -> ColumnStateEncoder | None: parsed = pd.to_numeric(real_series[~real_series.map(normalize_missing)], errors="coerce").dropna() if len(parsed) < 8 or int(parsed.nunique()) < 4: return None quantiles = np.linspace(0.0, 1.0, NUMERIC_BINS + 1) edges = np.quantile(parsed.to_numpy(dtype=float), quantiles) edges = np.unique(edges.astype(float)) if len(edges) < 3: return None inner_edges = tuple(float(value) for value in edges[1:-1].tolist()) bin_count = len(inner_edges) + 1 states = [f"bin_{idx}" for idx in range(bin_count)] if bool(real_series.map(normalize_missing).any()): states.append(STATE_MISSING) return ColumnStateEncoder( column=column, kind="numeric", states=tuple(states), bin_edges=inner_edges, )
def _build_encoder(column: str, real_series: pd.Series, hint: str) -> ColumnStateEncoder: inferred_kind = _infer_column_kind(real_series, hint) if inferred_kind == "numeric": numeric_encoder = _build_numeric_encoder(column, real_series) if numeric_encoder is not None: return numeric_encoder return _build_categorical_encoder(column, real_series)
def _encode_series(series: pd.Series, encoder: ColumnStateEncoder) -> pd.Series: normalized = series.fillna("").astype(str) if encoder.kind == "categorical": top = set(encoder.top_categories)
def _map_value(value: str) -> str: if normalize_missing(value): return STATE_MISSING if STATE_MISSING in encoder.states else STATE_OTHER if value in top: return value return STATE_OTHER if STATE_OTHER in encoder.states else encoder.states[0]
return normalized.map(_map_value)
parsed = pd.to_numeric(normalized.where(~normalized.map(normalize_missing), np.nan), errors="coerce") bins = [-np.inf, *encoder.bin_edges, np.inf] labels = [state for state in encoder.states if state != STATE_MISSING] encoded = pd.cut(parsed, bins=bins, labels=labels, include_lowest=True).astype("object") if STATE_MISSING in encoder.states: encoded = encoded.where(~normalized.map(normalize_missing), STATE_MISSING) encoded = encoded.fillna(labels[0] if labels else STATE_MISSING) return encoded.astype(str)
def _encode_codes(series: pd.Series, encoder: ColumnStateEncoder) -> np.ndarray: encoded = _encode_series(series, encoder) return pd.Categorical(encoded, categories=list(encoder.states)).codes.astype(np.int16, copy=False)
def _state_support_counts(encoded_codes: np.ndarray, state_count: int) -> np.ndarray: valid = encoded_codes >= 0 if not bool(np.any(valid)): return np.zeros(state_count, dtype=np.int64) return np.bincount(encoded_codes[valid], minlength=state_count)
def _conditional_rate_stats(missing_indicator: np.ndarray, encoded_codes: np.ndarray, state_count: int) -> tuple[np.ndarray, np.ndarray]: valid = encoded_codes >= 0 if not bool(np.any(valid)): return np.zeros(state_count, dtype=np.int64), np.zeros(state_count, dtype=float) support_counts = np.bincount(encoded_codes[valid], minlength=state_count) missing_sums = np.bincount(encoded_codes[valid], weights=missing_indicator[valid], minlength=state_count) rates = np.zeros(state_count, dtype=float) nonzero = support_counts > 0 rates[nonzero] = missing_sums[nonzero] / support_counts[nonzero] return support_counts, rates
def _relation_strength(global_missing_rate: float, state_probabilities: np.ndarray, conditional_rates: np.ndarray) -> float: denom = max(global_missing_rate * (1.0 - global_missing_rate), EPS) weighted_var = 0.0 for weight, rate in zip(state_probabilities, conditional_rates): weighted_var += float(weight) * ((float(rate) - global_missing_rate) ** 2) return _clip01(weighted_var / denom)
def build_dataset_context(dataset_id: str) -> DatasetContext: real_df = _load_real_df(dataset_id) row_count = len(real_df) columns = [str(col) for col in real_df.columns] missing_counts = { col: int(real_df[col].map(normalize_missing).sum()) for col in columns } target_defs: list[TargetDefinition] = [] min_missing_count = max(MIN_MISSING_COUNT_ABS, int(math.ceil(row_count * MIN_MISSING_RATE)))
active_target_columns = [ col for col in columns if missing_counts[col] >= min_missing_count and 0 < missing_counts[col] < row_count ] if not active_target_columns: return DatasetContext( dataset_id=dataset_id, row_count=row_count, columns=tuple(columns), column_kinds={}, encoders={}, missing_targets=(), )
hints = load_field_type_hints(dataset_id) column_kinds = {col: _infer_column_kind(real_df[col], hints.get(col, "")) for col in columns} encoders = {col: _build_encoder(col, real_df[col], hints.get(col, "")) for col in columns} real_encoded_cache = { col: _encode_codes(real_df[col], encoders[col]) for col in columns }
for target_col in active_target_columns: missing_indicator = real_df[target_col].map(normalize_missing).to_numpy(dtype=float) missing_count = missing_counts[target_col] missing_rate = float(missing_count / max(1, row_count))
info_weight = _binary_entropy(missing_rate) * math.log1p(missing_count) edge_defs: list[EdgeDefinition] = [] for related_col in columns: if related_col == target_col: continue encoder = encoders[related_col] encoded_real = real_encoded_cache[related_col] support_counts = _state_support_counts(encoded_real, len(encoder.states)) supported_state_indices = tuple(int(idx) for idx in np.where(support_counts > 0)[0].tolist()) if len(supported_state_indices) < 2: continue state_probabilities = support_counts.astype(float) / max(1, row_count) _, conditional_rates = _conditional_rate_stats(missing_indicator, encoded_real, len(encoder.states)) strength = _relation_strength(missing_rate, state_probabilities, conditional_rates) edge_defs.append( EdgeDefinition( missing_target=target_col, related_column=related_col, encoder=encoder, real_missing_rate=missing_rate, supported_state_indices=supported_state_indices, real_state_probabilities=tuple(float(v) for v in state_probabilities.tolist()), real_conditional_missing_rates=tuple(float(v) for v in conditional_rates.tolist()), real_relation_strength=strength, ) )
if edge_defs: target_defs.append( TargetDefinition( column=target_col, missing_count=missing_count, missing_rate=missing_rate, info_weight=float(info_weight), edges=tuple(edge_defs), ) )
return DatasetContext( dataset_id=dataset_id, row_count=row_count, columns=tuple(columns), column_kinds=column_kinds, encoders=encoders, missing_targets=tuple(target_defs), )
def _score_edge( target: TargetDefinition, edge: EdgeDefinition, missing_indicator: np.ndarray, encoded_syn: np.ndarray,) -> tuple[float, float, float]: global_missing_rate = float(np.mean(missing_indicator)) support_counts, synthetic_rates = _conditional_rate_stats(missing_indicator, encoded_syn, len(edge.encoder.states))
profile_distance = 0.0 synthetic_rates_fallback = synthetic_rates.copy() zero_support = support_counts <= 0 synthetic_rates_fallback[zero_support] = global_missing_rate for idx in edge.supported_state_indices: real_weight = edge.real_state_probabilities[idx] syn_rate = synthetic_rates_fallback[idx] real_rate = edge.real_conditional_missing_rates[idx] profile_distance += float(real_weight) * abs(float(real_rate) - float(syn_rate)) profile_score = _clip01(1.0 - profile_distance)
denom = max(global_missing_rate * (1.0 - global_missing_rate), EPS) weighted_var = 0.0 for idx in edge.supported_state_indices: weighted_var += float(edge.real_state_probabilities[idx]) * ((float(synthetic_rates_fallback[idx]) - global_missing_rate) ** 2) synthetic_strength = _clip01(weighted_var / denom) strength_score = _clip01(1.0 - abs(edge.real_relation_strength - synthetic_strength))
edge_score = _clip01((0.7 * profile_score) + (0.3 * strength_score)) return edge_score, profile_score, strength_score
def score_synthetic_df(context: DatasetContext, syn_df: pd.DataFrame) -> tuple[dict[str, Any], list[dict[str, Any]]]: if not context.missing_targets: return ( { "status": "not_applicable_no_missing_targets", "marginal_aggregation_scheme": CANONICAL_MARGINAL_AGGREGATION, "canonical_aggregation_scheme": CANONICAL_COMISSING_AGGREGATION, "comparison_aggregation_scheme": COMPARISON_COMISSING_AGGREGATION, "marginal_missing_rate_consistency": None, "co_missingness_pattern_consistency": None, "missingness_structure_score": None, "comparison_missingness_structure_score": None, "canonical_score": None, "direct_mean_score": None, "weighted_score": None, "missing_target_count": 0, "edge_count": 0, }, [], )
target_rows: list[dict[str, Any]] = [] marginal_target_scores: list[float] = [] all_edge_scores: list[float] = [] all_profile_scores: list[float] = [] all_strength_scores: list[float] = [] weighted_target_scores: list[tuple[float, float]] = [] encoded_cache = { column: _encode_codes(syn_df[column], encoder) for column, encoder in context.encoders.items() } missing_indicator_cache = { target.column: syn_df[target.column].map(normalize_missing).to_numpy(dtype=float) for target in context.missing_targets }
for target in context.missing_targets: missing_indicator = missing_indicator_cache[target.column] synthetic_missing_rate = float(np.mean(missing_indicator)) marginal_target_score = _clip01(1.0 - abs(float(target.missing_rate) - synthetic_missing_rate)) edge_scores: list[float] = [] edge_weights: list[float] = [] mean_profile_scores: list[float] = [] mean_strength_scores: list[float] = [] informative_edge_count = 0
for edge in target.edges: edge_score, profile_score, strength_score = _score_edge( target, edge, missing_indicator, encoded_cache[edge.related_column], ) edge_scores.append(edge_score) edge_weights.append(edge.real_relation_strength) mean_profile_scores.append(profile_score) mean_strength_scores.append(strength_score) all_edge_scores.append(edge_score) all_profile_scores.append(profile_score) all_strength_scores.append(strength_score) if edge.real_relation_strength > 0: informative_edge_count += 1
if not edge_scores: continue
marginal_target_scores.append(marginal_target_score) direct_target_score = float(mean(mean_profile_scores)) strength_target_score = float(mean(mean_strength_scores)) composite_target_score = float(mean(edge_scores)) total_weight = float(sum(edge_weights)) if total_weight > 0: weighted_target_score = float(sum(score * weight for score, weight in zip(edge_scores, edge_weights)) / total_weight) else: weighted_target_score = composite_target_score
weighted_target_scores.append((weighted_target_score, target.info_weight)) target_rows.append( { "missing_target": target.column, "missing_count_real": target.missing_count, "missing_rate_real": round(target.missing_rate, 6), "missing_rate_synthetic": round(synthetic_missing_rate, 6), "marginal_target_score": round(marginal_target_score, 6), "target_info_weight": round(target.info_weight, 6), "edge_count": len(edge_scores), "informative_edge_count": informative_edge_count, "co_missing_direct_target_score": round(direct_target_score, 6), "co_missing_profile_target_score": round(direct_target_score, 6), "co_missing_strength_target_score": round(strength_target_score, 6), "co_missing_composite_target_score": round(composite_target_score, 6), "co_missing_weighted_target_score": round(weighted_target_score, 6), "missingness_structure_target_score": round(float(mean([marginal_target_score, direct_target_score])), 6), "mean_profile_score": round(float(mean(mean_profile_scores)), 6), "mean_strength_score": round(float(mean(mean_strength_scores)), 6), } )
if not all_profile_scores or not target_rows or not marginal_target_scores: return ( { "status": "not_applicable_no_edges", "marginal_aggregation_scheme": CANONICAL_MARGINAL_AGGREGATION, "canonical_aggregation_scheme": CANONICAL_COMISSING_AGGREGATION, "composite_aggregation_scheme": COMPOSITE_COMISSING_AGGREGATION, "comparison_aggregation_scheme": COMPARISON_COMISSING_AGGREGATION, "marginal_missing_rate_consistency": None, "co_missingness_pattern_consistency": None, "co_missing_strength_score": None, "co_missing_composite_score": None, "missingness_structure_score": None, "comparison_missingness_structure_score": None, "canonical_score": None, "direct_mean_score": None, "weighted_score": None, "missing_target_count": len(context.missing_targets), "edge_count": 0, }, target_rows, )
marginal_missing_rate_consistency = float(mean(marginal_target_scores)) direct_mean_score = float(mean(all_profile_scores)) strength_score = float(mean(all_strength_scores)) composite_score = float(mean(all_edge_scores)) weight_sum = float(sum(weight for _, weight in weighted_target_scores)) if weight_sum > 0: weighted_score = float(sum(score * weight for score, weight in weighted_target_scores) / weight_sum) else: weighted_score = float(mean(score for score, _ in weighted_target_scores)) missingness_structure_score = float(mean([marginal_missing_rate_consistency, direct_mean_score])) comparison_missingness_structure_score = float(mean([marginal_missing_rate_consistency, weighted_score]))
return ( { "status": "ok", "marginal_aggregation_scheme": CANONICAL_MARGINAL_AGGREGATION, "canonical_aggregation_scheme": CANONICAL_COMISSING_AGGREGATION, "composite_aggregation_scheme": COMPOSITE_COMISSING_AGGREGATION, "comparison_aggregation_scheme": COMPARISON_COMISSING_AGGREGATION, "marginal_missing_rate_consistency": round(marginal_missing_rate_consistency, 6), "co_missingness_pattern_consistency": round(direct_mean_score, 6), "co_missing_strength_score": round(strength_score, 6), "co_missing_composite_score": round(composite_score, 6), "missingness_structure_score": round(missingness_structure_score, 6), "comparison_missingness_structure_score": round(comparison_missingness_structure_score, 6), "canonical_score": round(direct_mean_score, 6), "direct_mean_score": round(direct_mean_score, 6), "weighted_score": round(weighted_score, 6), "missing_target_count": len(target_rows), "edge_count": len(all_edge_scores), "score_gap_weighted_minus_direct": round(weighted_score - direct_mean_score, 6), }, target_rows, )
def _dataset_context_rows(context: DatasetContext) -> dict[str, Any]: return { "dataset_id": context.dataset_id, "row_count": context.row_count, "column_count": len(context.columns), "missing_target_count": len(context.missing_targets), "edge_count": sum(len(target.edges) for target in context.missing_targets), "missing_targets": ",".join(target.column for target in context.missing_targets), }
def _evaluate_dataset_assets(dataset_id: str, dataset_assets: list[SyntheticAsset]) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: context = build_dataset_context(dataset_id) context_row = _dataset_context_rows(context) asset_rows: list[dict[str, Any]] = [] target_rows: list[dict[str, Any]] = []
for asset in dataset_assets: syn_df = _load_syn_df(Path(asset.synthetic_csv_path), list(context.columns)) score_row, per_target_rows = score_synthetic_df(context, syn_df) asset_row = { **asset.to_dict(), "dataset_id": dataset_id, **score_row, } asset_rows.append(asset_row) for target_row in per_target_rows: target_rows.append( { **asset.to_dict(), "dataset_id": dataset_id, "status": score_row.get("status"), **target_row, } )
return context_row, asset_rows, target_rows
def _mean_or_none(values: list[float | None]) -> float | None: cleaned = [float(value) for value in values if value is not None] if not cleaned: return None return float(mean(cleaned))
def _summarize_asset_rows(asset_rows: list[dict[str, Any]], group_keys: tuple[str, ...]) -> list[dict[str, Any]]: grouped: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list) for row in asset_rows: grouped[tuple(str(row.get(key) or "") for key in group_keys)].append(row)
summary_rows: list[dict[str, Any]] = [] for key, rows in sorted(grouped.items()): payload = {field: value for field, value in zip(group_keys, key)} payload["asset_count"] = len(rows) payload["applicable_asset_count"] = sum(1 for row in rows if row.get("status") == "ok") payload["marginal_aggregation_scheme"] = CANONICAL_MARGINAL_AGGREGATION payload["canonical_aggregation_scheme"] = CANONICAL_COMISSING_AGGREGATION payload["composite_aggregation_scheme"] = COMPOSITE_COMISSING_AGGREGATION payload["comparison_aggregation_scheme"] = COMPARISON_COMISSING_AGGREGATION payload["marginal_missing_rate_consistency"] = _mean_or_none( [row.get("marginal_missing_rate_consistency") for row in rows if row.get("status") == "ok"] ) payload["co_missingness_pattern_consistency"] = _mean_or_none( [row.get("co_missingness_pattern_consistency") for row in rows if row.get("status") == "ok"] ) payload["co_missing_strength_score"] = _mean_or_none( [row.get("co_missing_strength_score") for row in rows if row.get("status") == "ok"] ) payload["co_missing_composite_score"] = _mean_or_none( [row.get("co_missing_composite_score") for row in rows if row.get("status") == "ok"] ) payload["missingness_structure_score"] = _mean_or_none( [row.get("missingness_structure_score") for row in rows if row.get("status") == "ok"] ) payload["comparison_missingness_structure_score"] = _mean_or_none( [row.get("comparison_missingness_structure_score") for row in rows if row.get("status") == "ok"] ) payload["canonical_score"] = _mean_or_none([row.get("canonical_score") for row in rows if row.get("status") == "ok"]) payload["direct_mean_score"] = _mean_or_none([row.get("direct_mean_score") for row in rows if row.get("status") == "ok"]) payload["weighted_score"] = _mean_or_none([row.get("weighted_score") for row in rows if row.get("status") == "ok"]) payload["score_gap_weighted_minus_direct"] = _mean_or_none( [row.get("score_gap_weighted_minus_direct") for row in rows if row.get("status") == "ok"] ) for field in ( "marginal_missing_rate_consistency", "co_missingness_pattern_consistency", "co_missing_strength_score", "co_missing_composite_score", "missingness_structure_score", "comparison_missingness_structure_score", "canonical_score", "direct_mean_score", "weighted_score", "score_gap_weighted_minus_direct", ): if payload[field] is not None: payload[field] = round(float(payload[field]), 6) summary_rows.append(payload) return summary_rows
def evaluate_all_synthetic_assets(output_dir: Path, max_workers: int | None = None) -> dict[str, Path]: output_dir.mkdir(parents=True, exist_ok=True) dataset_ids = list_dataset_ids() assets = discover_synthetic_assets(datasets=dataset_ids, latest_only=True) dataset_asset_map: dict[str, list[SyntheticAsset]] = defaultdict(list) for asset in assets: dataset_asset_map[asset.dataset_id].append(asset)
dataset_context_rows: list[dict[str, Any]] = [] asset_rows: list[dict[str, Any]] = [] target_rows: list[dict[str, Any]] = []
worker_count = max_workers if max_workers is not None else min(8, max(1, (cpu_count() or 4) - 1)) futures = {} with ThreadPoolExecutor(max_workers=max(1, worker_count)) as executor: for dataset_id in dataset_ids: futures[executor.submit(_evaluate_dataset_assets, dataset_id, dataset_asset_map.get(dataset_id, []))] = dataset_id for index, future in enumerate(as_completed(futures), start=1): dataset_id = futures[future] context_row, dataset_asset_rows, dataset_target_rows = future.result() dataset_context_rows.append(context_row) asset_rows.extend(dataset_asset_rows) target_rows.extend(dataset_target_rows) print( f"[co-missing] dataset={index}/{len(dataset_ids)}" f" id={dataset_id}" f" assets={len(dataset_asset_rows)}" f" missing_targets={context_row.get('missing_target_count')}", flush=True, )
model_dataset_rows = _summarize_asset_rows(asset_rows, ("dataset_id", "model_id")) model_overall_rows = _summarize_asset_rows(asset_rows, ("model_id",))
dataset_context_path = output_dir / "co_missing_dataset_context.csv" asset_scores_path = output_dir / "co_missing_asset_scores.csv" target_scores_path = output_dir / "co_missing_target_scores.csv" model_dataset_path = output_dir / "co_missing_model_dataset_summary.csv" model_overall_path = output_dir / "co_missing_model_overall_summary.csv"
write_csv(dataset_context_path, dataset_context_rows) write_csv(asset_scores_path, asset_rows) write_csv(target_scores_path, target_rows) write_csv(model_dataset_path, model_dataset_rows) write_csv(model_overall_path, model_overall_rows)
return { "dataset_context": dataset_context_path, "asset_scores": asset_scores_path, "target_scores": target_scores_path, "model_dataset_summary": model_dataset_path, "model_overall_summary": model_overall_path, }evaluation/query_family/code_support/README.mdAdded+14
evaluation/query_family/code_support/src/eval/analytics_contract.pyAdded+341
evaluation/query_family/code_support/src/eval/common.pyAdded+1629
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/__init__.pyAdded+5
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/runner.pyAdded
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_final.pyAdded+107
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_heatmap_palette.pyAdded+60
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_grouped_bars.pyAdded+261
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_heatmap.pyAdded+155
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/__init__.pyAdded+1
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/__init__.pyAdded+1
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/runner.pyAdded+563
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/regime_diagnostic_runner.pyAdded+334
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/review_strict_pairwise.pyAdded+519
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/runner.pyAdded+1171
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/__init__.pyAdded+2
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/runner.pyAdded+463
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/__init__.pyAdded+2
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/runner.pyAdded+521
evaluation/query_family/code_support/tests/comissing_condition_eval.pyAdded+663