TabQueryBench commited on
Commit
1d227d7
·
verified ·
1 Parent(s): b027c6b

Upload missingness and cardinality evaluation code support

Browse files
Files changed (20) hide show
  1. evaluation/query_family/code_support/README.md +14 -0
  2. evaluation/query_family/code_support/src/eval/analytics_contract.py +341 -0
  3. evaluation/query_family/code_support/src/eval/common.py +1629 -0
  4. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/__init__.py +5 -0
  5. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/runner.py +0 -0
  6. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_final.py +107 -0
  7. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_heatmap_palette.py +60 -0
  8. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_grouped_bars.py +261 -0
  9. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_heatmap.py +155 -0
  10. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/__init__.py +1 -0
  11. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/__init__.py +1 -0
  12. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/runner.py +563 -0
  13. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/regime_diagnostic_runner.py +334 -0
  14. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/review_strict_pairwise.py +519 -0
  15. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/runner.py +1171 -0
  16. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/__init__.py +2 -0
  17. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/runner.py +463 -0
  18. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/__init__.py +2 -0
  19. evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/runner.py +521 -0
  20. evaluation/query_family/code_support/tests/comissing_condition_eval.py +663 -0
evaluation/query_family/code_support/README.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Query Family Evaluation Code Support
2
+
3
+ This support bundle mirrors the server-side code needed to reproduce
4
+ the missingness and cardinality query-family evaluations.
5
+
6
+ Included components:
7
+ - `src/eval/common.py`
8
+ - `src/eval/analytics_contract.py`
9
+ - `src/eval/query_fivepart_breakdown/common_*` helpers
10
+ - `src/eval/query_fivepart_breakdown/missingness_breakdown/*`
11
+ - `src/eval/query_fivepart_breakdown/cardinality/*`
12
+ - `tests/comissing_condition_eval.py`
13
+
14
+ Source of truth: `/data/jialinzhang/TabQueryBench/code_snapshot`
evaluation/query_family/code_support/src/eval/analytics_contract.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical analytics family/sub-item contract helpers.
2
+
3
+ This module centralizes how query-level evidence is mapped onto the
4
+ frozen analytics sub-item contract defined in
5
+ `doc/analytics_family_subitem_contract_v1.md`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from statistics import mean
12
+ from typing import Any, Mapping
13
+
14
+ ANALYTICS_CONTRACT_VERSION = "analytics_family_subitem_contract_v1"
15
+
16
+ CANONICAL_ANALYTICS_SUBITEMS: dict[str, list[str]] = {
17
+ "subgroup_structure": [
18
+ "internal_profile_stability",
19
+ "subgroup_size_stability",
20
+ ],
21
+ "conditional_dependency_structure": [
22
+ "dependency_strength_similarity",
23
+ "direction_consistency",
24
+ "slice_level_consistency",
25
+ ],
26
+ "tail_rarity_structure": [
27
+ "tail_set_consistency",
28
+ "tail_mass_similarity",
29
+ "tail_concentration_consistency",
30
+ ],
31
+ "missingness_structure": [
32
+ "marginal_missing_rate_consistency",
33
+ "co_missingness_pattern_consistency",
34
+ ],
35
+ }
36
+
37
+ _FACET_TO_SUBITEM: dict[str, dict[str, str]] = {
38
+ "subgroup_structure": {
39
+ "subgroup_distribution_shift": "internal_profile_stability",
40
+ "subgroup_rank_order": "internal_profile_stability",
41
+ "subgroup_conditional_contrast": "internal_profile_stability",
42
+ },
43
+ "conditional_dependency_structure": {
44
+ "pairwise_conditional_dependency": "dependency_strength_similarity",
45
+ "conditional_rate_shift": "direction_consistency",
46
+ "conditional_interaction_hotspots": "slice_level_consistency",
47
+ },
48
+ "tail_rarity_structure": {
49
+ "rare_target_concentration": "tail_concentration_consistency",
50
+ "low_support_extremes": "tail_set_consistency",
51
+ "tail_ranked_signal": "tail_concentration_consistency",
52
+ },
53
+ "missingness_structure": {
54
+ "missing_indicator_distribution": "marginal_missing_rate_consistency",
55
+ "missing_target_interaction": "co_missingness_pattern_consistency",
56
+ "missing_rate_by_subgroup": "co_missingness_pattern_consistency",
57
+ },
58
+ }
59
+
60
+ _ROLE_ALIASES = {
61
+ "group_count": "count_distribution",
62
+ "filtered_group_count_topk": "filtered_stable_view",
63
+ "group_condition_rate": "within_group_proportion",
64
+ "group_ratio_two_conditions": "within_group_proportion",
65
+ "group_sum": "collapsed_target_view",
66
+ "group_avg_numeric": "collapsed_target_view",
67
+ "support_guarded_group_avg": "filtered_stable_view",
68
+ "binned_numeric_group_avg": "collapsed_target_view",
69
+ "two_dimensional_group_avg": "collapsed_target_view",
70
+ }
71
+
72
+ _ROLE_TO_SUBITEM: dict[str, dict[str, str]] = {
73
+ "subgroup_structure": {
74
+ "count_distribution": "subgroup_size_stability",
75
+ "filtered_stable_view": "subgroup_size_stability",
76
+ "within_group_proportion": "internal_profile_stability",
77
+ "collapsed_target_view": "internal_profile_stability",
78
+ "ranked_signal_view": "internal_profile_stability",
79
+ "focused_target_view": "internal_profile_stability",
80
+ "contrastive_conditional_view": "internal_profile_stability",
81
+ "rare_extreme_view": "internal_profile_stability",
82
+ },
83
+ "conditional_dependency_structure": {
84
+ "within_group_proportion": "dependency_strength_similarity",
85
+ "collapsed_target_view": "dependency_strength_similarity",
86
+ "count_distribution": "slice_level_consistency",
87
+ "filtered_stable_view": "slice_level_consistency",
88
+ "ranked_signal_view": "direction_consistency",
89
+ "focused_target_view": "direction_consistency",
90
+ "contrastive_conditional_view": "direction_consistency",
91
+ "rare_extreme_view": "direction_consistency",
92
+ },
93
+ "tail_rarity_structure": {
94
+ "rare_extreme_view": "tail_set_consistency",
95
+ "count_distribution": "tail_mass_similarity",
96
+ "filtered_stable_view": "tail_mass_similarity",
97
+ "within_group_proportion": "tail_concentration_consistency",
98
+ "focused_target_view": "tail_concentration_consistency",
99
+ "contrastive_conditional_view": "tail_concentration_consistency",
100
+ "ranked_signal_view": "tail_concentration_consistency",
101
+ "collapsed_target_view": "tail_concentration_consistency",
102
+ },
103
+ "missingness_structure": {
104
+ "missing_indicator_view": "marginal_missing_rate_consistency",
105
+ "missing_ranked_view": "marginal_missing_rate_consistency",
106
+ "filtered_stable_view": "marginal_missing_rate_consistency",
107
+ "count_distribution": "marginal_missing_rate_consistency",
108
+ "missing_target_interaction": "co_missingness_pattern_consistency",
109
+ "missing_rate_by_subgroup": "co_missingness_pattern_consistency",
110
+ "focused_target_view": "co_missingness_pattern_consistency",
111
+ "contrastive_conditional_view": "co_missingness_pattern_consistency",
112
+ "rare_extreme_view": "co_missingness_pattern_consistency",
113
+ "within_group_proportion": "co_missingness_pattern_consistency",
114
+ },
115
+ }
116
+
117
+ _RATE_RE = re.compile(r"(rate|ratio|proportion|share|pct|percent|bucket_rate|global_rate|within_group_rate|focus_rate)", re.IGNORECASE)
118
+ _COUNT_RE = re.compile(r"(count|support|total|freq|frequency)", re.IGNORECASE)
119
+ _RANK_RE = re.compile(r"(rank|ranked|order|top|highest|lowest|strongest|weakest|focus)", re.IGNORECASE)
120
+ _TAIL_RE = re.compile(r"(tail|rare|extreme|low[\s\-_]?support|outlier)", re.IGNORECASE)
121
+ _CONCENTRATION_RE = re.compile(r"(concentrat|dominant|heavy|share|focus)", re.IGNORECASE)
122
+ _MISSING_RE = re.compile(r"(missing|null|not_missing)", re.IGNORECASE)
123
+ _PAIRWISE_RE = re.compile(r"(pairwise|co[\s\-_]?missing|joint|interaction|subgroup)", re.IGNORECASE)
124
+
125
+
126
+ def canonical_subitem_score_field(family_id: str, subitem_id: str) -> str:
127
+ return f"{family_id}__{subitem_id}_score"
128
+
129
+
130
+ def all_canonical_subitem_score_fields() -> list[str]:
131
+ fields: list[str] = []
132
+ for family_id, subitems in CANONICAL_ANALYTICS_SUBITEMS.items():
133
+ for subitem_id in subitems:
134
+ fields.append(canonical_subitem_score_field(family_id, subitem_id))
135
+ return fields
136
+
137
+
138
+ def normalize_variant_semantic_role(value: Any) -> str:
139
+ text = str(value or "").strip().lower()
140
+ if not text:
141
+ return ""
142
+ return _ROLE_ALIASES.get(text, text)
143
+
144
+
145
+ def _normalize_family(value: Any) -> str:
146
+ return str(value or "").strip().lower()
147
+
148
+
149
+ def _normalize_facet(value: Any) -> str:
150
+ return str(value or "").strip().lower()
151
+
152
+
153
+ def _text_blob(query_row: Mapping[str, Any]) -> str:
154
+ parts = [
155
+ query_row.get("question"),
156
+ query_row.get("research_question"),
157
+ query_row.get("expected_output_shape"),
158
+ query_row.get("template_name"),
159
+ query_row.get("template_id"),
160
+ query_row.get("variant_semantic_role"),
161
+ query_row.get("intended_facet_id"),
162
+ query_row.get("intended_structure_claim"),
163
+ query_row.get("sql"),
164
+ ]
165
+ return " ".join(str(item or "") for item in parts).strip().lower()
166
+
167
+
168
+ def infer_canonical_subitem(query_row: Mapping[str, Any]) -> dict[str, Any]:
169
+ family_id = _normalize_family(query_row.get("family_id") or query_row.get("family"))
170
+ if family_id not in CANONICAL_ANALYTICS_SUBITEMS:
171
+ return {
172
+ "family_id": family_id,
173
+ "canonical_subitem_id": "",
174
+ "contract_version": ANALYTICS_CONTRACT_VERSION,
175
+ "normalized_variant_semantic_role": normalize_variant_semantic_role(query_row.get("variant_semantic_role")),
176
+ "normalized_intended_facet_id": _normalize_facet(query_row.get("intended_facet_id")),
177
+ "subitem_inference_source": "non_analytics_family",
178
+ "subitem_inference_note": "family_not_in_canonical_contract",
179
+ }
180
+
181
+ normalized_role = normalize_variant_semantic_role(query_row.get("variant_semantic_role"))
182
+ normalized_facet = _normalize_facet(query_row.get("intended_facet_id"))
183
+ text_blob = _text_blob(query_row)
184
+ sql_text = str(query_row.get("sql") or "").lower()
185
+ explicit_subitem_id = str(query_row.get("canonical_subitem_id") or "").strip()
186
+
187
+ if explicit_subitem_id and explicit_subitem_id in CANONICAL_ANALYTICS_SUBITEMS.get(family_id, []):
188
+ return {
189
+ "family_id": family_id,
190
+ "canonical_subitem_id": explicit_subitem_id,
191
+ "contract_version": ANALYTICS_CONTRACT_VERSION,
192
+ "normalized_variant_semantic_role": normalized_role,
193
+ "normalized_intended_facet_id": normalized_facet,
194
+ "subitem_inference_source": "explicit",
195
+ "subitem_inference_note": "canonical_subitem_id",
196
+ }
197
+
198
+ if normalized_facet in _FACET_TO_SUBITEM.get(family_id, {}):
199
+ return {
200
+ "family_id": family_id,
201
+ "canonical_subitem_id": _FACET_TO_SUBITEM[family_id][normalized_facet],
202
+ "contract_version": ANALYTICS_CONTRACT_VERSION,
203
+ "normalized_variant_semantic_role": normalized_role,
204
+ "normalized_intended_facet_id": normalized_facet,
205
+ "subitem_inference_source": "facet",
206
+ "subitem_inference_note": normalized_facet,
207
+ }
208
+
209
+ if normalized_role in _ROLE_TO_SUBITEM.get(family_id, {}):
210
+ return {
211
+ "family_id": family_id,
212
+ "canonical_subitem_id": _ROLE_TO_SUBITEM[family_id][normalized_role],
213
+ "contract_version": ANALYTICS_CONTRACT_VERSION,
214
+ "normalized_variant_semantic_role": normalized_role,
215
+ "normalized_intended_facet_id": normalized_facet,
216
+ "subitem_inference_source": "role",
217
+ "subitem_inference_note": normalized_role,
218
+ }
219
+
220
+ if family_id == "subgroup_structure":
221
+ if _RATE_RE.search(text_blob) or _RANK_RE.search(text_blob):
222
+ subitem_id = "internal_profile_stability"
223
+ note = "heuristic_rate_or_rank"
224
+ elif _COUNT_RE.search(text_blob) or "count(" in sql_text:
225
+ subitem_id = "subgroup_size_stability"
226
+ note = "heuristic_count_or_support"
227
+ else:
228
+ subitem_id = "internal_profile_stability"
229
+ note = "heuristic_family_default"
230
+ elif family_id == "conditional_dependency_structure":
231
+ if "contrast" in text_blob or _RANK_RE.search(text_blob):
232
+ subitem_id = "direction_consistency"
233
+ note = "heuristic_directional_signal"
234
+ elif _COUNT_RE.search(text_blob) and not _RATE_RE.search(text_blob):
235
+ subitem_id = "slice_level_consistency"
236
+ note = "heuristic_slice_support"
237
+ else:
238
+ subitem_id = "dependency_strength_similarity"
239
+ note = "heuristic_dependency_strength"
240
+ elif family_id == "tail_rarity_structure":
241
+ if _TAIL_RE.search(text_blob) and ("support asc" in sql_text or "order by support asc" in sql_text):
242
+ subitem_id = "tail_set_consistency"
243
+ note = "heuristic_tail_membership"
244
+ elif _CONCENTRATION_RE.search(text_blob) and (_RANK_RE.search(text_blob) or "focus_rate" in sql_text):
245
+ subitem_id = "tail_concentration_consistency"
246
+ note = "heuristic_tail_concentration"
247
+ elif (_RATE_RE.search(text_blob) or "focus_rate" in sql_text) and ("group by" in sql_text or "partition by" in sql_text):
248
+ subitem_id = "tail_concentration_consistency"
249
+ note = "heuristic_tail_concentration_from_rate_view"
250
+ else:
251
+ subitem_id = "tail_mass_similarity"
252
+ note = "heuristic_tail_mass"
253
+ else: # missingness_structure
254
+ if _PAIRWISE_RE.search(text_blob) or "missing_rate" in sql_text or "group by" in sql_text and _MISSING_RE.search(text_blob):
255
+ subitem_id = "co_missingness_pattern_consistency"
256
+ note = "heuristic_missing_structure"
257
+ else:
258
+ subitem_id = "marginal_missing_rate_consistency"
259
+ note = "heuristic_missing_marginal"
260
+
261
+ return {
262
+ "family_id": family_id,
263
+ "canonical_subitem_id": subitem_id,
264
+ "contract_version": ANALYTICS_CONTRACT_VERSION,
265
+ "normalized_variant_semantic_role": normalized_role,
266
+ "normalized_intended_facet_id": normalized_facet,
267
+ "subitem_inference_source": "heuristic",
268
+ "subitem_inference_note": note,
269
+ }
270
+
271
+
272
+ def annotate_query_row_with_contract(query_row: dict[str, Any]) -> dict[str, Any]:
273
+ annotated = dict(query_row)
274
+ annotated.update(infer_canonical_subitem(query_row))
275
+ return annotated
276
+
277
+
278
+ def build_subitem_and_family_rows(
279
+ *,
280
+ query_rows: list[dict[str, Any]],
281
+ context_fields: Mapping[str, Any],
282
+ score_field: str = "query_score",
283
+ missingness_applicable: bool = True,
284
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
285
+ subitem_rows: list[dict[str, Any]] = []
286
+ family_rows: list[dict[str, Any]] = []
287
+
288
+ by_family_subitem: dict[tuple[str, str], list[dict[str, Any]]] = {}
289
+ family_query_counts: dict[str, int] = {}
290
+ for row in query_rows:
291
+ family_id = _normalize_family(row.get("family_id"))
292
+ subitem_id = str(row.get("canonical_subitem_id") or "")
293
+ if family_id not in CANONICAL_ANALYTICS_SUBITEMS or not subitem_id:
294
+ continue
295
+ if family_id == "missingness_structure" and not missingness_applicable:
296
+ continue
297
+ by_family_subitem.setdefault((family_id, subitem_id), []).append(row)
298
+ family_query_counts[family_id] = family_query_counts.get(family_id, 0) + 1
299
+
300
+ for family_id, subitems in CANONICAL_ANALYTICS_SUBITEMS.items():
301
+ active_scores: list[float] = []
302
+ for order_index, subitem_id in enumerate(subitems, start=1):
303
+ applicable = not (family_id == "missingness_structure" and not missingness_applicable)
304
+ rows = by_family_subitem.get((family_id, subitem_id), [])
305
+ score_values = [
306
+ float(item.get(score_field))
307
+ for item in rows
308
+ if item.get(score_field) is not None
309
+ ]
310
+ score = mean(score_values) if score_values else None
311
+ if applicable and score is not None:
312
+ active_scores.append(float(score))
313
+ inference_sources = sorted({str(item.get("subitem_inference_source") or "") for item in rows if item.get("subitem_inference_source")})
314
+ subitem_rows.append(
315
+ {
316
+ **context_fields,
317
+ "family_id": family_id,
318
+ "subitem_id": subitem_id,
319
+ "subitem_order": order_index,
320
+ "subitem_score": round(float(score), 6) if score is not None else None,
321
+ "query_count": len(rows),
322
+ "subitem_applicable": applicable,
323
+ "subitem_inference_sources": ",".join(inference_sources),
324
+ "contract_version": ANALYTICS_CONTRACT_VERSION,
325
+ }
326
+ )
327
+
328
+ family_score = mean(active_scores) if active_scores else None
329
+ family_rows.append(
330
+ {
331
+ **context_fields,
332
+ "family_id": family_id,
333
+ "family_score": round(float(family_score), 6) if family_score is not None else None,
334
+ "query_count": family_query_counts.get(family_id, 0),
335
+ "active_subitem_count": len(active_scores),
336
+ "subitem_count": len(subitems),
337
+ "contract_version": ANALYTICS_CONTRACT_VERSION,
338
+ }
339
+ )
340
+
341
+ return subitem_rows, family_rows
evaluation/query_family/code_support/src/eval/common.py ADDED
@@ -0,0 +1,1629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared utilities for synthetic-data evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import hashlib
7
+ import json
8
+ import math
9
+ import os
10
+ import re
11
+ import sqlite3
12
+ import time
13
+ from collections import Counter, defaultdict
14
+ from dataclasses import asdict, dataclass
15
+ from datetime import datetime, timezone
16
+ from pathlib import Path
17
+ from typing import Any, Iterable
18
+
19
+ from src.eval.subitem_workload_v2.paths import (
20
+ SUPPORTED_LINE_VERSIONS,
21
+ normalize_line_version,
22
+ registry_dir,
23
+ run_manifest_dir,
24
+ runs_root,
25
+ )
26
+ from src.eval.subitem_workload_v2.registry import load_registry_rows
27
+
28
+ PROJECT_ROOT = Path(__file__).resolve().parents[2]
29
+
30
+
31
+ def _env_path(name: str, default: Path) -> Path:
32
+ value = os.environ.get(name, "").strip()
33
+ return Path(value).expanduser() if value else default
34
+
35
+
36
+ DATA_ROOT = _env_path("EVAL_REAL_DATA_ROOT", PROJECT_ROOT / "data")
37
+ LOGS_ROOT = _env_path("EVAL_LOGS_ROOT", PROJECT_ROOT / "logs" / "runs")
38
+ OUTPUT_ROOT = _env_path("EVAL_OUTPUT_ROOT", PROJECT_ROOT / "Evaluation")
39
+ SQL_RESULT_ROLE_ANNOTATION_ROOT = DATA_ROOT / "sql_result_role_annotations_v1" / "datasets"
40
+
41
+ PROVENANCE_CONTRACT_VERSION = "evaluation_source_provenance_v1"
42
+ SQL_SOURCE_VERSION_ENV_VAR = "EVAL_SQL_SOURCE_VERSION"
43
+ SQL_SOURCE_VERSION_V1 = "v1"
44
+ SQL_SOURCE_VERSION_V2 = "v2"
45
+ SQL_SOURCE_VERSION_V3 = "v3"
46
+ SQL_SOURCE_VERSION_V4 = "v4"
47
+ CURRENT_SQL_SOURCE_VERSIONS = tuple(SUPPORTED_LINE_VERSIONS)
48
+ SQL_SOURCE_VERSION_CHOICES = (
49
+ SQL_SOURCE_VERSION_V1,
50
+ *CURRENT_SQL_SOURCE_VERSIONS,
51
+ )
52
+ DEFAULT_SQL_SOURCE_VERSION = SQL_SOURCE_VERSION_V2
53
+
54
+ _SQL_SOURCE_LABELS = {
55
+ SQL_SOURCE_VERSION_V1: "v1_legacy",
56
+ SQL_SOURCE_VERSION_V2: "v2_current",
57
+ SQL_SOURCE_VERSION_V3: "v3_current",
58
+ SQL_SOURCE_VERSION_V4: "v4_current",
59
+ }
60
+ _SQL_SOURCE_DESCRIPTIONS = {
61
+ SQL_SOURCE_VERSION_V1: "legacy grounded SQL runs under logs/runs/",
62
+ SQL_SOURCE_VERSION_V2: "current registry-backed workload SQL under logs/subitem_workload_v2/",
63
+ SQL_SOURCE_VERSION_V3: "current registry-backed workload SQL under logs/subitem_workload_v3/",
64
+ SQL_SOURCE_VERSION_V4: "current registry-backed workload SQL under logs/subitem_workload_v4/",
65
+ }
66
+ _SQL_SOURCE_ALIASES = {
67
+ "v1": SQL_SOURCE_VERSION_V1,
68
+ "legacy": SQL_SOURCE_VERSION_V1,
69
+ "v1_legacy": SQL_SOURCE_VERSION_V1,
70
+ "logs/runs": SQL_SOURCE_VERSION_V1,
71
+ "logs\\runs": SQL_SOURCE_VERSION_V1,
72
+ "v2": SQL_SOURCE_VERSION_V2,
73
+ "query_registry_v2": SQL_SOURCE_VERSION_V2,
74
+ "current": SQL_SOURCE_VERSION_V2,
75
+ "v2_current": SQL_SOURCE_VERSION_V2,
76
+ "subitem_workload_v2": SQL_SOURCE_VERSION_V2,
77
+ "logs/subitem_workload_v2": SQL_SOURCE_VERSION_V2,
78
+ "logs\\subitem_workload_v2": SQL_SOURCE_VERSION_V2,
79
+ "v3": SQL_SOURCE_VERSION_V3,
80
+ "v3_current": SQL_SOURCE_VERSION_V3,
81
+ "query_registry_v3": SQL_SOURCE_VERSION_V3,
82
+ "subitem_workload_v3": SQL_SOURCE_VERSION_V3,
83
+ "logs/subitem_workload_v3": SQL_SOURCE_VERSION_V3,
84
+ "logs\\subitem_workload_v3": SQL_SOURCE_VERSION_V3,
85
+ "v4": SQL_SOURCE_VERSION_V4,
86
+ "v4_current": SQL_SOURCE_VERSION_V4,
87
+ "query_registry_v4": SQL_SOURCE_VERSION_V4,
88
+ "subitem_workload_v4": SQL_SOURCE_VERSION_V4,
89
+ "logs/subitem_workload_v4": SQL_SOURCE_VERSION_V4,
90
+ "logs\\subitem_workload_v4": SQL_SOURCE_VERSION_V4,
91
+ }
92
+
93
+ ROOT_CONFIGS = {
94
+ "SynOutput": {
95
+ "path": _env_path("EVAL_SYNOUTPUT_ROOT", PROJECT_ROOT / "SynOutput"),
96
+ "server_type": "rtx_pro_6000",
97
+ "gpu_hour_ratio": 1.0,
98
+ },
99
+ "SynOutput-5090": {
100
+ "path": _env_path("EVAL_SYNOUTPUT_5090_ROOT", PROJECT_ROOT / "SynOutput-5090"),
101
+ "server_type": "rtx_5090",
102
+ "gpu_hour_ratio": 1.0,
103
+ },
104
+ "Benchmark-trainonly-v1": {
105
+ "path": _env_path("EVAL_BENCHMARK_TRAINONLY_ROOT", PROJECT_ROOT / "remote-output-Benchmark-trainonly-v1"),
106
+ "server_type": "trainonly_serial",
107
+ "gpu_hour_ratio": 1.0,
108
+ },
109
+ "Hyperparameter-trainonly-v1": {
110
+ "path": _env_path(
111
+ "EVAL_HYPERPARAMETER_TRAINONLY_ROOT",
112
+ PROJECT_ROOT / "hyperparameter" / "output-Benchmark-trainonly-v1",
113
+ ),
114
+ "server_type": "hyperparameter_trainonly",
115
+ "gpu_hour_ratio": 1.0,
116
+ },
117
+ "TabQueryBench-SynDataSuccess-main": {
118
+ "path": _env_path(
119
+ "EVAL_TABQUERYBENCH_MAIN_ROOT",
120
+ Path("/data/jialinzhang/TabQueryBench/SynDataSuccess/main"),
121
+ ),
122
+ "server_type": "server_authoritative_main",
123
+ "gpu_hour_ratio": 1.0,
124
+ },
125
+ }
126
+
127
+ USD_PER_GPU_HOUR = 1.0
128
+ MAX_FALLBACK_GPU_SECONDS = 12 * 3600
129
+ MISSING_TEXT = {"", "null", "none", "nan", "na", "n/a", "<null>"}
130
+ TIMESTAMP_RE = re.compile(r"(\d{8}_\d{6})")
131
+ RUNTIME_RESULT_RE = re.compile(r"(?P<prefix>.+?)__runtime_result\.json$", re.IGNORECASE)
132
+ TRAIN_TIME_RE = re.compile(
133
+ r"(?:totoal|total)\s+training\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)",
134
+ re.IGNORECASE,
135
+ )
136
+ SAMPLE_TIME_RE = re.compile(
137
+ r"(?:totoal|total)\s+sampling\s+time\s*=\s*([0-9]+(?:\.[0-9]+)?)",
138
+ re.IGNORECASE,
139
+ )
140
+ GENERIC_SECONDS_RE = re.compile(
141
+ r"(?:elapsed|duration|runtime|wall\s*time|completed\s+in|finished\s+in)\D+([0-9]+(?:\.[0-9]+)?)\s*(?:seconds|secs|s)?",
142
+ re.IGNORECASE,
143
+ )
144
+ SUBITEM_RUNS_PATH_RE = re.compile(
145
+ r"/logs/subitem_workload_(v[234])/runs/(?P<suffix>.+)$",
146
+ re.IGNORECASE,
147
+ )
148
+
149
+
150
+ @dataclass
151
+ class SyntheticAsset:
152
+ dataset_id: str
153
+ model_id: str
154
+ server_type: str
155
+ root_name: str
156
+ root_path: str
157
+ asset_dir: str
158
+ run_id: str
159
+ synthetic_csv_path: str
160
+ metadata_paths: list[str]
161
+ log_paths: list[str]
162
+ discovered_via: str
163
+ timestamp_utc: str | None
164
+ synthetic_source_mtime_utc: str | None
165
+ synthetic_source_size_bytes: int | None
166
+ gpu_seconds_raw: float
167
+ gpu_hours_equivalent: float
168
+ gpu_hours_source: str
169
+ cost_usd: float
170
+
171
+ @property
172
+ def asset_key(self) -> str:
173
+ return f"{self.dataset_id}__{self.server_type}__{self.model_id}__{self.run_id}"
174
+
175
+ @property
176
+ def model_server_key(self) -> str:
177
+ return f"{self.model_id}__{self.server_type}"
178
+
179
+ def to_dict(self) -> dict[str, Any]:
180
+ row = asdict(self)
181
+ row["asset_key"] = self.asset_key
182
+ row["model_server_key"] = self.model_server_key
183
+ row["provenance_contract_version"] = PROVENANCE_CONTRACT_VERSION
184
+ row["synthetic_source_path"] = row["synthetic_csv_path"]
185
+ row["synthetic_source_root_name"] = row["root_name"]
186
+ row["synthetic_source_root_path"] = row["root_path"]
187
+ row["synthetic_source_asset_dir"] = row["asset_dir"]
188
+ row["synthetic_source_run_id"] = row["run_id"]
189
+ row["synthetic_source_discovered_via"] = row["discovered_via"]
190
+ return row
191
+
192
+
193
+ def now_run_tag() -> str:
194
+ return datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
195
+
196
+
197
+ def read_json(path: Path, default: Any = None) -> Any:
198
+ if not path.exists():
199
+ return default
200
+ try:
201
+ return json.loads(path.read_text(encoding="utf-8"))
202
+ except Exception:
203
+ return default
204
+
205
+
206
+ def write_json(path: Path, payload: Any) -> None:
207
+ path.parent.mkdir(parents=True, exist_ok=True)
208
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
209
+
210
+
211
+ def write_jsonl(path: Path, rows: Iterable[dict[str, Any]]) -> None:
212
+ path.parent.mkdir(parents=True, exist_ok=True)
213
+ with path.open("w", encoding="utf-8") as f:
214
+ for row in rows:
215
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
216
+
217
+
218
+ def write_csv(path: Path, rows: list[dict[str, Any]], fieldnames: list[str] | None = None) -> None:
219
+ path.parent.mkdir(parents=True, exist_ok=True)
220
+ if fieldnames is None:
221
+ keys: set[str] = set()
222
+ for row in rows:
223
+ keys.update(row.keys())
224
+ fieldnames = sorted(keys)
225
+ with path.open("w", encoding="utf-8", newline="") as f:
226
+ writer = csv.DictWriter(f, fieldnames=fieldnames)
227
+ writer.writeheader()
228
+ for row in rows:
229
+ writer.writerow({key: row.get(key) for key in fieldnames})
230
+
231
+
232
+ def format_duration(seconds: float | int | None) -> str:
233
+ if seconds is None:
234
+ return "--:--:--"
235
+ total_seconds = max(0, int(round(float(seconds))))
236
+ hours, rem = divmod(total_seconds, 3600)
237
+ minutes, secs = divmod(rem, 60)
238
+ return f"{hours:02d}:{minutes:02d}:{secs:02d}"
239
+
240
+
241
+ @dataclass
242
+ class TaskProgressTracker:
243
+ task_name: str
244
+ total_steps: int
245
+ step_label: str = "datasets"
246
+ substep_label: str = "assets"
247
+ total_substeps: int = 0
248
+ completed_steps: int = 0
249
+ completed_substeps: int = 0
250
+
251
+ def __post_init__(self) -> None:
252
+ self._start_ts = time.monotonic()
253
+ self._last_print_ts = self._start_ts
254
+
255
+ def print_start(self, extra: str = "") -> None:
256
+ parts = [
257
+ f"[{self.task_name}] start",
258
+ f"{self.step_label}=0/{self.total_steps}",
259
+ ]
260
+ if self.total_substeps > 0:
261
+ parts.append(f"{self.substep_label}=0/{self.total_substeps}")
262
+ if extra:
263
+ parts.append(extra)
264
+ print(" | ".join(parts), flush=True)
265
+
266
+ def advance(self, *, step_name: str, substeps_done: int = 0, extra: str = "") -> None:
267
+ self.completed_steps += 1
268
+ self.completed_substeps += max(0, int(substeps_done))
269
+ elapsed = time.monotonic() - self._start_ts
270
+ avg_per_step = (elapsed / self.completed_steps) if self.completed_steps > 0 else None
271
+ remaining_steps = max(0, self.total_steps - self.completed_steps)
272
+ eta_seconds = (avg_per_step * remaining_steps) if avg_per_step is not None else None
273
+
274
+ parts = [
275
+ f"[{self.task_name}] {self.step_label}={self.completed_steps}/{self.total_steps}",
276
+ ]
277
+ if self.total_substeps > 0:
278
+ parts.append(f"{self.substep_label}={self.completed_substeps}/{self.total_substeps}")
279
+ parts.extend(
280
+ [
281
+ f"elapsed={format_duration(elapsed)}",
282
+ f"eta={format_duration(eta_seconds)}",
283
+ f"done={step_name}",
284
+ ]
285
+ )
286
+ if extra:
287
+ parts.append(extra)
288
+ print(" | ".join(parts), flush=True)
289
+
290
+
291
+ def make_task_run_dir(task_name: str, run_tag: str) -> Path:
292
+ run_dir = OUTPUT_ROOT / task_name / "runs" / run_tag
293
+ run_dir.mkdir(parents=True, exist_ok=True)
294
+ write_json(OUTPUT_ROOT / task_name / "LATEST_RUN.json", {"run_tag": run_tag, "run_dir": str(run_dir.resolve())})
295
+ return run_dir
296
+
297
+
298
+ def list_dataset_ids() -> list[str]:
299
+ out: list[str] = []
300
+ if not DATA_ROOT.exists():
301
+ return out
302
+ for path in sorted(DATA_ROOT.iterdir()):
303
+ if not path.is_dir():
304
+ continue
305
+ if path.name.startswith("."):
306
+ continue
307
+ train_csv = resolve_real_split_path(path.name, split="train")
308
+ if train_csv.exists():
309
+ out.append(path.name)
310
+ return out
311
+
312
+
313
+ def resolve_dataset_dir(dataset_id: str) -> Path:
314
+ return DATA_ROOT / dataset_id
315
+
316
+
317
+ def resolve_real_split_path(dataset_id: str, split: str = "train") -> Path:
318
+ candidates = [
319
+ DATA_ROOT / dataset_id / f"{dataset_id}-{split}.csv",
320
+ DATA_ROOT / dataset_id / "raw" / f"{dataset_id}-{split}.csv",
321
+ ]
322
+ for path in candidates:
323
+ if path.exists():
324
+ return path
325
+ return candidates[0]
326
+
327
+
328
+ def resolve_field_registry_path(dataset_id: str) -> Path | None:
329
+ candidates = [
330
+ DATA_ROOT / dataset_id / "metadata_core" / "field_registry.json",
331
+ DATA_ROOT / dataset_id / "metadata" / "field_registry.json",
332
+ ]
333
+ for path in candidates:
334
+ if path.exists():
335
+ return path
336
+ return None
337
+
338
+
339
+ def load_field_registry(dataset_id: str) -> dict[str, Any]:
340
+ path = resolve_field_registry_path(dataset_id)
341
+ if path is None:
342
+ return {}
343
+ return read_json(path, {}) or {}
344
+
345
+
346
+ def load_field_type_hints(dataset_id: str) -> dict[str, str]:
347
+ payload = load_field_registry(dataset_id)
348
+ hints: dict[str, str] = {}
349
+ for item in payload.get("fields", []) if isinstance(payload, dict) else []:
350
+ if not isinstance(item, dict):
351
+ continue
352
+ name = str(item.get("name") or "").strip()
353
+ if not name:
354
+ continue
355
+ semantic = str(item.get("semantic_type") or "").strip().lower()
356
+ declared = str(item.get("declared_type") or "").strip().lower()
357
+ hints[name] = semantic or declared
358
+ return hints
359
+
360
+
361
+ def resolve_sql_result_role_annotation_path(dataset_id: str) -> Path:
362
+ return SQL_RESULT_ROLE_ANNOTATION_ROOT / dataset_id / "outputs" / "sql_result_roles_ai_v1.json"
363
+
364
+
365
+ def load_sql_result_role_annotations(
366
+ dataset_id: str,
367
+ *,
368
+ sql_source_version: str | None = None,
369
+ ) -> dict[tuple[str, str], dict[str, Any]]:
370
+ path = resolve_sql_result_role_annotation_path(dataset_id)
371
+ payload = read_json(path, {}) or {}
372
+ query_annotations = payload.get("query_annotations") if isinstance(payload, dict) else []
373
+ requested_version = normalize_sql_source_version(sql_source_version) if sql_source_version else None
374
+
375
+ output: dict[tuple[str, str], dict[str, Any]] = {}
376
+ if not isinstance(query_annotations, list):
377
+ return output
378
+
379
+ for item in query_annotations:
380
+ if not isinstance(item, dict):
381
+ continue
382
+ version_text = str(item.get("sql_source_version") or "").strip()
383
+ query_id = str(item.get("query_id") or "").strip()
384
+ if not query_id:
385
+ continue
386
+ try:
387
+ normalized_version = normalize_sql_source_version(version_text or requested_version or DEFAULT_SQL_SOURCE_VERSION)
388
+ except Exception:
389
+ continue
390
+ if requested_version and normalized_version != requested_version:
391
+ continue
392
+ output[(normalized_version, query_id)] = item
393
+ return output
394
+
395
+
396
+ def parse_timestamp_text(value: str | None) -> datetime | None:
397
+ if not value:
398
+ return None
399
+ text = str(value).strip()
400
+ try:
401
+ if text.endswith("Z"):
402
+ text = text[:-1] + "+00:00"
403
+ parsed = datetime.fromisoformat(text)
404
+ if parsed.tzinfo is None:
405
+ parsed = parsed.replace(tzinfo=timezone.utc)
406
+ return parsed.astimezone(timezone.utc)
407
+ except Exception:
408
+ pass
409
+ match = TIMESTAMP_RE.search(text)
410
+ if not match:
411
+ return None
412
+ try:
413
+ return datetime.strptime(match.group(1), "%Y%m%d_%H%M%S").replace(tzinfo=timezone.utc)
414
+ except Exception:
415
+ return None
416
+
417
+
418
+ def _candidate_timestamps(*values: str | Path | None) -> list[datetime]:
419
+ out: list[datetime] = []
420
+ for value in values:
421
+ if value is None:
422
+ continue
423
+ parsed = parse_timestamp_text(str(value))
424
+ if parsed is not None:
425
+ out.append(parsed)
426
+ return out
427
+
428
+
429
+ def _stat_mtime_ts(path: Path | None) -> datetime | None:
430
+ if path is None or not path.exists():
431
+ return None
432
+ try:
433
+ return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)
434
+ except Exception:
435
+ return None
436
+
437
+
438
+ def _stat_size_bytes(path: Path | None) -> int | None:
439
+ if path is None or not path.exists():
440
+ return None
441
+ try:
442
+ return int(path.stat().st_size)
443
+ except Exception:
444
+ return None
445
+
446
+
447
+ def _resolved_path_text(path: Path | None) -> str:
448
+ if path is None:
449
+ return ""
450
+ try:
451
+ return str(path.expanduser().resolve())
452
+ except Exception:
453
+ return str(path)
454
+
455
+
456
+ def _path_provenance_fields(prefix: str, path: Path | None) -> dict[str, Any]:
457
+ mtime = _stat_mtime_ts(path)
458
+ return {
459
+ f"{prefix}_path": _resolved_path_text(path),
460
+ f"{prefix}_exists": bool(path and path.exists()),
461
+ f"{prefix}_mtime_utc": (mtime.isoformat() if mtime is not None else None),
462
+ f"{prefix}_size_bytes": _stat_size_bytes(path),
463
+ }
464
+
465
+
466
+ def _sha256_text(text: str) -> str:
467
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
468
+
469
+
470
+ def _resolve_registry_backed_path(raw_path: str | Path | None) -> Path:
471
+ text = str(raw_path or "").strip()
472
+ if not text:
473
+ return Path("")
474
+ candidate = Path(text).expanduser()
475
+ if candidate.exists():
476
+ return candidate
477
+
478
+ normalized = text.replace("\\", "/")
479
+ marker = "/SQLagent/"
480
+ if marker in normalized:
481
+ suffix = normalized.split(marker, 1)[1].lstrip("/")
482
+ rebased = (PROJECT_ROOT / suffix).resolve()
483
+ if rebased.exists():
484
+ return rebased
485
+
486
+ if normalized.startswith("SQLagent/"):
487
+ rebased = (PROJECT_ROOT / normalized[len("SQLagent/"):]).resolve()
488
+ if rebased.exists():
489
+ return rebased
490
+
491
+ match = SUBITEM_RUNS_PATH_RE.search(normalized)
492
+ if match:
493
+ version = match.group(1).lower()
494
+ suffix = match.group("suffix").lstrip("/")
495
+ rebased = (runs_root(version) / suffix).resolve()
496
+ if rebased.exists():
497
+ return rebased
498
+
499
+ return candidate
500
+
501
+
502
+ def sql_source_family(version: str | None) -> str:
503
+ normalized = normalize_sql_source_version(version)
504
+ return "legacy" if normalized == SQL_SOURCE_VERSION_V1 else "current"
505
+
506
+
507
+ def sql_source_line_version(version: str | None) -> str:
508
+ normalized = normalize_sql_source_version(version)
509
+ return normalized if normalized in CURRENT_SQL_SOURCE_VERSIONS else ""
510
+
511
+
512
+ def sql_source_registry_root(version: str | None) -> Path | None:
513
+ normalized = normalize_sql_source_version(version)
514
+ if normalized == SQL_SOURCE_VERSION_V1:
515
+ return None
516
+ return registry_dir(normalized)
517
+
518
+
519
+ def is_current_sql_source_version(version: str | None) -> bool:
520
+ return normalize_sql_source_version(version) in CURRENT_SQL_SOURCE_VERSIONS
521
+
522
+
523
+ def real_split_provenance(dataset_id: str, split: str = "train") -> dict[str, Any]:
524
+ real_path = resolve_real_split_path(dataset_id, split=split)
525
+ return {
526
+ "provenance_contract_version": PROVENANCE_CONTRACT_VERSION,
527
+ "real_reference_split": split,
528
+ "real_source_kind": "reference_split_csv",
529
+ "real_source_dataset_id": dataset_id,
530
+ "real_source_split": split,
531
+ **_path_provenance_fields("real_source", real_path),
532
+ }
533
+
534
+
535
+ def resolve_latest_task_run_dir(task_name: str) -> Path | None:
536
+ latest_path = OUTPUT_ROOT / task_name / "LATEST_RUN.json"
537
+ payload = read_json(latest_path, {}) or {}
538
+ run_dir = payload.get("run_dir")
539
+ if not run_dir:
540
+ return None
541
+ candidate = Path(str(run_dir))
542
+ return candidate if candidate.exists() else None
543
+
544
+
545
+ def resolve_requested_sql_source_version(
546
+ task_name: str | None = None,
547
+ default: str = DEFAULT_SQL_SOURCE_VERSION,
548
+ ) -> str:
549
+ override = str(os.environ.get(SQL_SOURCE_VERSION_ENV_VAR) or "").strip()
550
+ if override:
551
+ return normalize_sql_source_version(override)
552
+ if task_name:
553
+ return resolve_latest_task_sql_source_version(task_name, default=default)
554
+ return normalize_sql_source_version(default)
555
+
556
+
557
+ def resolve_latest_task_sql_source_version(task_name: str, default: str = DEFAULT_SQL_SOURCE_VERSION) -> str:
558
+ run_dir = resolve_latest_task_run_dir(task_name)
559
+ if run_dir is None:
560
+ return normalize_sql_source_version(default)
561
+ manifest = read_json(run_dir / "manifest.json", {}) or {}
562
+ try:
563
+ return normalize_sql_source_version(str(manifest.get("sql_source_version") or default))
564
+ except Exception:
565
+ return normalize_sql_source_version(default)
566
+
567
+
568
+ def resolve_task_run_dir_for_sql_source(
569
+ task_name: str,
570
+ sql_source_version: str | None = None,
571
+ *,
572
+ default: str = DEFAULT_SQL_SOURCE_VERSION,
573
+ ) -> Path | None:
574
+ requested = resolve_requested_sql_source_version(task_name=task_name, default=default)
575
+ target_version = normalize_sql_source_version(sql_source_version or requested)
576
+ latest_run_dir = resolve_latest_task_run_dir(task_name)
577
+ if latest_run_dir is not None:
578
+ latest_manifest = read_json(latest_run_dir / "manifest.json", {}) or {}
579
+ latest_version = str(latest_manifest.get("sql_source_version") or "").strip()
580
+ if latest_version:
581
+ try:
582
+ if normalize_sql_source_version(latest_version) == target_version:
583
+ return latest_run_dir
584
+ except Exception:
585
+ pass
586
+
587
+ runs_root_dir = OUTPUT_ROOT / task_name / "runs"
588
+ if not runs_root_dir.exists():
589
+ return None
590
+
591
+ ranked: list[tuple[int, int, str, Path]] = []
592
+ for candidate in runs_root_dir.iterdir():
593
+ if not candidate.is_dir():
594
+ continue
595
+ manifest_path = candidate / "manifest.json"
596
+ if not manifest_path.exists():
597
+ continue
598
+ manifest = read_json(manifest_path, {}) or {}
599
+ manifest_version = str(manifest.get("sql_source_version") or "").strip()
600
+ if not manifest_version:
601
+ continue
602
+ try:
603
+ if normalize_sql_source_version(manifest_version) != target_version:
604
+ continue
605
+ except Exception:
606
+ continue
607
+ ranked.append(
608
+ (
609
+ int(manifest.get("dataset_count") or 0),
610
+ int(manifest.get("asset_count") or 0),
611
+ candidate.name,
612
+ candidate.resolve(),
613
+ )
614
+ )
615
+ if not ranked:
616
+ return None
617
+ ranked.sort(reverse=True)
618
+ return ranked[0][3]
619
+
620
+
621
+ def build_sql_source_provenance(
622
+ *,
623
+ sql_source_version: str,
624
+ sql_source_kind: str,
625
+ sql_source_selection_mode: str,
626
+ source_run_id: str = "",
627
+ sql_file_path: Path | None = None,
628
+ manifest_path: Path | None = None,
629
+ registry_path: Path | None = None,
630
+ run_dir: Path | None = None,
631
+ dataset_dir: Path | None = None,
632
+ registry_version: str = "",
633
+ declared_version: str = "",
634
+ declared_label: str = "",
635
+ sql_file_sha256: str = "",
636
+ ) -> dict[str, Any]:
637
+ normalized = normalize_sql_source_version(sql_source_version)
638
+ registry_root = sql_source_registry_root(normalized)
639
+ return {
640
+ "provenance_contract_version": PROVENANCE_CONTRACT_VERSION,
641
+ "sql_source_family": sql_source_family(normalized),
642
+ "sql_source_line_version": sql_source_line_version(normalized),
643
+ "sql_source_version": normalized,
644
+ "sql_source_label": sql_source_label(normalized),
645
+ "sql_source_description": sql_source_description(normalized),
646
+ "sql_source_root": _resolved_path_text(sql_source_root(normalized)),
647
+ "sql_source_registry_root": _resolved_path_text(registry_root),
648
+ "sql_source_kind": sql_source_kind,
649
+ "sql_source_selection_mode": sql_source_selection_mode,
650
+ "sql_source_registry_version": str(registry_version or ""),
651
+ "sql_source_declared_version": str(declared_version or ""),
652
+ "sql_source_declared_label": str(declared_label or ""),
653
+ "sql_source_file_sha256": str(sql_file_sha256 or ""),
654
+ "source_run_id": str(source_run_id or ""),
655
+ "sql_origin_path": _resolved_path_text(sql_file_path),
656
+ **_path_provenance_fields("sql_source_file", sql_file_path),
657
+ **_path_provenance_fields("sql_source_manifest", manifest_path),
658
+ **_path_provenance_fields("sql_source_registry", registry_path),
659
+ **_path_provenance_fields("sql_source_run_dir", run_dir),
660
+ **_path_provenance_fields("sql_source_dataset_dir", dataset_dir),
661
+ }
662
+
663
+
664
+ def _find_local_artifact_by_name(search_root: Path, name: str) -> Path | None:
665
+ if not name:
666
+ return None
667
+ for path in search_root.rglob(name):
668
+ if path.is_file():
669
+ return path
670
+ return None
671
+
672
+
673
+ def _choose_synthetic_csv(candidates: list[Path]) -> Path | None:
674
+ filtered = _list_synthetic_csv_candidates(candidates)
675
+ if not filtered:
676
+ return None
677
+ filtered.sort(key=lambda p: (parse_timestamp_text(p.name) or _stat_mtime_ts(p) or datetime.min.replace(tzinfo=timezone.utc)))
678
+ return filtered[-1]
679
+
680
+
681
+ def _list_synthetic_csv_candidates(candidates: Iterable[Path]) -> list[Path]:
682
+ return [path for path in candidates if _is_synthetic_candidate_csv(path)]
683
+
684
+
685
+ def _is_synthetic_candidate_csv(path: Path) -> bool:
686
+ lname = path.name.lower()
687
+ stem = path.stem.lower()
688
+ if "train_continuous_imputed" in lname:
689
+ return False
690
+ for suffix in ("real", "test", "val", "train"):
691
+ if f"__{suffix}.csv" in lname or lname.endswith(f"_{suffix}.csv") or stem.endswith(f"_{suffix}"):
692
+ return False
693
+ return True
694
+
695
+
696
+ def _synthetic_candidate_sort_key(path: Path) -> datetime:
697
+ return parse_timestamp_text(path.name) or _stat_mtime_ts(path) or datetime.min.replace(tzinfo=timezone.utc)
698
+
699
+
700
+ def _runtime_result_prefix(path: Path) -> str:
701
+ match = RUNTIME_RESULT_RE.match(path.name)
702
+ if match:
703
+ return str(match.group("prefix") or "").strip()
704
+ return path.stem
705
+
706
+
707
+ def _match_runtime_payload_for_synthetic_csv(runtime_files: list[Path], synthetic_csv_path: Path) -> tuple[dict[str, Any], Path | None]:
708
+ synthetic_name = synthetic_csv_path.name
709
+ for runtime_file in sorted(runtime_files, reverse=True):
710
+ prefix = _runtime_result_prefix(runtime_file)
711
+ if prefix and synthetic_name.startswith(prefix):
712
+ return read_json(runtime_file, {}) or {}, runtime_file
713
+ if runtime_files:
714
+ chosen = sorted(runtime_files)[-1]
715
+ return read_json(chosen, {}) or {}, chosen
716
+ return {}, None
717
+
718
+
719
+ def _derive_run_id_for_candidate(runtime_run_id: str, synthetic_csv_path: Path) -> str:
720
+ stem = synthetic_csv_path.stem
721
+ if runtime_run_id and runtime_run_id in stem:
722
+ suffix = stem.split(runtime_run_id, 1)[1].strip("_-")
723
+ if suffix:
724
+ return f"{runtime_run_id}__{suffix}"
725
+ return runtime_run_id
726
+ if runtime_run_id:
727
+ return runtime_run_id
728
+ return stem
729
+
730
+
731
+ def _extract_gpu_seconds_from_logs(log_paths: list[Path], synthetic_csv_path: Path | None = None) -> tuple[float, str]:
732
+ explicit_seconds = 0.0
733
+ saw_explicit = False
734
+ for path in log_paths:
735
+ try:
736
+ text = path.read_text(encoding="utf-8", errors="ignore")
737
+ except Exception:
738
+ continue
739
+ for regex in [TRAIN_TIME_RE, SAMPLE_TIME_RE, GENERIC_SECONDS_RE]:
740
+ for match in regex.findall(text):
741
+ try:
742
+ explicit_seconds += float(match)
743
+ saw_explicit = True
744
+ except Exception:
745
+ continue
746
+ if saw_explicit and explicit_seconds > 0:
747
+ return explicit_seconds, "explicit_log_seconds"
748
+
749
+ inferred_seconds = 0.0
750
+ for path in log_paths:
751
+ start_ts = parse_timestamp_text(path.name) or parse_timestamp_text(path.stem)
752
+ end_ts = _stat_mtime_ts(path)
753
+ if start_ts is not None and end_ts is not None:
754
+ delta = (end_ts - start_ts).total_seconds()
755
+ if 0 < delta <= MAX_FALLBACK_GPU_SECONDS:
756
+ inferred_seconds += delta
757
+ if inferred_seconds > 0:
758
+ return inferred_seconds, "log_mtime_fallback"
759
+
760
+ if log_paths and synthetic_csv_path is not None and synthetic_csv_path.exists():
761
+ start_candidates = [parse_timestamp_text(path.name) for path in log_paths]
762
+ start_candidates = [item for item in start_candidates if item is not None]
763
+ end_ts = _stat_mtime_ts(synthetic_csv_path)
764
+ if start_candidates and end_ts is not None:
765
+ delta = (end_ts - min(start_candidates)).total_seconds()
766
+ if 0 < delta <= MAX_FALLBACK_GPU_SECONDS:
767
+ return delta, "artifact_mtime_fallback"
768
+
769
+ return 0.0, "unavailable_zero"
770
+
771
+
772
+ def _extract_gpu_seconds_from_runtime_payload(runtime_payload: dict[str, Any] | None) -> tuple[float, str] | None:
773
+ if not isinstance(runtime_payload, dict):
774
+ return None
775
+ timings = runtime_payload.get("timings")
776
+ if not isinstance(timings, dict):
777
+ return None
778
+ total_seconds = 0.0
779
+ saw_duration = False
780
+ for stage_name in ("train", "generate"):
781
+ stage_payload = timings.get(stage_name)
782
+ if not isinstance(stage_payload, dict):
783
+ continue
784
+ raw_value = stage_payload.get("duration_sec")
785
+ if raw_value is None:
786
+ continue
787
+ try:
788
+ duration_sec = float(raw_value)
789
+ except Exception:
790
+ continue
791
+ if duration_sec > 0:
792
+ total_seconds += duration_sec
793
+ saw_duration = True
794
+ if saw_duration:
795
+ return total_seconds, "runtime_result_timings"
796
+ return None
797
+
798
+
799
+ def _hyperparameter_tabsyn_is_consistent_batch(env_overrides: dict[str, Any]) -> bool:
800
+ # Accept any successful Tabsyn hyperparameter run that explicitly varies
801
+ # training knobs. Older code only admitted one very specific sweep shape,
802
+ # which filtered out newer smoke/BO runs (e.g. smaller batch sizes).
803
+ keys = {str(k): v for k, v in env_overrides.items()}
804
+ has_batch = any(
805
+ str(keys.get(name) or "").strip()
806
+ for name in (
807
+ "TABSYN_VAE_BATCH_SIZE",
808
+ "TABSYN_DIFFUSION_BATCH_SIZE",
809
+ "TABSYN_VAE_ENCODE_BATCH_SIZE",
810
+ "TABSYN_VAE_EVAL_BATCH_SIZE",
811
+ "TABSYN_VAE_INFER_BATCH_SIZE",
812
+ )
813
+ )
814
+ has_epoch = any(
815
+ str(keys.get(name) or "").strip()
816
+ for name in (
817
+ "TABSYN_VAE_EPOCHS",
818
+ "TABSYN_DIFFUSION_MAX_EPOCHS",
819
+ )
820
+ )
821
+ if not (has_batch and has_epoch):
822
+ return False
823
+ num_workers = str(keys.get("TABSYN_VAE_NUM_WORKERS") or "").strip()
824
+ if num_workers and num_workers != "0":
825
+ return False
826
+ return True
827
+
828
+
829
+ def _should_keep_hyperparameter_run(*, model_id: str, run_config_payload: dict[str, Any], runtime_payload: dict[str, Any]) -> bool:
830
+ if str(runtime_payload.get("train_status") or "").strip().lower() != "success":
831
+ return False
832
+ if str(runtime_payload.get("generate_status") or "").strip().lower() != "success":
833
+ return False
834
+ env_overrides = run_config_payload.get("env_overrides")
835
+ if not isinstance(env_overrides, dict) or not env_overrides:
836
+ return False
837
+ if str(model_id or "").strip().lower() == "tabsyn":
838
+ if _hyperparameter_tabsyn_is_consistent_batch(env_overrides):
839
+ return True
840
+ cli_args = run_config_payload.get("cli_args")
841
+ cli_args = cli_args if isinstance(cli_args, dict) else {}
842
+ has_epoch_signal = bool(str(cli_args.get("epochs") or "").strip()) or any(
843
+ str(env_overrides.get(name) or "").strip()
844
+ for name in ("TABSYN_VAE_EPOCHS", "TABSYN_DIFFUSION_MAX_EPOCHS")
845
+ )
846
+ has_batch_signal = any(
847
+ str(env_overrides.get(name) or "").strip()
848
+ for name in (
849
+ "TABSYN_VAE_BATCH_SIZE",
850
+ "TABSYN_DIFFUSION_BATCH_SIZE",
851
+ "TABSYN_VAE_ENCODE_BATCH_SIZE",
852
+ "TABSYN_VAE_EVAL_BATCH_SIZE",
853
+ "TABSYN_VAE_INFER_BATCH_SIZE",
854
+ )
855
+ )
856
+ return has_epoch_signal and has_batch_signal
857
+ return True
858
+
859
+
860
+ def _has_substantive_hyperparameter_overrides(env_overrides: dict[str, Any]) -> bool:
861
+ for key, value in env_overrides.items():
862
+ if str(key).startswith("BENCHMARK_"):
863
+ continue
864
+ if value is None:
865
+ continue
866
+ if str(value).strip():
867
+ return True
868
+ return False
869
+
870
+
871
+ def _build_asset(
872
+ *,
873
+ dataset_id: str,
874
+ model_id: str,
875
+ root_name: str,
876
+ asset_dir: Path,
877
+ run_id: str,
878
+ synthetic_csv_path: Path,
879
+ metadata_paths: list[Path],
880
+ log_paths: list[Path],
881
+ discovered_via: str,
882
+ runtime_payload: dict[str, Any] | None = None,
883
+ ) -> SyntheticAsset:
884
+ cfg = ROOT_CONFIGS[root_name]
885
+ timestamp_candidates = []
886
+ timestamp_candidates.extend(_candidate_timestamps(run_id, synthetic_csv_path.name))
887
+ timestamp_candidates.extend(item for item in (_stat_mtime_ts(synthetic_csv_path), _stat_mtime_ts(asset_dir)) if item is not None)
888
+ timestamp = max(timestamp_candidates) if timestamp_candidates else None
889
+ runtime_timing = _extract_gpu_seconds_from_runtime_payload(runtime_payload)
890
+ if runtime_timing is not None:
891
+ gpu_seconds_raw, gpu_source = runtime_timing
892
+ else:
893
+ gpu_seconds_raw, gpu_source = _extract_gpu_seconds_from_logs(log_paths, synthetic_csv_path)
894
+ gpu_hours_equivalent = (gpu_seconds_raw / 3600.0) * float(cfg["gpu_hour_ratio"])
895
+ return SyntheticAsset(
896
+ dataset_id=dataset_id,
897
+ model_id=model_id,
898
+ server_type=str(cfg["server_type"]),
899
+ root_name=root_name,
900
+ root_path=str(Path(cfg["path"]).resolve()),
901
+ asset_dir=str(asset_dir.resolve()),
902
+ run_id=run_id,
903
+ synthetic_csv_path=str(synthetic_csv_path.resolve()),
904
+ metadata_paths=[str(path.resolve()) for path in metadata_paths],
905
+ log_paths=[str(path.resolve()) for path in log_paths],
906
+ discovered_via=discovered_via,
907
+ timestamp_utc=(timestamp.isoformat() if timestamp is not None else None),
908
+ synthetic_source_mtime_utc=(_stat_mtime_ts(synthetic_csv_path).isoformat() if _stat_mtime_ts(synthetic_csv_path) is not None else None),
909
+ synthetic_source_size_bytes=_stat_size_bytes(synthetic_csv_path),
910
+ gpu_seconds_raw=round(gpu_seconds_raw, 6),
911
+ gpu_hours_equivalent=round(gpu_hours_equivalent, 6),
912
+ gpu_hours_source=gpu_source,
913
+ cost_usd=round(gpu_hours_equivalent * USD_PER_GPU_HOUR, 6),
914
+ )
915
+
916
+
917
+ def _discover_assets_in_synoutput(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
918
+ root = Path(ROOT_CONFIGS[root_name]["path"])
919
+ dataset_root = root / dataset_id
920
+ if not dataset_root.exists():
921
+ return []
922
+ assets: list[SyntheticAsset] = []
923
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
924
+ model_id = model_dir.name
925
+ for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
926
+ manifest_path = run_dir / "manifest.json"
927
+ if not manifest_path.exists():
928
+ continue
929
+ manifest = read_json(manifest_path, {}) or {}
930
+ runtime_result = manifest.get("runtime_result") if isinstance(manifest, dict) else {}
931
+ artifacts = runtime_result.get("artifacts") if isinstance(runtime_result, dict) else {}
932
+ desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name
933
+ synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None
934
+ if synthetic_csv_path is None:
935
+ synthetic_csv_path = _choose_synthetic_csv(list((run_dir / "synthetic").glob("*.csv")))
936
+ if synthetic_csv_path is None:
937
+ continue
938
+ run_id = str(runtime_result.get("run_id") or manifest.get("run_id") or run_dir.name)
939
+ log_paths = sorted((run_dir / "logs").glob("*.log"))
940
+ metadata_paths = [manifest_path] + sorted((run_dir / "meta").glob("*.json"))
941
+ assets.append(
942
+ _build_asset(
943
+ dataset_id=dataset_id,
944
+ model_id=model_id,
945
+ root_name=root_name,
946
+ asset_dir=run_dir,
947
+ run_id=run_id,
948
+ synthetic_csv_path=synthetic_csv_path,
949
+ metadata_paths=metadata_paths,
950
+ log_paths=log_paths,
951
+ discovered_via="manifest_json",
952
+ )
953
+ )
954
+ return assets
955
+
956
+
957
+ def _discover_assets_in_synoutput_5090(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
958
+ root = Path(ROOT_CONFIGS[root_name]["path"])
959
+ dataset_root = root / dataset_id
960
+ if not dataset_root.exists():
961
+ return []
962
+ assets: list[SyntheticAsset] = []
963
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
964
+ model_id = model_dir.name
965
+ runtime_files = sorted((model_dir / "metadata").glob("*__runtime_result.json"))
966
+ synthetic_candidates = sorted(
967
+ _list_synthetic_csv_candidates((model_dir / "synthetic_data").glob("*.csv")),
968
+ key=_synthetic_candidate_sort_key,
969
+ )
970
+ if not synthetic_candidates:
971
+ continue
972
+ metadata_paths_all = sorted((model_dir / "metadata").glob("*.json"))
973
+ log_paths = sorted((model_dir / "logs").glob("*.log"))
974
+
975
+ for synthetic_csv_path in synthetic_candidates:
976
+ runtime_payload, matched_runtime = _match_runtime_payload_for_synthetic_csv(runtime_files, synthetic_csv_path)
977
+ runtime_run_id = str(runtime_payload.get("run_id") or model_dir.name)
978
+ run_id = _derive_run_id_for_candidate(runtime_run_id, synthetic_csv_path)
979
+ metadata_paths = list(metadata_paths_all)
980
+ if matched_runtime is not None and matched_runtime not in metadata_paths:
981
+ metadata_paths = [matched_runtime] + metadata_paths
982
+ assets.append(
983
+ _build_asset(
984
+ dataset_id=dataset_id,
985
+ model_id=model_id,
986
+ root_name=root_name,
987
+ asset_dir=model_dir,
988
+ run_id=run_id,
989
+ synthetic_csv_path=synthetic_csv_path,
990
+ metadata_paths=metadata_paths,
991
+ log_paths=log_paths,
992
+ discovered_via=("runtime_result_json_matched" if matched_runtime is not None else "synthetic_csv_scan"),
993
+ )
994
+ )
995
+ return assets
996
+
997
+
998
+ def _discover_assets_in_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
999
+ root = Path(ROOT_CONFIGS[root_name]["path"])
1000
+ dataset_root = root / dataset_id
1001
+ if not dataset_root.exists():
1002
+ return []
1003
+ assets: list[SyntheticAsset] = []
1004
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
1005
+ model_id = model_dir.name
1006
+ for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
1007
+ runtime_path = run_dir / "runtime_result.json"
1008
+ runtime_payload = read_json(runtime_path, {}) or {}
1009
+ if not isinstance(runtime_payload, dict):
1010
+ continue
1011
+ artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {}
1012
+ desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name
1013
+ candidate_files = list(run_dir.glob("*.csv"))
1014
+ synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None
1015
+ if synthetic_csv_path is None:
1016
+ synthetic_csv_path = _choose_synthetic_csv(candidate_files)
1017
+ if synthetic_csv_path is None:
1018
+ continue
1019
+
1020
+ run_id = str(runtime_payload.get("run_id") or run_dir.name)
1021
+ log_paths = sorted(run_dir.glob("*.log"))
1022
+ metadata_paths = [runtime_path] if runtime_path.exists() else []
1023
+ for extra in [
1024
+ run_dir / "input_snapshot.json",
1025
+ run_dir / "run_config.json",
1026
+ run_dir / "public_gate" / "public_gate_report.json",
1027
+ run_dir / "public_gate" / "normalized_schema_snapshot.json",
1028
+ run_dir / "public_gate" / "staged_input_manifest.json",
1029
+ ]:
1030
+ if extra.exists() and extra not in metadata_paths:
1031
+ metadata_paths.append(extra)
1032
+ assets.append(
1033
+ _build_asset(
1034
+ dataset_id=dataset_id,
1035
+ model_id=model_id,
1036
+ root_name=root_name,
1037
+ asset_dir=run_dir,
1038
+ run_id=run_id,
1039
+ synthetic_csv_path=synthetic_csv_path,
1040
+ metadata_paths=metadata_paths,
1041
+ log_paths=log_paths,
1042
+ discovered_via="runtime_result_json",
1043
+ runtime_payload=runtime_payload,
1044
+ )
1045
+ )
1046
+ return assets
1047
+
1048
+
1049
+ def _discover_assets_in_hyperparameter_trainonly_root(dataset_id: str, root_name: str) -> list[SyntheticAsset]:
1050
+ root = Path(ROOT_CONFIGS[root_name]["path"])
1051
+ dataset_root = root / dataset_id
1052
+ if not dataset_root.exists():
1053
+ return []
1054
+ assets: list[SyntheticAsset] = []
1055
+ for model_dir in sorted(path for path in dataset_root.iterdir() if path.is_dir()):
1056
+ model_id = model_dir.name
1057
+ candidate_runs: list[tuple[Path, dict[str, Any], dict[str, Any], bool]] = []
1058
+ for run_dir in sorted(path for path in model_dir.iterdir() if path.is_dir()):
1059
+ runtime_path = run_dir / "runtime_result.json"
1060
+ run_config_path = run_dir / "run_config.json"
1061
+ runtime_payload = read_json(runtime_path, {}) or {}
1062
+ run_config_payload = read_json(run_config_path, {}) or {}
1063
+ if not isinstance(runtime_payload, dict) or not isinstance(run_config_payload, dict):
1064
+ continue
1065
+ if not _should_keep_hyperparameter_run(
1066
+ model_id=model_id,
1067
+ run_config_payload=run_config_payload,
1068
+ runtime_payload=runtime_payload,
1069
+ ):
1070
+ continue
1071
+ env_overrides = run_config_payload.get("env_overrides")
1072
+ env_overrides = env_overrides if isinstance(env_overrides, dict) else {}
1073
+ candidate_runs.append(
1074
+ (
1075
+ run_dir,
1076
+ runtime_payload,
1077
+ run_config_payload,
1078
+ _has_substantive_hyperparameter_overrides(env_overrides),
1079
+ )
1080
+ )
1081
+
1082
+ if not candidate_runs:
1083
+ continue
1084
+ keep_only_substantive = any(item[3] for item in candidate_runs)
1085
+ for run_dir, runtime_payload, run_config_payload, has_substantive_overrides in candidate_runs:
1086
+ if keep_only_substantive and not has_substantive_overrides:
1087
+ continue
1088
+ artifacts = runtime_payload.get("artifacts") if isinstance(runtime_payload.get("artifacts"), dict) else {}
1089
+ desired_name = Path(str(artifacts.get("synthetic_csv") or "")).name
1090
+ candidate_files = list(run_dir.glob("*.csv"))
1091
+ synthetic_csv_path = _find_local_artifact_by_name(run_dir, desired_name) if desired_name else None
1092
+ if synthetic_csv_path is None:
1093
+ synthetic_csv_path = _choose_synthetic_csv(candidate_files)
1094
+ if synthetic_csv_path is None:
1095
+ continue
1096
+
1097
+ run_id = str(runtime_payload.get("run_id") or run_dir.name)
1098
+ log_paths = sorted(run_dir.glob("*.log"))
1099
+ metadata_paths = [runtime_path] if runtime_path.exists() else []
1100
+ for extra in [
1101
+ run_config_path,
1102
+ run_dir / "input_snapshot.json",
1103
+ run_dir / "public_gate" / "public_gate_report.json",
1104
+ run_dir / "public_gate" / "normalized_schema_snapshot.json",
1105
+ run_dir / "public_gate" / "staged_input_manifest.json",
1106
+ ]:
1107
+ if extra.exists() and extra not in metadata_paths:
1108
+ metadata_paths.append(extra)
1109
+ assets.append(
1110
+ _build_asset(
1111
+ dataset_id=dataset_id,
1112
+ model_id=model_id,
1113
+ root_name=root_name,
1114
+ asset_dir=run_dir,
1115
+ run_id=run_id,
1116
+ synthetic_csv_path=synthetic_csv_path,
1117
+ metadata_paths=metadata_paths,
1118
+ log_paths=log_paths,
1119
+ discovered_via="runtime_result_json_hyperparameter",
1120
+ runtime_payload=runtime_payload,
1121
+ )
1122
+ )
1123
+ return assets
1124
+
1125
+
1126
+ def discover_synthetic_assets(
1127
+ *,
1128
+ datasets: list[str] | None = None,
1129
+ latest_only: bool = True,
1130
+ root_names: list[str] | tuple[str, ...] | None = None,
1131
+ ) -> list[SyntheticAsset]:
1132
+ dataset_ids = datasets or list_dataset_ids()
1133
+ requested_roots = [str(item).strip() for item in (root_names or []) if str(item).strip()]
1134
+ if requested_roots:
1135
+ invalid = sorted(set(requested_roots) - set(ROOT_CONFIGS.keys()))
1136
+ if invalid:
1137
+ raise ValueError(f"Unsupported synthetic root names: {invalid}. Available: {sorted(ROOT_CONFIGS.keys())}")
1138
+ active_roots = requested_roots or list(ROOT_CONFIGS.keys())
1139
+ assets: list[SyntheticAsset] = []
1140
+ for dataset_id in dataset_ids:
1141
+ for root_name in active_roots:
1142
+ if root_name == "SynOutput":
1143
+ assets.extend(_discover_assets_in_synoutput(dataset_id, root_name))
1144
+ elif root_name == "SynOutput-5090":
1145
+ assets.extend(_discover_assets_in_synoutput_5090(dataset_id, root_name))
1146
+ elif root_name == "Benchmark-trainonly-v1":
1147
+ assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name))
1148
+ elif root_name == "Hyperparameter-trainonly-v1":
1149
+ assets.extend(_discover_assets_in_hyperparameter_trainonly_root(dataset_id, root_name))
1150
+ elif root_name == "TabQueryBench-SynDataSuccess-main":
1151
+ assets.extend(_discover_assets_in_trainonly_root(dataset_id, root_name))
1152
+ if not latest_only:
1153
+ return sorted(assets, key=lambda item: (item.dataset_id, item.server_type, item.model_id, item.timestamp_utc or ""))
1154
+
1155
+ latest_map: dict[tuple[str, str, str], SyntheticAsset] = {}
1156
+ for asset in assets:
1157
+ key = (asset.dataset_id, asset.server_type, asset.model_id)
1158
+ current = latest_map.get(key)
1159
+ asset_ts = parse_timestamp_text(asset.timestamp_utc or "")
1160
+ current_ts = parse_timestamp_text(current.timestamp_utc or "") if current else None
1161
+ if current is None or ((asset_ts or datetime.min.replace(tzinfo=timezone.utc)) >= (current_ts or datetime.min.replace(tzinfo=timezone.utc))):
1162
+ latest_map[key] = asset
1163
+ return sorted(latest_map.values(), key=lambda item: (item.dataset_id, item.server_type, item.model_id))
1164
+
1165
+
1166
+ def split_sql_statements(sql_text: str) -> list[str]:
1167
+ statements: list[str] = []
1168
+ buf: list[str] = []
1169
+ in_single = False
1170
+ in_double = False
1171
+ prev = ""
1172
+ for ch in sql_text:
1173
+ if ch == "'" and not in_double and prev != "\\":
1174
+ in_single = not in_single
1175
+ elif ch == '"' and not in_single and prev != "\\":
1176
+ in_double = not in_double
1177
+ if ch == ";" and not in_single and not in_double:
1178
+ stmt = "".join(buf).strip()
1179
+ if stmt:
1180
+ statements.append(stmt)
1181
+ buf = []
1182
+ else:
1183
+ buf.append(ch)
1184
+ prev = ch
1185
+ tail = "".join(buf).strip()
1186
+ if tail:
1187
+ statements.append(tail)
1188
+ cleaned = []
1189
+ for stmt in statements:
1190
+ lines = [line for line in stmt.splitlines() if not line.strip().startswith("--")]
1191
+ candidate = "\n".join(lines).strip()
1192
+ if candidate:
1193
+ cleaned.append(candidate)
1194
+ return cleaned
1195
+
1196
+
1197
+ def normalize_sql_source_version(value: str | None) -> str:
1198
+ text = str(value or "").strip().lower()
1199
+ if not text:
1200
+ return DEFAULT_SQL_SOURCE_VERSION
1201
+ match = re.search(r"(v[1-4])", text)
1202
+ if match and match.group(1) in SQL_SOURCE_VERSION_CHOICES:
1203
+ candidate = match.group(1)
1204
+ if candidate == SQL_SOURCE_VERSION_V1 and "subitem_workload" in text:
1205
+ candidate = ""
1206
+ if candidate:
1207
+ return candidate
1208
+ version = _SQL_SOURCE_ALIASES.get(text)
1209
+ if version is None:
1210
+ raise ValueError(
1211
+ f"Unsupported sql source version: {value!r}. Expected one of: {', '.join(SQL_SOURCE_VERSION_CHOICES)}"
1212
+ )
1213
+ return version
1214
+
1215
+
1216
+ def sql_source_label(version: str | None) -> str:
1217
+ normalized = normalize_sql_source_version(version)
1218
+ return _SQL_SOURCE_LABELS[normalized]
1219
+
1220
+
1221
+ def sql_source_description(version: str | None) -> str:
1222
+ normalized = normalize_sql_source_version(version)
1223
+ return _SQL_SOURCE_DESCRIPTIONS[normalized]
1224
+
1225
+
1226
+ def sql_source_root(version: str | None) -> Path:
1227
+ normalized = normalize_sql_source_version(version)
1228
+ if normalized == SQL_SOURCE_VERSION_V1:
1229
+ return LOGS_ROOT
1230
+ if normalized in CURRENT_SQL_SOURCE_VERSIONS:
1231
+ return runs_root(normalized)
1232
+ raise ValueError(f"Unsupported sql source version: {version!r}")
1233
+
1234
+
1235
+ def resolve_sql_run_dir(*, sql_source_version: str, run_id: str, dataset_id: str | None = None) -> Path:
1236
+ normalized = normalize_sql_source_version(sql_source_version)
1237
+ if normalized == SQL_SOURCE_VERSION_V1:
1238
+ return LOGS_ROOT / run_id
1239
+ if not dataset_id:
1240
+ raise ValueError("dataset_id is required when resolving a current workload run directory.")
1241
+ return runs_root(normalized) / run_id / dataset_id
1242
+
1243
+
1244
+ def _load_latest_v1_sql_query_groups(
1245
+ *,
1246
+ dataset_ids: Iterable[str] | None = None,
1247
+ engines: tuple[str, ...] = ("cli",),
1248
+ ) -> dict[tuple[str, str], dict[str, Any]]:
1249
+ grouped: dict[tuple[str, str], dict[str, Any]] = {}
1250
+ if not LOGS_ROOT.exists():
1251
+ return grouped
1252
+
1253
+ dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()}
1254
+ for manifest_path in LOGS_ROOT.rglob("run_manifest.json"):
1255
+ payload = read_json(manifest_path, {}) or {}
1256
+ if str(payload.get("status") or "") != "completed":
1257
+ continue
1258
+ if str(payload.get("mode") or "") != "template_grounded_sql_qa":
1259
+ continue
1260
+ dataset_id = str(payload.get("dataset_id") or "").strip()
1261
+ if not dataset_id:
1262
+ continue
1263
+ if dataset_filter and dataset_id not in dataset_filter:
1264
+ continue
1265
+ engine = str(payload.get("engine") or "").strip()
1266
+ if engines and engine not in engines:
1267
+ continue
1268
+ question_record = payload.get("question_record")
1269
+ if not isinstance(question_record, dict):
1270
+ continue
1271
+ question_id = str(question_record.get("question_id") or "").strip()
1272
+ if not question_id:
1273
+ continue
1274
+ sql_path = manifest_path.parent / "generated_sql.sql"
1275
+ if not sql_path.exists():
1276
+ continue
1277
+ ended_at = str(payload.get("ended_at") or payload.get("started_at") or "")
1278
+ key = (dataset_id, question_id)
1279
+ current = grouped.get(key)
1280
+ if current is None:
1281
+ grouped[key] = {
1282
+ "payload": payload,
1283
+ "sql_path": sql_path,
1284
+ "sort_dt": parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc),
1285
+ "manifest_path": manifest_path,
1286
+ }
1287
+ continue
1288
+ new_dt = parse_timestamp_text(ended_at) or _stat_mtime_ts(sql_path) or datetime.min.replace(tzinfo=timezone.utc)
1289
+ if new_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)):
1290
+ grouped[key] = {
1291
+ "payload": payload,
1292
+ "sql_path": sql_path,
1293
+ "sort_dt": new_dt,
1294
+ "manifest_path": manifest_path,
1295
+ }
1296
+ return grouped
1297
+
1298
+
1299
+ def _current_query_manifest_path(
1300
+ *,
1301
+ run_id: str,
1302
+ dataset_id: str,
1303
+ query_record_id: str,
1304
+ sql_source_version: str,
1305
+ ) -> Path:
1306
+ normalized = normalize_line_version(sql_source_version)
1307
+ return run_manifest_dir(run_id, dataset_id, line_version=normalized) / query_record_id / "run_manifest.json"
1308
+
1309
+
1310
+ def _load_latest_current_sql_query_groups(
1311
+ *,
1312
+ sql_source_version: str,
1313
+ dataset_ids: Iterable[str] | None = None,
1314
+ engines: tuple[str, ...] = ("cli",),
1315
+ require_accepted_for_eval: bool = True,
1316
+ ) -> dict[tuple[str, str], dict[str, Any]]:
1317
+ grouped: dict[tuple[str, str], dict[str, Any]] = {}
1318
+ normalized = normalize_sql_source_version(sql_source_version)
1319
+ registry_root = registry_dir(normalized)
1320
+ if not registry_root.exists():
1321
+ return grouped
1322
+
1323
+ dataset_filter = {str(item).strip() for item in dataset_ids or [] if str(item).strip()}
1324
+ for registry_path in sorted(registry_root.glob(f"*_query_registry_{normalized}.jsonl")):
1325
+ for row in load_registry_rows(registry_path):
1326
+ dataset_id = str(row.get("dataset_id") or "").strip()
1327
+ if not dataset_id:
1328
+ continue
1329
+ if dataset_filter and dataset_id not in dataset_filter:
1330
+ continue
1331
+ engine = str(row.get("engine") or "").strip()
1332
+ if engines and engine not in engines:
1333
+ continue
1334
+ if require_accepted_for_eval and not bool(row.get("accepted_for_eval")):
1335
+ continue
1336
+ query_record_id = str(row.get("query_record_id") or "").strip()
1337
+ if not query_record_id:
1338
+ continue
1339
+ sql_path = _resolve_registry_backed_path(row.get("sql_path"))
1340
+ if not sql_path.exists():
1341
+ continue
1342
+ run_id = str(row.get("round_id") or "").strip()
1343
+ manifest_path = _current_query_manifest_path(
1344
+ run_id=run_id,
1345
+ dataset_id=dataset_id,
1346
+ query_record_id=query_record_id,
1347
+ sql_source_version=normalized,
1348
+ )
1349
+ manifest = read_json(manifest_path, {}) or {}
1350
+ sort_dt = (
1351
+ parse_timestamp_text(str(manifest.get("ended_at") or manifest.get("started_at") or ""))
1352
+ or _stat_mtime_ts(sql_path)
1353
+ or _stat_mtime_ts(manifest_path)
1354
+ or _stat_mtime_ts(registry_path)
1355
+ or datetime.min.replace(tzinfo=timezone.utc)
1356
+ )
1357
+ key = (dataset_id, query_record_id)
1358
+ current = grouped.get(key)
1359
+ if current is None or sort_dt >= current.get("sort_dt", datetime.min.replace(tzinfo=timezone.utc)):
1360
+ grouped[key] = {
1361
+ "row": row,
1362
+ "sql_path": sql_path,
1363
+ "registry_path": registry_path,
1364
+ "manifest_path": manifest_path,
1365
+ "manifest": manifest,
1366
+ "sql_source_version": normalized,
1367
+ "sort_dt": sort_dt,
1368
+ }
1369
+ return grouped
1370
+
1371
+
1372
+ def load_latest_sql_queries_by_dataset(
1373
+ *,
1374
+ dataset_ids: Iterable[str],
1375
+ engines: tuple[str, ...] = ("cli",),
1376
+ include_all_statements: bool = True,
1377
+ sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,
1378
+ ) -> dict[str, list[dict[str, Any]]]:
1379
+ dataset_ids = [str(item).strip() for item in dataset_ids if str(item).strip()]
1380
+ normalized_source = normalize_sql_source_version(sql_source_version)
1381
+ rows_by_dataset: dict[str, list[dict[str, Any]]] = defaultdict(list)
1382
+ if normalized_source == SQL_SOURCE_VERSION_V1:
1383
+ grouped = _load_latest_v1_sql_query_groups(dataset_ids=dataset_ids, engines=engines)
1384
+ for (dataset_id, question_id), item in sorted(grouped.items()):
1385
+ payload = item["payload"]
1386
+ sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore")
1387
+ sql_file_hash = _sha256_text(sql_text)
1388
+ statements = split_sql_statements(sql_text)
1389
+ if not statements:
1390
+ continue
1391
+ if not include_all_statements:
1392
+ statements = statements[:1]
1393
+ question_record = payload.get("question_record") or {}
1394
+ provenance = build_sql_source_provenance(
1395
+ sql_source_version=SQL_SOURCE_VERSION_V1,
1396
+ sql_source_kind="legacy_grounded_run_manifest",
1397
+ sql_source_selection_mode="latest_per_question_id",
1398
+ source_run_id=str(payload.get("run_id") or ""),
1399
+ sql_file_path=item["sql_path"],
1400
+ manifest_path=item["manifest_path"],
1401
+ run_dir=item["manifest_path"].parent,
1402
+ declared_version=str(payload.get("sql_source_version") or ""),
1403
+ declared_label=str(payload.get("sql_source_label") or ""),
1404
+ sql_file_sha256=sql_file_hash,
1405
+ )
1406
+ for idx, statement in enumerate(statements, start=1):
1407
+ rows_by_dataset[dataset_id].append(
1408
+ {
1409
+ "dataset_id": dataset_id,
1410
+ "question_id": question_id,
1411
+ "query_id": f"{question_id}__sql{idx}",
1412
+ "sql_index": idx,
1413
+ "question": str(payload.get("question") or question_record.get("question") or ""),
1414
+ "template_id": str(question_record.get("template_id") or ""),
1415
+ "template_name": str(question_record.get("template_name") or ""),
1416
+ "family_id": str(question_record.get("primary_family") or ""),
1417
+ "canonical_subitem_id": str(question_record.get("canonical_subitem_id") or ""),
1418
+ "intended_facet_id": str(question_record.get("intended_facet_id") or ""),
1419
+ "variant_semantic_role": str(question_record.get("variant_semantic_role") or ""),
1420
+ "stable_question_id": str(question_record.get("stable_question_id") or ""),
1421
+ "query_identity_stable_key": str(question_record.get("query_identity_stable_key") or ""),
1422
+ "source_run_id": str(payload.get("run_id") or ""),
1423
+ "engine": str(payload.get("engine") or ""),
1424
+ "model": str(payload.get("model") or ""),
1425
+ "sql": statement,
1426
+ **provenance,
1427
+ }
1428
+ )
1429
+ else:
1430
+ grouped = _load_latest_current_sql_query_groups(
1431
+ sql_source_version=normalized_source,
1432
+ dataset_ids=dataset_ids,
1433
+ engines=engines,
1434
+ require_accepted_for_eval=True,
1435
+ )
1436
+ for (dataset_id, query_record_id), item in sorted(grouped.items()):
1437
+ row = item["row"]
1438
+ manifest = item["manifest"] if isinstance(item.get("manifest"), dict) else {}
1439
+ question_record = manifest.get("question_record") if isinstance(manifest, dict) else {}
1440
+ sql_text = item["sql_path"].read_text(encoding="utf-8", errors="ignore")
1441
+ sql_file_hash = str(row.get("sql_sha256") or "") or _sha256_text(sql_text)
1442
+ statements = split_sql_statements(sql_text)
1443
+ if not statements:
1444
+ continue
1445
+ if not include_all_statements:
1446
+ statements = statements[:1]
1447
+ declared_version = str(row.get("sql_source_version") or manifest.get("sql_source_version") or "")
1448
+ declared_label = str(row.get("sql_source_label") or manifest.get("sql_source_label") or "")
1449
+ run_id = str(row.get("round_id") or "")
1450
+ current_runs_root = runs_root(normalized_source)
1451
+ run_root = current_runs_root / run_id
1452
+ dataset_dir = run_root / dataset_id
1453
+ provenance = build_sql_source_provenance(
1454
+ sql_source_version=normalized_source,
1455
+ sql_source_kind="current_query_registry",
1456
+ sql_source_selection_mode="latest_per_query_record_id",
1457
+ source_run_id=run_id,
1458
+ sql_file_path=item["sql_path"],
1459
+ manifest_path=item["manifest_path"],
1460
+ registry_path=item["registry_path"],
1461
+ run_dir=run_root,
1462
+ dataset_dir=dataset_dir,
1463
+ registry_version=str(row.get("registry_version") or ""),
1464
+ declared_version=declared_version,
1465
+ declared_label=declared_label,
1466
+ sql_file_sha256=sql_file_hash,
1467
+ )
1468
+ for idx, statement in enumerate(statements, start=1):
1469
+ query_id = query_record_id if len(statements) == 1 else f"{query_record_id}__sql{idx}"
1470
+ rows_by_dataset[dataset_id].append(
1471
+ {
1472
+ "dataset_id": dataset_id,
1473
+ "question_id": query_record_id,
1474
+ "query_id": query_id,
1475
+ "sql_index": idx,
1476
+ "question": str(row.get("question_text") or question_record.get("question") or ""),
1477
+ "template_id": str(row.get("template_id") or question_record.get("template_id") or ""),
1478
+ "template_name": str(row.get("template_name") or question_record.get("template_name") or ""),
1479
+ "family_id": str(row.get("family_id") or question_record.get("family_id") or ""),
1480
+ "canonical_subitem_id": str(row.get("canonical_subitem_id") or question_record.get("canonical_subitem_id") or ""),
1481
+ "intended_facet_id": str(row.get("intended_facet_id") or question_record.get("intended_facet_id") or ""),
1482
+ "variant_semantic_role": str(row.get("variant_semantic_role") or question_record.get("variant_semantic_role") or ""),
1483
+ "stable_question_id": query_record_id,
1484
+ "query_identity_stable_key": str(row.get("query_identity_stable_key") or f"{dataset_id}::{query_record_id}"),
1485
+ "source_run_id": run_id,
1486
+ "engine": str(row.get("engine") or manifest.get("engine") or ""),
1487
+ "model": str(manifest.get("model") or ""),
1488
+ "sql": statement,
1489
+ "accepted_for_eval": bool(row.get("accepted_for_eval")),
1490
+ **provenance,
1491
+ }
1492
+ )
1493
+ return {dataset_id: rows_by_dataset.get(dataset_id, []) for dataset_id in dataset_ids}
1494
+
1495
+
1496
+ def load_latest_sql_queries(
1497
+ *,
1498
+ dataset_id: str,
1499
+ engines: tuple[str, ...] = ("cli",),
1500
+ include_all_statements: bool = True,
1501
+ sql_source_version: str = DEFAULT_SQL_SOURCE_VERSION,
1502
+ ) -> list[dict[str, Any]]:
1503
+ return load_latest_sql_queries_by_dataset(
1504
+ dataset_ids=[dataset_id],
1505
+ engines=engines,
1506
+ include_all_statements=include_all_statements,
1507
+ sql_source_version=sql_source_version,
1508
+ ).get(dataset_id, [])
1509
+
1510
+
1511
+ def materialize_csv_to_sqlite(csv_path: Path, sqlite_path: Path, table_name: str) -> None:
1512
+ if sqlite_path.exists():
1513
+ sqlite_path.unlink()
1514
+ sqlite_path.parent.mkdir(parents=True, exist_ok=True)
1515
+
1516
+ def _sqlite_ident(name: str) -> str:
1517
+ return f'"{str(name).replace("\"", "\"\"")}"'
1518
+
1519
+ def _sniff_delimiter(path: Path) -> str:
1520
+ try:
1521
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
1522
+ sample = handle.read(4096)
1523
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
1524
+ return dialect.delimiter
1525
+ except Exception:
1526
+ return ","
1527
+
1528
+ def _repair_single_field_row(row: list[str], delimiter: str) -> list[str]:
1529
+ if len(row) != 1:
1530
+ return row
1531
+ cell = str(row[0] or "")
1532
+ if delimiter not in cell:
1533
+ return row
1534
+ repaired = cell.strip()
1535
+ if repaired.startswith('"') and repaired.endswith('"') and len(repaired) >= 2:
1536
+ repaired = repaired[1:-1]
1537
+ repaired = repaired.replace('""', '"')
1538
+ try:
1539
+ return next(csv.reader([repaired], delimiter=delimiter))
1540
+ except Exception:
1541
+ return repaired.split(delimiter)
1542
+
1543
+ def _infer_header_from_synthetic(dataset_id: str, width: int) -> list[str] | None:
1544
+ try:
1545
+ assets = discover_synthetic_assets(
1546
+ datasets=[dataset_id],
1547
+ root_names=["TabQueryBench-SynDataSuccess-main"],
1548
+ )
1549
+ except Exception:
1550
+ return None
1551
+ for asset in assets:
1552
+ synthetic_path = Path(asset.synthetic_csv_path)
1553
+ if not synthetic_path.exists():
1554
+ continue
1555
+ try:
1556
+ delimiter = _sniff_delimiter(synthetic_path)
1557
+ with synthetic_path.open("r", encoding="utf-8-sig", newline="") as synthetic_file:
1558
+ synthetic_reader = csv.reader(synthetic_file, delimiter=delimiter)
1559
+ synthetic_headers = next(synthetic_reader, [])
1560
+ except Exception:
1561
+ continue
1562
+ normalized = [str(header or "").strip() for header in synthetic_headers]
1563
+ if len(normalized) == width and all(normalized):
1564
+ return normalized
1565
+ return None
1566
+
1567
+ def _normalize_headers(first_row: list[str]) -> tuple[list[str], bool]:
1568
+ cleaned = [str(header or "").strip() for header in first_row]
1569
+ counts = Counter(cleaned)
1570
+ has_duplicates = any(name and count > 1 for name, count in counts.items())
1571
+ has_empty = any(not name for name in cleaned)
1572
+ if has_duplicates or has_empty:
1573
+ inferred = _infer_header_from_synthetic(table_name, len(first_row))
1574
+ if inferred:
1575
+ return inferred, True
1576
+ return [f"col_{idx}" for idx in range(1, len(first_row) + 1)], True
1577
+ return cleaned, False
1578
+
1579
+ conn = sqlite3.connect(sqlite_path)
1580
+ try:
1581
+ cur = conn.cursor()
1582
+ delimiter = _sniff_delimiter(csv_path)
1583
+ with csv_path.open("r", encoding="utf-8-sig", newline="") as f:
1584
+ reader = csv.reader(f, delimiter=delimiter)
1585
+ first_row = _repair_single_field_row(next(reader, []), delimiter)
1586
+ if not first_row:
1587
+ raise ValueError(f"Empty header: {csv_path}")
1588
+ headers, headerless = _normalize_headers(first_row)
1589
+ col_defs = ", ".join([f"{_sqlite_ident(header)} TEXT" for header in headers])
1590
+ cur.execute(f"DROP TABLE IF EXISTS {_sqlite_ident(table_name)}")
1591
+ cur.execute(f"CREATE TABLE {_sqlite_ident(table_name)} ({col_defs})")
1592
+ placeholders = ",".join(["?" for _ in headers])
1593
+ insert_sql = f"INSERT INTO {_sqlite_ident(table_name)} VALUES ({placeholders})"
1594
+ batch: list[list[str]] = []
1595
+ if headerless:
1596
+ row = list(first_row)
1597
+ if len(row) < len(headers):
1598
+ row = row + [""] * (len(headers) - len(row))
1599
+ elif len(row) > len(headers):
1600
+ row = row[: len(headers)]
1601
+ batch.append(row)
1602
+ for row in reader:
1603
+ row = _repair_single_field_row(row, delimiter)
1604
+ if len(row) < len(headers):
1605
+ row = row + [""] * (len(headers) - len(row))
1606
+ elif len(row) > len(headers):
1607
+ row = row[: len(headers)]
1608
+ batch.append(row)
1609
+ if len(batch) >= 1000:
1610
+ cur.executemany(insert_sql, batch)
1611
+ batch.clear()
1612
+ if batch:
1613
+ cur.executemany(insert_sql, batch)
1614
+ conn.commit()
1615
+ finally:
1616
+ conn.close()
1617
+
1618
+
1619
+ def normalize_missing(value: Any) -> bool:
1620
+ if value is None:
1621
+ return True
1622
+ return str(value).strip().lower() in MISSING_TEXT
1623
+
1624
+
1625
+ def mean_or_none(values: Iterable[float | None]) -> float | None:
1626
+ cleaned = [float(value) for value in values if value is not None and not math.isnan(float(value))]
1627
+ if not cleaned:
1628
+ return None
1629
+ return sum(cleaned) / len(cleaned)
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Cardinality/range dynamic analysis outputs and runners."""
2
+
3
+ from .runner import main
4
+
5
+ __all__ = ["main"]
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/cardinality/runner.py ADDED
The diff for this file is too large to render. See raw diff
 
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_final.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import Iterable, Mapping
6
+
7
+
8
+ def versioned_name(filename: str, version_tag: str) -> str:
9
+ path = Path(str(filename))
10
+ suffix = path.suffix
11
+ stem = path.stem if suffix else path.name
12
+ tagged = f"{stem}__{version_tag}"
13
+ return f"{tagged}{suffix}" if suffix else tagged
14
+
15
+
16
+ def _copy_file(src: Path, dst: Path) -> None:
17
+ if not src.exists():
18
+ return
19
+ dst.parent.mkdir(parents=True, exist_ok=True)
20
+ try:
21
+ if src.resolve() == dst.resolve():
22
+ return
23
+ except FileNotFoundError:
24
+ pass
25
+ shutil.copy2(src, dst)
26
+
27
+
28
+ def sync_final_outputs(
29
+ final_dir: Path,
30
+ files: Iterable[Path],
31
+ must_do_aliases: Mapping[str, Path] | None = None,
32
+ *,
33
+ version_tag: str | None = None,
34
+ copy_plain_files: bool = True,
35
+ ) -> None:
36
+ final_dir.mkdir(parents=True, exist_ok=True)
37
+ must_do_dir = final_dir / "must_do"
38
+ must_do_dir.mkdir(parents=True, exist_ok=True)
39
+ version_dir = final_dir / str(version_tag) if version_tag else None
40
+ version_must_do_dir = (version_dir / "must_do") if version_dir is not None else None
41
+ if version_dir is not None:
42
+ version_dir.mkdir(parents=True, exist_ok=True)
43
+ if version_must_do_dir is not None:
44
+ version_must_do_dir.mkdir(parents=True, exist_ok=True)
45
+
46
+ for src in files:
47
+ if copy_plain_files:
48
+ _copy_file(src, final_dir / src.name)
49
+ if version_tag:
50
+ tagged_name = versioned_name(src.name, str(version_tag))
51
+ _copy_file(src, final_dir / tagged_name)
52
+ if version_dir is not None:
53
+ _copy_file(src, version_dir / tagged_name)
54
+
55
+ for alias_name, src in (must_do_aliases or {}).items():
56
+ if copy_plain_files:
57
+ _copy_file(src, final_dir / alias_name)
58
+ _copy_file(src, must_do_dir / alias_name)
59
+ if version_tag:
60
+ tagged_alias = versioned_name(alias_name, str(version_tag))
61
+ _copy_file(src, final_dir / tagged_alias)
62
+ _copy_file(src, must_do_dir / tagged_alias)
63
+ if version_dir is not None:
64
+ _copy_file(src, version_dir / tagged_alias)
65
+ if version_must_do_dir is not None:
66
+ _copy_file(src, version_must_do_dir / tagged_alias)
67
+
68
+
69
+ def render_final_readme(
70
+ *,
71
+ title: str,
72
+ summary: str,
73
+ primary_files: list[str],
74
+ must_do_files: list[str],
75
+ support_files: list[str] | None = None,
76
+ notes: list[str] | None = None,
77
+ ) -> str:
78
+ lines = [
79
+ f"# {title}",
80
+ "",
81
+ summary.strip(),
82
+ "",
83
+ "Primary paper-facing files:",
84
+ "",
85
+ ]
86
+ lines.extend(f"- `{item}`" for item in primary_files)
87
+ lines.extend(
88
+ [
89
+ "",
90
+ "Must-do bundle (`must_do/`):",
91
+ "",
92
+ ]
93
+ )
94
+ lines.extend(f"- `must_do/{item}`" for item in must_do_files)
95
+ if support_files:
96
+ lines.extend(
97
+ [
98
+ "",
99
+ "Support files:",
100
+ "",
101
+ ]
102
+ )
103
+ lines.extend(f"- `{item}`" for item in support_files)
104
+ if notes:
105
+ lines.extend(["", *notes])
106
+ lines.append("")
107
+ return "\n".join(lines)
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_heatmap_palette.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+
5
+ import matplotlib
6
+
7
+ matplotlib.use("Agg")
8
+ from matplotlib import colormaps
9
+
10
+
11
+ HEATMAP_NA_HEX = "F1F1F1"
12
+
13
+ _BASE_HEATMAP_CMAP = colormaps["YlGnBu"].copy()
14
+ _BASE_HEATMAP_CMAP.set_bad(f"#{HEATMAP_NA_HEX}")
15
+
16
+
17
+ def get_heatmap_cmap():
18
+ return _BASE_HEATMAP_CMAP
19
+
20
+
21
+ def coerce_heatmap_value(value: object) -> float | None:
22
+ if value is None:
23
+ return None
24
+ try:
25
+ numeric = float(value)
26
+ except (TypeError, ValueError):
27
+ return None
28
+ if math.isnan(numeric):
29
+ return None
30
+ return max(0.0, min(1.0, numeric))
31
+
32
+
33
+ def heatmap_hex(value: object) -> str:
34
+ numeric = coerce_heatmap_value(value)
35
+ if numeric is None:
36
+ return HEATMAP_NA_HEX
37
+ red, green, blue, _alpha = get_heatmap_cmap()(numeric)
38
+ return "".join(f"{int(round(channel * 255)):02X}" for channel in (red, green, blue))
39
+
40
+
41
+ def text_hex_for_fill(fill_hex: str) -> str:
42
+ red = int(fill_hex[0:2], 16)
43
+ green = int(fill_hex[2:4], 16)
44
+ blue = int(fill_hex[4:6], 16)
45
+ luminance = 0.2126 * red + 0.7152 * green + 0.0722 * blue
46
+ return "111111" if luminance >= 150 else "F8F8F8"
47
+
48
+
49
+ def format_heatmap_latex_cell(value: object, *, precision: int = 2, show_text: bool = False) -> str:
50
+ numeric = coerce_heatmap_value(value)
51
+ if numeric is None:
52
+ return ""
53
+ fill_hex = heatmap_hex(numeric)
54
+ if not show_text:
55
+ return rf"\cellcolor[HTML]{{{fill_hex}}}"
56
+ text_hex = text_hex_for_fill(fill_hex)
57
+ return (
58
+ rf"\cellcolor[HTML]{{{fill_hex}}}"
59
+ rf"\textcolor[HTML]{{{text_hex}}}{{{numeric:.{precision}f}}}"
60
+ )
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_grouped_bars.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Mapping, Sequence
5
+
6
+ import matplotlib
7
+
8
+ matplotlib.use("Agg")
9
+ import matplotlib.pyplot as plt
10
+ import pandas as pd
11
+
12
+
13
+ def _escape_tex(text: str) -> str:
14
+ replacements = {
15
+ "\\": r"\textbackslash{}",
16
+ "&": r"\&",
17
+ "%": r"\%",
18
+ "$": r"\$",
19
+ "#": r"\#",
20
+ "_": r"\_",
21
+ "{": r"\{",
22
+ "}": r"\}",
23
+ }
24
+ out = str(text)
25
+ for src, dst in replacements.items():
26
+ out = out.replace(src, dst)
27
+ return out
28
+
29
+
30
+ def _tex_preamble() -> str:
31
+ return "\n".join(
32
+ [
33
+ r"\documentclass[tikz,border=4pt]{standalone}",
34
+ r"\usepackage{pgfplots}",
35
+ r"\usepackage{xcolor}",
36
+ r"\pgfplotsset{compat=1.18}",
37
+ "",
38
+ ]
39
+ )
40
+
41
+
42
+ def _filtered_subitem_rows(heatmap_df: pd.DataFrame, *, include_summary_row: bool) -> pd.DataFrame:
43
+ if include_summary_row:
44
+ return heatmap_df.copy().reset_index(drop=True)
45
+ out = heatmap_df.loc[heatmap_df["subitem_id"].astype(str).str.lower() != "family_mean"].copy()
46
+ return out.reset_index(drop=True)
47
+
48
+
49
+ def _cluster_layout(
50
+ heatmap_df: pd.DataFrame,
51
+ *,
52
+ model_order: Sequence[str],
53
+ model_label_map: Mapping[str, str],
54
+ include_real_baseline: bool,
55
+ real_label: str,
56
+ real_value: float,
57
+ include_summary_row: bool,
58
+ intra_gap: float,
59
+ cluster_gap: float,
60
+ ) -> tuple[list[dict[str, object]], list[dict[str, object]], list[float]]:
61
+ plot_df = _filtered_subitem_rows(heatmap_df, include_summary_row=include_summary_row)
62
+ displayed_models = ([("__real__", real_label)] if include_real_baseline else []) + [
63
+ (model_id, model_label_map.get(model_id, model_id)) for model_id in model_order
64
+ ]
65
+
66
+ bars: list[dict[str, object]] = []
67
+ clusters: list[dict[str, object]] = []
68
+ separators: list[float] = []
69
+ cursor = 0.0
70
+ for cluster_index, row in enumerate(plot_df.itertuples(index=False)):
71
+ cluster_start = cursor
72
+ for model_key, model_label in displayed_models:
73
+ if model_key == "__real__":
74
+ value = float(real_value)
75
+ else:
76
+ raw = getattr(row, model_key, None)
77
+ value = None if raw is None or pd.isna(raw) else float(raw)
78
+ if value is None:
79
+ cursor += 1.0 + intra_gap
80
+ continue
81
+ bars.append(
82
+ {
83
+ "cluster_index": cluster_index,
84
+ "subitem_id": str(row.subitem_id),
85
+ "subitem_label": str(row.subitem_label),
86
+ "model_id": str(model_key),
87
+ "model_label": str(model_label),
88
+ "x": float(cursor),
89
+ "score": float(value),
90
+ }
91
+ )
92
+ cursor += 1.0 + intra_gap
93
+ cluster_end = cursor - (1.0 + intra_gap)
94
+ clusters.append(
95
+ {
96
+ "cluster_index": cluster_index,
97
+ "subitem_id": str(row.subitem_id),
98
+ "subitem_label": str(row.subitem_label),
99
+ "start_x": float(cluster_start),
100
+ "end_x": float(cluster_end),
101
+ "center_x": float((cluster_start + cluster_end) / 2.0),
102
+ }
103
+ )
104
+ if cluster_index < len(plot_df) - 1:
105
+ separators.append(float(cursor - intra_gap / 2.0 + cluster_gap / 2.0))
106
+ cursor += cluster_gap
107
+ return bars, clusters, separators
108
+
109
+
110
+ def write_model_subitem_grouped_bar_tex(
111
+ heatmap_df: pd.DataFrame,
112
+ *,
113
+ model_order: Sequence[str],
114
+ model_label_map: Mapping[str, str],
115
+ model_color_map: Mapping[str, str],
116
+ title: str,
117
+ y_label: str,
118
+ path: Path,
119
+ include_real_baseline: bool = True,
120
+ real_label: str = "REAL",
121
+ real_value: float = 1.0,
122
+ include_summary_row: bool = False,
123
+ intra_gap: float = 0.10,
124
+ cluster_gap: float = 1.35,
125
+ ) -> None:
126
+ if heatmap_df.empty:
127
+ path.write_text("", encoding="utf-8")
128
+ return
129
+
130
+ bars, clusters, separators = _cluster_layout(
131
+ heatmap_df,
132
+ model_order=model_order,
133
+ model_label_map=model_label_map,
134
+ include_real_baseline=include_real_baseline,
135
+ real_label=real_label,
136
+ real_value=real_value,
137
+ include_summary_row=include_summary_row,
138
+ intra_gap=intra_gap,
139
+ cluster_gap=cluster_gap,
140
+ )
141
+ if not bars:
142
+ path.write_text("", encoding="utf-8")
143
+ return
144
+
145
+ label_lookup = {}
146
+ for item in bars:
147
+ label_lookup[float(item["x"])] = str(item["model_label"])
148
+ x_positions = [float(item["x"]) for item in bars]
149
+ x_labels = [label_lookup[pos] for pos in x_positions]
150
+ max_x = max(x_positions) + 1.0
151
+
152
+ color_defs = []
153
+ for model_id in ["__real__", *model_order]:
154
+ color = "#000000" if model_id == "__real__" else str(model_color_map.get(model_id, "#777777"))
155
+ color_defs.append(rf"\definecolor{{bar{model_id.replace('_', '').replace('-', '')}}}{{HTML}}{{{color.replace('#', '')}}}")
156
+
157
+ lines = [
158
+ _tex_preamble(),
159
+ *color_defs,
160
+ r"\begin{document}",
161
+ r"\begin{tikzpicture}",
162
+ r"\begin{axis}[",
163
+ rf"width={max(13.5, 0.32 * len(x_positions) + 3.6):.2f}cm,",
164
+ r"height=8.8cm,",
165
+ r"ymin=0.0, ymax=1.08,",
166
+ rf"ylabel={{{_escape_tex(y_label)}}},",
167
+ rf"title={{{_escape_tex(title)}}},",
168
+ r"ymajorgrids,",
169
+ r"grid style={draw=gray!22},",
170
+ r"major grid style={draw=gray!30},",
171
+ r"axis line style={draw=black!70},",
172
+ r"tick style={draw=black!70},",
173
+ rf"xtick={{{','.join(f'{item:.4f}' for item in x_positions)}}},",
174
+ rf"xticklabels={{{','.join(_escape_tex(item) for item in x_labels)}}},",
175
+ r"x tick label style={rotate=90, anchor=east, font=\scriptsize},",
176
+ r"enlarge x limits=0.01,",
177
+ r"clip=false,",
178
+ r"]",
179
+ ]
180
+ for item in bars:
181
+ model_id = str(item["model_id"])
182
+ color_name = f"bar{model_id.replace('_', '').replace('-', '')}"
183
+ lines.append(
184
+ rf"\addplot+[ybar, bar width=5.8pt, draw={color_name}, fill={color_name}] coordinates {{({float(item['x']):.4f},{float(item['score']):.6f})}};"
185
+ )
186
+ for sep in separators:
187
+ lines.append(rf"\draw[dashed, gray!70, line width=0.6pt] (axis cs:{sep:.4f},0) -- (axis cs:{sep:.4f},1.08);")
188
+ for cluster in clusters:
189
+ lines.append(
190
+ rf"\node[anchor=south, font=\bfseries\small] at (axis cs:{float(cluster['center_x']):.4f},1.035) {{{_escape_tex(str(cluster['subitem_label']))}}};"
191
+ )
192
+ lines.extend([r"\end{axis}", r"\end{tikzpicture}", r"\end{document}", ""])
193
+ path.write_text("\n".join(lines), encoding="utf-8")
194
+
195
+
196
+ def plot_model_subitem_grouped_bar_preview(
197
+ heatmap_df: pd.DataFrame,
198
+ *,
199
+ model_order: Sequence[str],
200
+ model_label_map: Mapping[str, str],
201
+ model_color_map: Mapping[str, str],
202
+ title: str,
203
+ y_label: str,
204
+ pdf_path: Path,
205
+ png_path: Path,
206
+ include_real_baseline: bool = True,
207
+ real_label: str = "REAL",
208
+ real_value: float = 1.0,
209
+ include_summary_row: bool = False,
210
+ intra_gap: float = 0.10,
211
+ cluster_gap: float = 1.35,
212
+ ) -> None:
213
+ if heatmap_df.empty:
214
+ return
215
+
216
+ bars, clusters, separators = _cluster_layout(
217
+ heatmap_df,
218
+ model_order=model_order,
219
+ model_label_map=model_label_map,
220
+ include_real_baseline=include_real_baseline,
221
+ real_label=real_label,
222
+ real_value=real_value,
223
+ include_summary_row=include_summary_row,
224
+ intra_gap=intra_gap,
225
+ cluster_gap=cluster_gap,
226
+ )
227
+ if not bars:
228
+ return
229
+
230
+ x_positions = [float(item["x"]) for item in bars]
231
+ values = [float(item["score"]) for item in bars]
232
+ x_labels = [str(item["model_label"]) for item in bars]
233
+ colors = ["#000000" if str(item["model_id"]) == "__real__" else str(model_color_map.get(str(item["model_id"]), "#777777")) for item in bars]
234
+
235
+ fig_width = max(14.0, 0.33 * len(x_positions) + 3.8)
236
+ fig, ax = plt.subplots(figsize=(fig_width, 7.9))
237
+ ax.bar(x_positions, values, width=0.90, color=colors, edgecolor=colors, linewidth=0.8)
238
+ for sep in separators:
239
+ ax.axvline(sep, color="#666666", linestyle="--", linewidth=1.0, alpha=0.75)
240
+ for cluster in clusters:
241
+ ax.text(
242
+ float(cluster["center_x"]),
243
+ 1.035,
244
+ str(cluster["subitem_label"]),
245
+ ha="center",
246
+ va="bottom",
247
+ fontsize=11,
248
+ fontweight="bold",
249
+ )
250
+
251
+ ax.set_ylim(0.0, 1.08)
252
+ ax.set_ylabel(y_label)
253
+ ax.set_title(title)
254
+ ax.set_xticks(x_positions)
255
+ ax.set_xticklabels(x_labels, rotation=90, ha="center", va="top", fontsize=8)
256
+ ax.grid(axis="y", alpha=0.24)
257
+ ax.margins(x=0.01)
258
+ fig.tight_layout()
259
+ fig.savefig(pdf_path, bbox_inches="tight")
260
+ fig.savefig(png_path, dpi=260, bbox_inches="tight")
261
+ plt.close(fig)
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/common_model_subitem_heatmap.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Mapping, Sequence
5
+
6
+ import matplotlib
7
+
8
+ matplotlib.use("Agg")
9
+ import matplotlib.pyplot as plt
10
+ import pandas as pd
11
+
12
+ from src.eval.query_fivepart_breakdown.common_heatmap_palette import (
13
+ format_heatmap_latex_cell,
14
+ get_heatmap_cmap,
15
+ )
16
+
17
+
18
+ def _escape_tex(text: str) -> str:
19
+ replacements = {
20
+ "\\": r"\textbackslash{}",
21
+ "&": r"\&",
22
+ "%": r"\%",
23
+ "$": r"\$",
24
+ "#": r"\#",
25
+ "_": r"\_",
26
+ "{": r"\{",
27
+ "}": r"\}",
28
+ }
29
+ out = str(text)
30
+ for src, dst in replacements.items():
31
+ out = out.replace(src, dst)
32
+ return out
33
+
34
+
35
+ def _tex_preamble() -> str:
36
+ return "\n".join(
37
+ [
38
+ r"\documentclass{standalone}",
39
+ r"\usepackage[table]{xcolor}",
40
+ r"\usepackage{xcolor}",
41
+ r"\usepackage{booktabs}",
42
+ "",
43
+ ]
44
+ )
45
+
46
+
47
+ def build_model_subitem_heatmap_df(
48
+ summary_df: pd.DataFrame,
49
+ *,
50
+ model_id_col: str,
51
+ model_order: Sequence[str],
52
+ subitem_specs: Sequence[tuple[str, str, str]],
53
+ summary_row_spec: tuple[str, str, str] | None = None,
54
+ ) -> pd.DataFrame:
55
+ columns = ["subitem_id", "subitem_label", *model_order]
56
+ if summary_df.empty:
57
+ return pd.DataFrame(columns=columns)
58
+ indexed = summary_df.set_index(model_id_col, drop=False)
59
+ rows: list[dict[str, float | str | None]] = []
60
+ for subitem_id, subitem_label, mean_col in subitem_specs:
61
+ payload: dict[str, float | str | None] = {
62
+ "subitem_id": subitem_id,
63
+ "subitem_label": subitem_label,
64
+ }
65
+ for model_id in model_order:
66
+ value = None
67
+ if model_id in indexed.index and mean_col in indexed.columns:
68
+ raw = indexed.loc[model_id, mean_col]
69
+ if isinstance(raw, pd.Series):
70
+ raw = raw.iloc[0]
71
+ value = float(raw) if pd.notna(raw) else None
72
+ payload[model_id] = value
73
+ rows.append(payload)
74
+ if summary_row_spec is not None:
75
+ subitem_id, subitem_label, mean_col = summary_row_spec
76
+ payload = {
77
+ "subitem_id": subitem_id,
78
+ "subitem_label": subitem_label,
79
+ }
80
+ for model_id in model_order:
81
+ value = None
82
+ if model_id in indexed.index and mean_col in indexed.columns:
83
+ raw = indexed.loc[model_id, mean_col]
84
+ if isinstance(raw, pd.Series):
85
+ raw = raw.iloc[0]
86
+ value = float(raw) if pd.notna(raw) else None
87
+ payload[model_id] = value
88
+ rows.append(payload)
89
+ return pd.DataFrame(rows, columns=columns)
90
+
91
+
92
+ def write_model_subitem_heatmap_tex(
93
+ heatmap_df: pd.DataFrame,
94
+ *,
95
+ model_order: Sequence[str],
96
+ model_label_map: Mapping[str, str],
97
+ title: str,
98
+ colorbar_title: str,
99
+ path: Path,
100
+ ) -> None:
101
+ if heatmap_df.empty:
102
+ path.write_text("", encoding="utf-8")
103
+ return
104
+
105
+ n_cols = len(model_order)
106
+ lines = [
107
+ _tex_preamble(),
108
+ r"\begin{document}",
109
+ r"\scriptsize",
110
+ rf"\textbf{{{_escape_tex(title)}}}\\[0.4em]",
111
+ rf"\emph{{{_escape_tex(colorbar_title)}, 0--1; missing cells stay white.}}\\[0.5em]",
112
+ r"\setlength{\tabcolsep}{4pt}",
113
+ rf"\begin{{tabular}}{{l{'c' * n_cols}}}",
114
+ r"\toprule",
115
+ "Subitem & " + " & ".join(_escape_tex(model_label_map.get(model_id, model_id)) for model_id in model_order) + r" \\",
116
+ r"\midrule",
117
+ ]
118
+ for row_index, row in enumerate(heatmap_df.itertuples(index=False), start=1):
119
+ _ = row_index
120
+ cells = [_escape_tex(getattr(row, "subitem_label"))]
121
+ for model_id in model_order:
122
+ value = getattr(row, model_id)
123
+ cells.append(format_heatmap_latex_cell(value))
124
+ lines.append(" & ".join(cells) + r" \\")
125
+ lines.extend([r"\bottomrule", r"\end{tabular}", r"\end{document}", ""])
126
+ path.write_text("\n".join(lines), encoding="utf-8")
127
+
128
+
129
+ def plot_model_subitem_heatmap_preview(
130
+ heatmap_df: pd.DataFrame,
131
+ *,
132
+ model_order: Sequence[str],
133
+ model_label_map: Mapping[str, str],
134
+ title: str,
135
+ pdf_path: Path,
136
+ png_path: Path,
137
+ ) -> None:
138
+ if heatmap_df.empty:
139
+ return
140
+ plot_df = heatmap_df.copy()
141
+ value_matrix = plot_df[model_order].to_numpy(dtype=float)
142
+ fig_height = max(3.8, 0.72 * len(plot_df) + 1.9)
143
+ fig, ax = plt.subplots(figsize=(14.0, fig_height))
144
+ image = ax.imshow(value_matrix, aspect="auto", vmin=0.0, vmax=1.0, cmap=get_heatmap_cmap())
145
+ ax.set_xticks(range(len(model_order)))
146
+ ax.set_xticklabels([model_label_map.get(model_id, model_id) for model_id in model_order], rotation=45, ha="right", fontsize=9)
147
+ ax.set_yticks(range(len(plot_df)))
148
+ ax.set_yticklabels(plot_df["subitem_label"], fontsize=10)
149
+ ax.set_title(title)
150
+ cbar = fig.colorbar(image, ax=ax, fraction=0.03, pad=0.02)
151
+ cbar.set_label("Mean score")
152
+ fig.tight_layout()
153
+ fig.savefig(pdf_path, bbox_inches="tight")
154
+ fig.savefig(png_path, dpi=260, bbox_inches="tight")
155
+ plt.close(fig)
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Missingness breakdown task."""
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Experimental pairwise-centered co-missing diagnostic."""
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/pairwise_centered_diagnostic/runner.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Experimental missingness diagnostic using missing-target pairs and centered profiles."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections import defaultdict
7
+ from concurrent.futures import ThreadPoolExecutor, as_completed
8
+ from functools import lru_cache
9
+ import os
10
+ from os import cpu_count
11
+ from pathlib import Path
12
+ import sys
13
+ from typing import Any
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ PROJECT_ROOT = Path(__file__).resolve().parents[5]
19
+ if str(PROJECT_ROOT) not in sys.path:
20
+ sys.path.insert(0, str(PROJECT_ROOT))
21
+
22
+ from src.eval.common import normalize_missing, write_csv
23
+ from tests.comissing_condition_eval import _clip01, _load_real_df, build_dataset_context
24
+
25
+ OUTPUT_ROOT = (
26
+ PROJECT_ROOT
27
+ / "Evaluation"
28
+ / "query_fivepart_breakdown"
29
+ / "missingness_breakdown"
30
+ / "pairwise_centered_diagnostic"
31
+ )
32
+ DATA_DIR = OUTPUT_ROOT / "data"
33
+ FINAL_DIR = OUTPUT_ROOT / "final"
34
+ CURRENT_ASSET_CSV = (
35
+ PROJECT_ROOT
36
+ / "Evaluation"
37
+ / "query_fivepart_breakdown"
38
+ / "missingness_breakdown"
39
+ / "data"
40
+ / "direct_asset_scores.csv"
41
+ )
42
+ EMIT_PAIR_ROWS = os.environ.get("PAIRWISE_CENTERED_EMIT_PAIR_ROWS", "").strip().lower() in {"1", "true", "yes"}
43
+ MODEL_ALIASES = {"rtf": "realtabformer"}
44
+ PREFERRED_MODEL_ORDER = [
45
+ "arf",
46
+ "bayesnet",
47
+ "cdtd",
48
+ "codi",
49
+ "ctgan",
50
+ "forestdiffusion",
51
+ "goggle",
52
+ "realtabformer",
53
+ "tabbyflow",
54
+ "tabddpm",
55
+ "tabdiff",
56
+ "tabpfgen",
57
+ "tabsyn",
58
+ "tvae",
59
+ ]
60
+ MODEL_LABELS = {
61
+ "arf": "ARF",
62
+ "bayesnet": "BayesNet",
63
+ "cdtd": "CDTD",
64
+ "codi": "CoDi",
65
+ "ctgan": "CTGAN",
66
+ "forestdiffusion": "ForestDiffusion",
67
+ "goggle": "GOGGLE",
68
+ "realtabformer": "RealTabFormer",
69
+ "tabbyflow": "TabbyFlow",
70
+ "tabddpm": "TabDDPM",
71
+ "tabdiff": "TabDiff",
72
+ "tabpfgen": "TabPFGen",
73
+ "tabsyn": "TabSyn",
74
+ "tvae": "TVAE",
75
+ }
76
+
77
+
78
+ def _ensure_dirs() -> None:
79
+ for path in (OUTPUT_ROOT, DATA_DIR, FINAL_DIR):
80
+ path.mkdir(parents=True, exist_ok=True)
81
+
82
+
83
+ def _normalize_model(model_id: Any) -> str:
84
+ key = str(model_id or "").strip().lower()
85
+ return MODEL_ALIASES.get(key, key)
86
+
87
+
88
+ def _model_label(model_id: str) -> str:
89
+ return MODEL_LABELS.get(model_id, model_id)
90
+
91
+
92
+ def _model_sort_key(model_id: str) -> tuple[int, str]:
93
+ if model_id in PREFERRED_MODEL_ORDER:
94
+ return (PREFERRED_MODEL_ORDER.index(model_id), model_id)
95
+ return (len(PREFERRED_MODEL_ORDER), model_id)
96
+
97
+
98
+ def _dataset_prefix(dataset_id: str) -> str:
99
+ text = str(dataset_id or "").strip().lower()
100
+ if not text:
101
+ return "?"
102
+ return text[0]
103
+
104
+
105
+ def _binary_missing_indicator(series: pd.Series) -> np.ndarray:
106
+ return series.map(normalize_missing).to_numpy(dtype=float)
107
+
108
+
109
+ def _ordered_centered_profile_score_from_counts(
110
+ *,
111
+ target_idx: int,
112
+ related_idx: int,
113
+ real_row_count: int,
114
+ syn_row_count: int,
115
+ real_missing_counts: np.ndarray,
116
+ syn_missing_counts: np.ndarray,
117
+ real_joint_missing_counts: np.ndarray,
118
+ syn_joint_missing_counts: np.ndarray,
119
+ ) -> tuple[float, dict[str, Any]]:
120
+ real_target_rate = float(real_missing_counts[target_idx] / max(real_row_count, 1))
121
+ syn_target_rate = float(syn_missing_counts[target_idx] / max(syn_row_count, 1))
122
+
123
+ real_related_missing = float(real_missing_counts[related_idx])
124
+ real_related_nonmissing = float(real_row_count - real_related_missing)
125
+ real_state_probs = np.array(
126
+ [real_related_nonmissing / max(real_row_count, 1), real_related_missing / max(real_row_count, 1)],
127
+ dtype=float,
128
+ )
129
+
130
+ real_joint = float(real_joint_missing_counts[target_idx, related_idx])
131
+ real_cond_nonmissing = (float(real_missing_counts[target_idx]) - real_joint) / max(real_related_nonmissing, 1.0)
132
+ real_cond_missing = real_joint / max(real_related_missing, 1.0)
133
+ real_conditional_rates = np.array([real_cond_nonmissing, real_cond_missing], dtype=float)
134
+
135
+ syn_related_missing = float(syn_missing_counts[related_idx])
136
+ syn_related_nonmissing = float(syn_row_count - syn_related_missing)
137
+ syn_joint = float(syn_joint_missing_counts[target_idx, related_idx])
138
+ syn_cond_nonmissing = (float(syn_missing_counts[target_idx]) - syn_joint) / max(syn_related_nonmissing, 1.0)
139
+ syn_cond_missing = syn_joint / max(syn_related_missing, 1.0)
140
+ syn_conditional_rates = np.array([syn_cond_nonmissing, syn_cond_missing], dtype=float)
141
+ if syn_related_nonmissing <= 0:
142
+ syn_conditional_rates[0] = syn_target_rate
143
+ if syn_related_missing <= 0:
144
+ syn_conditional_rates[1] = syn_target_rate
145
+
146
+ delta_real = real_conditional_rates - real_target_rate
147
+ delta_syn = syn_conditional_rates - syn_target_rate
148
+ centered_distance = float(
149
+ real_state_probs[0] * abs(float(delta_real[0]) - float(delta_syn[0]))
150
+ + real_state_probs[1] * abs(float(delta_real[1]) - float(delta_syn[1]))
151
+ )
152
+ centered_profile_score = _clip01(1.0 - (0.5 * centered_distance))
153
+
154
+ pair_row = {
155
+ "target_missing_index": int(target_idx),
156
+ "related_missing_index": int(related_idx),
157
+ "real_target_missing_rate": round(real_target_rate, 6),
158
+ "synthetic_target_missing_rate": round(syn_target_rate, 6),
159
+ "real_conditional_nonmissing": round(float(real_conditional_rates[0]), 6),
160
+ "real_conditional_missing": round(float(real_conditional_rates[1]), 6),
161
+ "synthetic_conditional_nonmissing": round(float(syn_conditional_rates[0]), 6),
162
+ "synthetic_conditional_missing": round(float(syn_conditional_rates[1]), 6),
163
+ "real_delta_nonmissing": round(float(delta_real[0]), 6),
164
+ "real_delta_missing": round(float(delta_real[1]), 6),
165
+ "synthetic_delta_nonmissing": round(float(delta_syn[0]), 6),
166
+ "synthetic_delta_missing": round(float(delta_syn[1]), 6),
167
+ "centered_profile_distance": round(centered_distance, 6),
168
+ "pairwise_centered_ordered_score": round(float(centered_profile_score), 6),
169
+ }
170
+ return centered_profile_score, pair_row
171
+
172
+
173
+ @lru_cache(maxsize=None)
174
+ def _get_dataset_context(dataset_id: str):
175
+ return build_dataset_context(dataset_id)
176
+
177
+
178
+ @lru_cache(maxsize=None)
179
+ def _get_real_target_df(dataset_id: str, missing_targets_key: tuple[str, ...]) -> pd.DataFrame:
180
+ real_df = _load_real_df(dataset_id)
181
+ return real_df[list(missing_targets_key)].copy()
182
+
183
+
184
+ def _load_syn_target_df(synthetic_csv_path: Path, target_columns: list[str]) -> pd.DataFrame:
185
+ target_set = set(target_columns)
186
+ try:
187
+ syn_df = pd.read_csv(
188
+ synthetic_csv_path,
189
+ dtype=str,
190
+ keep_default_na=False,
191
+ usecols=lambda name: str(name) in target_set,
192
+ )
193
+ except ValueError:
194
+ syn_df = pd.read_csv(synthetic_csv_path, dtype=str, keep_default_na=False)
195
+ syn_df = syn_df[[column for column in target_columns if column in syn_df.columns]]
196
+ for column in target_columns:
197
+ if column not in syn_df.columns:
198
+ syn_df[column] = ""
199
+ return syn_df[target_columns].copy()
200
+
201
+
202
+ def _pairwise_centered_score_for_asset(dataset_id: str, synthetic_csv_path: Path) -> dict[str, Any]:
203
+ context = _get_dataset_context(dataset_id)
204
+ missing_targets = [target.column for target in context.missing_targets]
205
+ if len(missing_targets) < 2:
206
+ return {
207
+ "pairwise_centered_status": "not_applicable_fewer_than_2_missing_targets",
208
+ "pairwise_centered_comissing_score": None,
209
+ "pairwise_centered_pair_count": 0,
210
+ "pairwise_centered_ordered_edge_count": 0,
211
+ "active_missing_target_count": len(missing_targets),
212
+ "pair_rows": [],
213
+ }
214
+
215
+ real_df = _get_real_target_df(dataset_id, tuple(missing_targets))
216
+ syn_df = _load_syn_target_df(synthetic_csv_path, missing_targets)
217
+
218
+ real_row_count = len(real_df)
219
+ syn_row_count = len(syn_df)
220
+ real_matrix = np.column_stack([_binary_missing_indicator(real_df[col]) for col in missing_targets]).astype(np.float32)
221
+ syn_matrix = np.column_stack([_binary_missing_indicator(syn_df[col]) for col in missing_targets]).astype(np.float32)
222
+ real_missing_counts = real_matrix.sum(axis=0)
223
+ syn_missing_counts = syn_matrix.sum(axis=0)
224
+ real_joint_missing_counts = real_matrix.T @ real_matrix
225
+ syn_joint_missing_counts = syn_matrix.T @ syn_matrix
226
+
227
+ target_count = len(missing_targets)
228
+ real_target_rates = real_missing_counts / max(real_row_count, 1)
229
+ syn_target_rates = syn_missing_counts / max(syn_row_count, 1)
230
+
231
+ real_related_missing = real_missing_counts[np.newaxis, :]
232
+ real_related_nonmissing = (real_row_count - real_missing_counts)[np.newaxis, :]
233
+ syn_related_missing = syn_missing_counts[np.newaxis, :]
234
+ syn_related_nonmissing = (syn_row_count - syn_missing_counts)[np.newaxis, :]
235
+
236
+ real_cond_missing = np.divide(
237
+ real_joint_missing_counts,
238
+ np.maximum(real_related_missing, 1.0),
239
+ out=np.zeros_like(real_joint_missing_counts, dtype=float),
240
+ )
241
+ real_cond_nonmissing = np.divide(
242
+ real_missing_counts[:, np.newaxis] - real_joint_missing_counts,
243
+ np.maximum(real_related_nonmissing, 1.0),
244
+ out=np.zeros_like(real_joint_missing_counts, dtype=float),
245
+ )
246
+ syn_cond_missing = np.divide(
247
+ syn_joint_missing_counts,
248
+ np.maximum(syn_related_missing, 1.0),
249
+ out=np.zeros_like(syn_joint_missing_counts, dtype=float),
250
+ )
251
+ syn_cond_nonmissing = np.divide(
252
+ syn_missing_counts[:, np.newaxis] - syn_joint_missing_counts,
253
+ np.maximum(syn_related_nonmissing, 1.0),
254
+ out=np.zeros_like(syn_joint_missing_counts, dtype=float),
255
+ )
256
+
257
+ syn_missing_zero_mask = (syn_related_missing <= 0)[0]
258
+ syn_nonmissing_zero_mask = (syn_related_nonmissing <= 0)[0]
259
+ if bool(np.any(syn_missing_zero_mask)):
260
+ syn_cond_missing[:, syn_missing_zero_mask] = syn_target_rates[:, np.newaxis]
261
+ if bool(np.any(syn_nonmissing_zero_mask)):
262
+ syn_cond_nonmissing[:, syn_nonmissing_zero_mask] = syn_target_rates[:, np.newaxis]
263
+
264
+ real_delta_missing = real_cond_missing - real_target_rates[:, np.newaxis]
265
+ real_delta_nonmissing = real_cond_nonmissing - real_target_rates[:, np.newaxis]
266
+ syn_delta_missing = syn_cond_missing - syn_target_rates[:, np.newaxis]
267
+ syn_delta_nonmissing = syn_cond_nonmissing - syn_target_rates[:, np.newaxis]
268
+
269
+ real_state_prob_missing = real_related_missing / max(real_row_count, 1)
270
+ real_state_prob_nonmissing = real_related_nonmissing / max(real_row_count, 1)
271
+ centered_distance_matrix = (
272
+ real_state_prob_nonmissing * np.abs(real_delta_nonmissing - syn_delta_nonmissing)
273
+ + real_state_prob_missing * np.abs(real_delta_missing - syn_delta_missing)
274
+ )
275
+ ordered_score_matrix = np.clip(1.0 - (0.5 * centered_distance_matrix), 0.0, 1.0)
276
+ np.fill_diagonal(ordered_score_matrix, np.nan)
277
+
278
+ pair_score_matrix = 0.5 * (ordered_score_matrix + ordered_score_matrix.T)
279
+ upper_left, upper_right = np.triu_indices(target_count, k=1)
280
+ pair_scores = pair_score_matrix[upper_left, upper_right]
281
+ ordered_edge_count = int(pair_scores.size * 2)
282
+ pair_rows: list[dict[str, Any]] = []
283
+ if EMIT_PAIR_ROWS:
284
+ for left_idx, right_idx in zip(upper_left.tolist(), upper_right.tolist(), strict=False):
285
+ left_score, left_row = _ordered_centered_profile_score_from_counts(
286
+ target_idx=left_idx,
287
+ related_idx=right_idx,
288
+ real_row_count=real_row_count,
289
+ syn_row_count=syn_row_count,
290
+ real_missing_counts=real_missing_counts,
291
+ syn_missing_counts=syn_missing_counts,
292
+ real_joint_missing_counts=real_joint_missing_counts,
293
+ syn_joint_missing_counts=syn_joint_missing_counts,
294
+ )
295
+ right_score, right_row = _ordered_centered_profile_score_from_counts(
296
+ target_idx=right_idx,
297
+ related_idx=left_idx,
298
+ real_row_count=real_row_count,
299
+ syn_row_count=syn_row_count,
300
+ real_missing_counts=real_missing_counts,
301
+ syn_missing_counts=syn_missing_counts,
302
+ real_joint_missing_counts=real_joint_missing_counts,
303
+ syn_joint_missing_counts=syn_joint_missing_counts,
304
+ )
305
+ pair_id = f"{missing_targets[left_idx]}__{missing_targets[right_idx]}"
306
+ pair_rows.append(
307
+ {
308
+ "pair_id": pair_id,
309
+ "target_missing_column": missing_targets[left_idx],
310
+ "related_missing_column": missing_targets[right_idx],
311
+ "direction": f"{missing_targets[left_idx]}|{missing_targets[right_idx]}",
312
+ **left_row,
313
+ }
314
+ )
315
+ pair_rows.append(
316
+ {
317
+ "pair_id": pair_id,
318
+ "target_missing_column": missing_targets[right_idx],
319
+ "related_missing_column": missing_targets[left_idx],
320
+ "direction": f"{missing_targets[right_idx]}|{missing_targets[left_idx]}",
321
+ **right_row,
322
+ }
323
+ )
324
+
325
+ if pair_scores.size == 0:
326
+ return {
327
+ "pairwise_centered_status": "not_applicable_no_pairs",
328
+ "pairwise_centered_comissing_score": None,
329
+ "pairwise_centered_pair_count": 0,
330
+ "pairwise_centered_ordered_edge_count": 0,
331
+ "active_missing_target_count": len(missing_targets),
332
+ "pair_rows": [],
333
+ }
334
+
335
+ return {
336
+ "pairwise_centered_status": "ok",
337
+ "pairwise_centered_comissing_score": round(float(np.nanmean(pair_scores)), 6),
338
+ "pairwise_centered_pair_count": int(pair_scores.size),
339
+ "pairwise_centered_ordered_edge_count": ordered_edge_count,
340
+ "active_missing_target_count": len(missing_targets),
341
+ "pair_rows": pair_rows,
342
+ }
343
+
344
+
345
+ def _maybe_float(value: Any) -> float | None:
346
+ if value is None or pd.isna(value):
347
+ return None
348
+ try:
349
+ return float(value)
350
+ except (TypeError, ValueError):
351
+ return None
352
+
353
+
354
+ def _evaluate_asset_row(source_row: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
355
+ dataset_id = str(source_row.get("dataset_id") or "").strip()
356
+ synthetic_csv_path = Path(str(source_row.get("synthetic_csv_path") or "").strip())
357
+ model_id = _normalize_model(source_row.get("model_id"))
358
+ if not synthetic_csv_path.exists():
359
+ payload = {
360
+ **source_row,
361
+ "dataset_id": dataset_id,
362
+ "dataset_prefix": _dataset_prefix(dataset_id),
363
+ "model_id": model_id,
364
+ "model_label": _model_label(model_id),
365
+ "current_status": source_row.get("status"),
366
+ "marginal_missing_rate_consistency": _maybe_float(source_row.get("marginal_missing_rate_consistency")),
367
+ "current_broad_comissing_score": _maybe_float(source_row.get("co_missingness_pattern_consistency")),
368
+ "current_missingness_structure_score": _maybe_float(source_row.get("missingness_structure_score")),
369
+ "pairwise_centered_status": "synthetic_csv_missing",
370
+ "pairwise_centered_comissing_score": None,
371
+ "pairwise_centered_pair_count": 0,
372
+ "pairwise_centered_ordered_edge_count": 0,
373
+ "active_missing_target_count": None,
374
+ "pairwise_centered_missingness_structure_score": None,
375
+ "delta_pairwise_centered_minus_current_broad": None,
376
+ }
377
+ return payload, []
378
+
379
+ pairwise_result = _pairwise_centered_score_for_asset(dataset_id, synthetic_csv_path)
380
+ payload = {
381
+ **source_row,
382
+ "dataset_id": dataset_id,
383
+ "dataset_prefix": _dataset_prefix(dataset_id),
384
+ "model_id": model_id,
385
+ "model_label": _model_label(model_id),
386
+ "current_status": source_row.get("status"),
387
+ "marginal_missing_rate_consistency": _maybe_float(source_row.get("marginal_missing_rate_consistency")),
388
+ "current_broad_comissing_score": _maybe_float(source_row.get("co_missingness_pattern_consistency")),
389
+ "current_missingness_structure_score": _maybe_float(source_row.get("missingness_structure_score")),
390
+ "pairwise_centered_status": pairwise_result.get("pairwise_centered_status"),
391
+ "pairwise_centered_comissing_score": pairwise_result.get("pairwise_centered_comissing_score"),
392
+ "pairwise_centered_pair_count": pairwise_result.get("pairwise_centered_pair_count"),
393
+ "pairwise_centered_ordered_edge_count": pairwise_result.get("pairwise_centered_ordered_edge_count"),
394
+ "active_missing_target_count": pairwise_result.get("active_missing_target_count"),
395
+ }
396
+ marginal = payload.get("marginal_missing_rate_consistency")
397
+ pairwise_score = payload.get("pairwise_centered_comissing_score")
398
+ if marginal is not None and pairwise_score is not None:
399
+ payload["pairwise_centered_missingness_structure_score"] = round(float(np.mean([float(marginal), float(pairwise_score)])), 6)
400
+ else:
401
+ payload["pairwise_centered_missingness_structure_score"] = None
402
+ current_broad = payload.get("current_broad_comissing_score")
403
+ if current_broad is not None and pairwise_score is not None:
404
+ payload["delta_pairwise_centered_minus_current_broad"] = round(float(pairwise_score) - float(current_broad), 6)
405
+ else:
406
+ payload["delta_pairwise_centered_minus_current_broad"] = None
407
+
408
+ pair_rows = []
409
+ for row in pairwise_result.get("pair_rows", []):
410
+ pair_rows.append(
411
+ {
412
+ "dataset_id": dataset_id,
413
+ "dataset_prefix": _dataset_prefix(dataset_id),
414
+ "model_id": model_id,
415
+ "model_label": _model_label(model_id),
416
+ "synthetic_csv_path": str(synthetic_csv_path),
417
+ **row,
418
+ }
419
+ )
420
+ return payload, pair_rows
421
+
422
+
423
+ def _mean_or_none(values: list[Any]) -> float | None:
424
+ cleaned = [float(value) for value in values if value is not None and not pd.isna(value)]
425
+ if not cleaned:
426
+ return None
427
+ return float(np.mean(cleaned))
428
+
429
+
430
+ def _summarize_asset_rows(asset_rows: list[dict[str, Any]], group_keys: tuple[str, ...]) -> list[dict[str, Any]]:
431
+ grouped: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list)
432
+ for row in asset_rows:
433
+ grouped[tuple(str(row.get(key) or "") for key in group_keys)].append(row)
434
+
435
+ rows: list[dict[str, Any]] = []
436
+ for key, items in sorted(grouped.items()):
437
+ payload = {field: value for field, value in zip(group_keys, key)}
438
+ payload["asset_count"] = len(items)
439
+ payload["current_applicable_asset_count"] = sum(1 for item in items if item.get("current_status") == "ok")
440
+ payload["pairwise_centered_applicable_asset_count"] = sum(1 for item in items if item.get("pairwise_centered_status") == "ok")
441
+ for field in (
442
+ "marginal_missing_rate_consistency",
443
+ "current_broad_comissing_score",
444
+ "current_missingness_structure_score",
445
+ "pairwise_centered_comissing_score",
446
+ "pairwise_centered_missingness_structure_score",
447
+ "delta_pairwise_centered_minus_current_broad",
448
+ ):
449
+ payload[field] = _mean_or_none([item.get(field) for item in items])
450
+ if payload[field] is not None:
451
+ payload[field] = round(float(payload[field]), 6)
452
+ payload["pairwise_centered_pair_count__max"] = int(
453
+ max(float(item.get("pairwise_centered_pair_count") or 0.0) for item in items)
454
+ )
455
+ payload["active_missing_target_count__max"] = int(
456
+ max(float(item.get("active_missing_target_count") or 0.0) for item in items)
457
+ )
458
+ rows.append(payload)
459
+ return rows
460
+
461
+
462
+ def run_pairwise_centered_diagnostic(max_workers: int | None = None) -> dict[str, Path]:
463
+ _ensure_dirs()
464
+ asset_df_source = pd.read_csv(CURRENT_ASSET_CSV, encoding="utf-8-sig")
465
+ source_rows = asset_df_source.to_dict(orient="records")
466
+
467
+ asset_rows: list[dict[str, Any]] = []
468
+ pair_rows: list[dict[str, Any]] = []
469
+ worker_count = max_workers if max_workers is not None else min(8, max(1, (cpu_count() or 4) - 1))
470
+
471
+ with ThreadPoolExecutor(max_workers=max(1, worker_count)) as executor:
472
+ futures = [executor.submit(_evaluate_asset_row, row) for row in source_rows]
473
+ for index, future in enumerate(as_completed(futures), start=1):
474
+ asset_row, asset_pair_rows = future.result()
475
+ asset_rows.append(asset_row)
476
+ pair_rows.extend(asset_pair_rows)
477
+ print(
478
+ f"[pairwise-centered] asset={index}/{len(futures)}"
479
+ f" dataset={asset_row['dataset_id']}"
480
+ f" model={asset_row['model_id']}"
481
+ f" status={asset_row['pairwise_centered_status']}",
482
+ flush=True,
483
+ )
484
+
485
+ asset_df = pd.DataFrame(asset_rows)
486
+ pair_df = pd.DataFrame(pair_rows)
487
+ if not asset_df.empty:
488
+ asset_df["model_sort"] = asset_df["model_id"].map(lambda item: _model_sort_key(str(item)))
489
+ asset_df = asset_df.sort_values(["dataset_id", "model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True)
490
+
491
+ dataset_model_df = pd.DataFrame(_summarize_asset_rows(asset_rows, ("dataset_id", "dataset_prefix", "model_id", "model_label")))
492
+ model_overall_df = pd.DataFrame(_summarize_asset_rows(asset_rows, ("model_id", "model_label")))
493
+ dataset_overall_df = pd.DataFrame(_summarize_asset_rows(asset_rows, ("dataset_id", "dataset_prefix")))
494
+ if not model_overall_df.empty:
495
+ model_overall_df["model_sort"] = model_overall_df["model_id"].map(lambda item: _model_sort_key(str(item)))
496
+ model_overall_df = model_overall_df.sort_values(["model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True)
497
+ if not dataset_model_df.empty:
498
+ dataset_model_df["model_sort"] = dataset_model_df["model_id"].map(lambda item: _model_sort_key(str(item)))
499
+ dataset_model_df = dataset_model_df.sort_values(["dataset_id", "model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True)
500
+ if not pair_df.empty:
501
+ pair_df["model_sort"] = pair_df["model_id"].map(lambda item: _model_sort_key(str(item)))
502
+ pair_df = pair_df.sort_values(["dataset_id", "model_sort", "model_id", "pair_id", "direction"]).drop(columns=["model_sort"]).reset_index(drop=True)
503
+
504
+ asset_csv = DATA_DIR / "pairwise_centered_asset_scores.csv"
505
+ pair_csv = DATA_DIR / "pairwise_centered_pair_scores.csv"
506
+ dataset_model_csv = DATA_DIR / "pairwise_centered_model_dataset_summary.csv"
507
+ model_overall_csv = DATA_DIR / "pairwise_centered_model_overall_summary.csv"
508
+ dataset_overall_csv = DATA_DIR / "pairwise_centered_dataset_overall_summary.csv"
509
+
510
+ write_csv(asset_csv, asset_df.to_dict(orient="records"))
511
+ write_csv(pair_csv, pair_df.to_dict(orient="records"))
512
+ write_csv(dataset_model_csv, dataset_model_df.to_dict(orient="records"))
513
+ write_csv(model_overall_csv, model_overall_df.to_dict(orient="records"))
514
+ write_csv(dataset_overall_csv, dataset_overall_df.to_dict(orient="records"))
515
+
516
+ applicable_panels = int(
517
+ asset_df["pairwise_centered_status"].eq("ok").sum()
518
+ ) if not asset_df.empty else 0
519
+ applicable_datasets = int(
520
+ asset_df.loc[asset_df["pairwise_centered_status"].eq("ok"), "dataset_id"].nunique()
521
+ ) if not asset_df.empty else 0
522
+ readme_lines = [
523
+ "# Pairwise-Centered Co-Missing Diagnostic",
524
+ "",
525
+ "- This is an experimental diagnostic and does not modify the official missingness bundle.",
526
+ "- Canonical marginal score is reused unchanged from the direct missingness evaluator.",
527
+ "- Experimental co-missing score restricts the second axis to pairs of active missing-target columns.",
528
+ "- For each ordered pair `(Mi | Mj)`, we compare centered profiles:",
529
+ " - `delta_real(r) = P_real(Mi=1 | Mj=r) - P_real(Mi=1)`",
530
+ " - `delta_syn(r) = P_syn(Mi=1 | Mj=r) - P_syn(Mi=1)`",
531
+ " - `score = 1 - 0.5 * sum_r P_real(Mj=r) * |delta_real(r) - delta_syn(r)|`",
532
+ "- Final experimental co-missing score = mean over unordered missing-target pairs after averaging both directions.",
533
+ "",
534
+ f"- Asset panels evaluated: `{asset_df.shape[0]}`",
535
+ f"- Pairwise-applicable panels: `{applicable_panels}`",
536
+ f"- Pairwise-applicable datasets: `{applicable_datasets}`",
537
+ "",
538
+ "## Files",
539
+ "",
540
+ "- `data/pairwise_centered_asset_scores.csv`",
541
+ "- `data/pairwise_centered_pair_scores.csv`",
542
+ "- `data/pairwise_centered_model_dataset_summary.csv`",
543
+ "- `data/pairwise_centered_model_overall_summary.csv`",
544
+ "- `data/pairwise_centered_dataset_overall_summary.csv`",
545
+ ]
546
+ (OUTPUT_ROOT / "README.md").write_text("\n".join(readme_lines) + "\n", encoding="utf-8")
547
+ (FINAL_DIR / "README.md").write_text("\n".join(readme_lines) + "\n", encoding="utf-8")
548
+ for src in (asset_csv, pair_csv, dataset_model_csv, model_overall_csv, dataset_overall_csv):
549
+ (FINAL_DIR / src.name).write_text(src.read_text(encoding="utf-8-sig"), encoding="utf-8-sig")
550
+
551
+ return {
552
+ "asset_scores": asset_csv,
553
+ "pair_scores": pair_csv,
554
+ "model_dataset_summary": dataset_model_csv,
555
+ "model_overall_summary": model_overall_csv,
556
+ "dataset_overall_summary": dataset_overall_csv,
557
+ }
558
+
559
+
560
+ if __name__ == "__main__":
561
+ outputs = run_pairwise_centered_diagnostic()
562
+ for key, value in outputs.items():
563
+ print(f"{key}: {value}")
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/regime_diagnostic_runner.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build missingness regime diagnostic grouped-bar figures.
3
+
4
+ This diagnostic compares categorical, mixed, and numerical regimes for:
5
+
6
+ 1. missingness_structure_score
7
+ 2. co_missingness_pattern_consistency
8
+ 3. marginal_missing_rate_consistency
9
+
10
+ It writes paper-friendly PNG/PDF previews plus concise text insights.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import matplotlib
20
+
21
+ matplotlib.use("Agg")
22
+ import matplotlib.pyplot as plt
23
+ import numpy as np
24
+ import pandas as pd
25
+
26
+
27
+ PROJECT_ROOT = Path(__file__).resolve().parents[4]
28
+ OUTPUT_ROOT = PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown" / "regime_diagnostic"
29
+ DATA_DIR = OUTPUT_ROOT / "data"
30
+ FIG_DIR = OUTPUT_ROOT / "figures"
31
+ FINAL_DIR = OUTPUT_ROOT / "final"
32
+ SOURCE_CSV = (
33
+ PROJECT_ROOT
34
+ / "Evaluation"
35
+ / "query_fivepart_breakdown"
36
+ / "missingness_breakdown"
37
+ / "final"
38
+ / "prefix_summary__v2.csv"
39
+ )
40
+
41
+ MODEL_COLORS = {
42
+ "REAL": "#000000",
43
+ "RealTabFormer": "#332288",
44
+ "TVAE": "#4477AA",
45
+ "ForestDiffusion": "#228833",
46
+ "TabDDPM": "#EE7733",
47
+ "TabSyn": "#66CCEE",
48
+ "TabDiff": "#AA3377",
49
+ "CTGAN": "#EE6677",
50
+ "ARF": "#777777",
51
+ "BayesNet": "#CCBB44",
52
+ "TabPFGen": "#009988",
53
+ "TabbyFlow": "#882255",
54
+ }
55
+
56
+ MODEL_ORDER = [
57
+ "ARF",
58
+ "BayesNet",
59
+ "CTGAN",
60
+ "ForestDiffusion",
61
+ "RealTabFormer",
62
+ "TabbyFlow",
63
+ "TabDDPM",
64
+ "TabDiff",
65
+ "TabPFGen",
66
+ "TabSyn",
67
+ "TVAE",
68
+ ]
69
+
70
+ PREFIX_ORDER = ["c", "m", "n"]
71
+ PREFIX_LABELS = {"c": "Categorical", "m": "Mixed", "n": "Numerical"}
72
+ PREFIX_COLORS = {"c": "#E6C229", "m": "#3FA7D6", "n": "#D1495B"}
73
+
74
+ METRIC_SPECS = [
75
+ (
76
+ "missingness_structure_score",
77
+ "missingness_regime_grouped_bars_main",
78
+ "Missingness family score across regimes",
79
+ ),
80
+ (
81
+ "co_missingness_pattern_consistency",
82
+ "missingness_regime_grouped_bars_profile_appendix",
83
+ "Co-missingness profile score across regimes",
84
+ ),
85
+ (
86
+ "marginal_missing_rate_consistency",
87
+ "missingness_regime_grouped_bars_marginal_appendix",
88
+ "Marginal missing-rate score across regimes",
89
+ ),
90
+ ]
91
+
92
+
93
+ def _ensure_dirs() -> None:
94
+ for path in [OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR]:
95
+ path.mkdir(parents=True, exist_ok=True)
96
+
97
+
98
+ def _load_prefix_summary() -> pd.DataFrame:
99
+ df = pd.read_csv(SOURCE_CSV)
100
+ df = df.rename(columns={"model_label": "Model", "dataset_prefix": "Prefix"})
101
+ df["Model"] = df["Model"].astype(str)
102
+ df["Prefix"] = df["Prefix"].astype(str)
103
+ return df
104
+
105
+
106
+ def _pivot_metric(df: pd.DataFrame, metric: str) -> pd.DataFrame:
107
+ pivot = (
108
+ df.pivot(index="Model", columns="Prefix", values=metric)
109
+ .reindex(index=MODEL_ORDER, columns=PREFIX_ORDER)
110
+ .reset_index()
111
+ )
112
+ return pivot
113
+
114
+
115
+ def _write_csv(df: pd.DataFrame, path: Path) -> None:
116
+ df.to_csv(path, index=False, encoding="utf-8")
117
+
118
+
119
+ def _plot_grouped_bars(metric_df: pd.DataFrame, title: str, pdf_path: Path, png_path: Path) -> None:
120
+ models = metric_df["Model"].tolist()
121
+ x = np.arange(len(models))
122
+ width = 0.23
123
+ fig, ax = plt.subplots(figsize=(13.6, 5.8))
124
+
125
+ for idx, prefix in enumerate(PREFIX_ORDER):
126
+ values = pd.to_numeric(metric_df[prefix], errors="coerce").to_numpy(dtype=float)
127
+ offset = (idx - 1) * width
128
+ mask = ~np.isnan(values)
129
+ ax.bar(
130
+ x[mask] + offset,
131
+ values[mask],
132
+ width=width,
133
+ color=PREFIX_COLORS[prefix],
134
+ label=PREFIX_LABELS[prefix],
135
+ edgecolor="white",
136
+ linewidth=0.8,
137
+ )
138
+
139
+ ax.set_title(title, fontsize=15)
140
+ ax.set_ylabel("Score")
141
+ ax.set_xlabel("Model")
142
+ ax.set_ylim(0.0, 1.02)
143
+ ax.set_xticks(x)
144
+ ax.set_xticklabels(models, rotation=90, ha="center", va="top")
145
+ ax.grid(axis="y", alpha=0.25)
146
+ ax.legend(frameon=False, ncol=3, loc="upper right")
147
+ fig.tight_layout()
148
+ fig.savefig(pdf_path, bbox_inches="tight")
149
+ fig.savefig(png_path, dpi=240, bbox_inches="tight")
150
+ plt.close(fig)
151
+
152
+
153
+ def _tex_escape(text: str) -> str:
154
+ escaped = str(text)
155
+ for src, dst in [
156
+ ("\\", r"\textbackslash{}"),
157
+ ("&", r"\&"),
158
+ ("%", r"\%"),
159
+ ("$", r"\$"),
160
+ ("#", r"\#"),
161
+ ("_", r"\_"),
162
+ ("{", r"\{"),
163
+ ("}", r"\}"),
164
+ ]:
165
+ escaped = escaped.replace(src, dst)
166
+ return escaped
167
+
168
+
169
+ def _write_grouped_bars_tex(metric_df: pd.DataFrame, title: str, tex_path: Path) -> None:
170
+ models = metric_df["Model"].tolist()
171
+ symbolic = ",".join(_tex_escape(model) for model in models)
172
+ bar_width = "8pt"
173
+ lines = [
174
+ r"\documentclass[tikz,border=4pt]{standalone}",
175
+ r"\usepackage{pgfplots}",
176
+ r"\pgfplotsset{compat=1.18}",
177
+ r"\usepackage{xcolor}",
178
+ r"\begin{document}",
179
+ r"\begin{tikzpicture}",
180
+ r"\begin{axis}[",
181
+ f"title={{{_tex_escape(title)}}},",
182
+ r"width=15.6cm,",
183
+ r"height=7.0cm,",
184
+ r"ymin=0, ymax=1.02,",
185
+ r"ylabel={Score},",
186
+ r"xlabel={Model},",
187
+ r"ymajorgrids=true,",
188
+ r"grid style={gray!25},",
189
+ r"legend style={draw=none, fill=none, at={(0.98,0.98)}, anchor=north east},",
190
+ r"legend columns=3,",
191
+ f"symbolic x coords={{{symbolic}}},",
192
+ r"xtick=data,",
193
+ r"x tick label style={rotate=90, anchor=east, font=\small},",
194
+ r"enlarge x limits=0.05,",
195
+ f"bar width={bar_width},",
196
+ r"]",
197
+ ]
198
+
199
+ for idx, prefix in enumerate(PREFIX_ORDER):
200
+ color = PREFIX_COLORS[prefix]
201
+ label = PREFIX_LABELS[prefix]
202
+ shift = (-1 + idx) * 10
203
+ coords: list[str] = []
204
+ for row in metric_df.itertuples(index=False):
205
+ value = getattr(row, prefix)
206
+ if pd.isna(value):
207
+ continue
208
+ coords.append(f"({_tex_escape(row.Model)},{float(value):.6f})")
209
+ lines.extend(
210
+ [
211
+ rf"\addplot+[ybar, bar shift={shift}pt, draw=white, fill={color}] coordinates {{",
212
+ " ".join(coords),
213
+ r"};",
214
+ rf"\addlegendentry{{{_tex_escape(label)}}}",
215
+ ]
216
+ )
217
+
218
+ lines.extend(
219
+ [
220
+ r"\end{axis}",
221
+ r"\end{tikzpicture}",
222
+ r"\end{document}",
223
+ "",
224
+ ]
225
+ )
226
+ tex_path.write_text("\n".join(lines), encoding="utf-8")
227
+
228
+
229
+ def _format_value(value: Any) -> str:
230
+ if pd.isna(value):
231
+ return "NA"
232
+ return f"{float(value):.3f}"
233
+
234
+
235
+ def _build_story_txt(main_df: pd.DataFrame) -> str:
236
+ numeric = pd.to_numeric(main_df["n"], errors="coerce")
237
+ categorical = pd.to_numeric(main_df["c"], errors="coerce")
238
+ mixed = pd.to_numeric(main_df["m"], errors="coerce")
239
+ work = main_df.copy()
240
+ work["drop_c_to_n"] = categorical - numeric
241
+ work["drop_m_to_n"] = mixed - numeric
242
+ work["range_max_min"] = pd.concat([categorical, mixed, numeric], axis=1).max(axis=1) - pd.concat([categorical, mixed, numeric], axis=1).min(axis=1)
243
+
244
+ valid_n = work.loc[work["n"].notna()].copy()
245
+ valid_n = valid_n.sort_values("n", ascending=False)
246
+ largest_drop = valid_n.sort_values("drop_m_to_n", ascending=False)
247
+
248
+ lines = [
249
+ "Insight 1: Numerical missingness is the hardest regime for most models.",
250
+ (
251
+ "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. "
252
+ f"The numerical column is especially weak for ARF ({_format_value(valid_n.loc[valid_n['Model']=='ARF', 'n'].iloc[0])}), "
253
+ f"BayesNet ({_format_value(valid_n.loc[valid_n['Model']=='BayesNet', 'n'].iloc[0])}), "
254
+ f"CTGAN ({_format_value(valid_n.loc[valid_n['Model']=='CTGAN', 'n'].iloc[0])}), "
255
+ 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])})."
256
+ ),
257
+ "",
258
+ "Insight 2: Some models collapse sharply on numerical missingness, but RealTabFormer remains stable.",
259
+ (
260
+ f"RealTabFormer stays high in all three regimes with c/m/n = "
261
+ f"{_format_value(valid_n.loc[valid_n['Model']=='RealTabFormer', 'c'].iloc[0])}/"
262
+ f"{_format_value(valid_n.loc[valid_n['Model']=='RealTabFormer', 'm'].iloc[0])}/"
263
+ f"{_format_value(valid_n.loc[valid_n['Model']=='RealTabFormer', 'n'].iloc[0])}. "
264
+ f"By contrast, the largest mixed-to-numerical drops come from "
265
+ f"{largest_drop.iloc[0]['Model']} ({_format_value(largest_drop.iloc[0]['m'])} -> {_format_value(largest_drop.iloc[0]['n'])}), "
266
+ f"{largest_drop.iloc[1]['Model']} ({_format_value(largest_drop.iloc[1]['m'])} -> {_format_value(largest_drop.iloc[1]['n'])}), and "
267
+ f"{largest_drop.iloc[2]['Model']} ({_format_value(largest_drop.iloc[2]['m'])} -> {_format_value(largest_drop.iloc[2]['n'])}). "
268
+ "This suggests that preserving numerical missingness structure is not just uniformly harder; for some models it is a clear regime-specific failure mode."
269
+ ),
270
+ ]
271
+ return "\n".join(lines) + "\n"
272
+
273
+
274
+ def _build_manifest(metric_tables: dict[str, str]) -> dict[str, Any]:
275
+ return {
276
+ "task": "missingness_regime_diagnostic",
277
+ "source_csv": str(SOURCE_CSV),
278
+ "output_root": str(OUTPUT_ROOT),
279
+ "metric_tables": metric_tables,
280
+ "model_order": MODEL_ORDER,
281
+ "prefix_order": PREFIX_ORDER,
282
+ }
283
+
284
+
285
+ def run() -> dict[str, Any]:
286
+ _ensure_dirs()
287
+ df = _load_prefix_summary()
288
+ metric_tables: dict[str, str] = {}
289
+
290
+ main_metric_df: pd.DataFrame | None = None
291
+ for metric, stem, title in METRIC_SPECS:
292
+ metric_df = _pivot_metric(df, metric)
293
+ _write_csv(metric_df, DATA_DIR / f"{stem}.csv")
294
+ _write_grouped_bars_tex(metric_df, title, FIG_DIR / f"{stem}.tex")
295
+ _plot_grouped_bars(metric_df, title, FIG_DIR / f"{stem}.pdf", FIG_DIR / f"{stem}.png")
296
+ metric_tables[metric] = f"data/{stem}.csv"
297
+ if metric == "missingness_structure_score":
298
+ main_metric_df = metric_df
299
+
300
+ if main_metric_df is None:
301
+ raise RuntimeError("Main metric table was not built.")
302
+
303
+ story_txt = _build_story_txt(main_metric_df)
304
+ (FINAL_DIR / "missingness_regime_insights.txt").write_text(story_txt, encoding="utf-8")
305
+ (FINAL_DIR / "README.txt").write_text(
306
+ "\n".join(
307
+ [
308
+ "Missingness regime diagnostic bundle",
309
+ "",
310
+ "Main figure:",
311
+ "- figures/missingness_regime_grouped_bars_main.png",
312
+ "- figures/missingness_regime_grouped_bars_main.tex",
313
+ "",
314
+ "Appendix figures:",
315
+ "- figures/missingness_regime_grouped_bars_profile_appendix.png",
316
+ "- figures/missingness_regime_grouped_bars_profile_appendix.tex",
317
+ "- figures/missingness_regime_grouped_bars_marginal_appendix.png",
318
+ "- figures/missingness_regime_grouped_bars_marginal_appendix.tex",
319
+ "",
320
+ "Text insight:",
321
+ "- final/missingness_regime_insights.txt",
322
+ ]
323
+ )
324
+ + "\n",
325
+ encoding="utf-8",
326
+ )
327
+
328
+ manifest = _build_manifest(metric_tables)
329
+ (OUTPUT_ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
330
+ return manifest
331
+
332
+
333
+ if __name__ == "__main__":
334
+ print(json.dumps(run(), indent=2))
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/review_strict_pairwise.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Temporary audit: compare current broad co-missingness vs strict pairwise co-missingness.
3
+
4
+ This script does not modify the official missingness breakdown outputs.
5
+ It writes a standalone review bundle under:
6
+
7
+ Evaluation/query_fivepart_breakdown/missingness_breakdown/review_strict_pairwise
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ import sys
14
+ from concurrent.futures import ThreadPoolExecutor, as_completed
15
+ from functools import lru_cache
16
+ from pathlib import Path
17
+ from statistics import mean
18
+ from typing import Any
19
+
20
+ import matplotlib
21
+
22
+ matplotlib.use("Agg")
23
+ import matplotlib.pyplot as plt
24
+ import numpy as np
25
+ import pandas as pd
26
+
27
+ PROJECT_ROOT = Path(__file__).resolve().parents[4]
28
+ if str(PROJECT_ROOT) not in sys.path:
29
+ sys.path.insert(0, str(PROJECT_ROOT))
30
+
31
+ from src.eval.common import normalize_missing, resolve_real_split_path
32
+ from tests.comissing_condition_eval import _clip01, _relation_strength, build_dataset_context
33
+
34
+
35
+ OUTPUT_ROOT = (
36
+ PROJECT_ROOT
37
+ / "Evaluation"
38
+ / "query_fivepart_breakdown"
39
+ / "missingness_breakdown"
40
+ / "review_strict_pairwise"
41
+ )
42
+ DATA_DIR = OUTPUT_ROOT / "data"
43
+ FIG_DIR = OUTPUT_ROOT / "figures"
44
+ NOTES_DIR = OUTPUT_ROOT / "notes"
45
+
46
+ CURRENT_ASSET_CSV = (
47
+ PROJECT_ROOT
48
+ / "Evaluation"
49
+ / "query_fivepart_breakdown"
50
+ / "missingness_breakdown"
51
+ / "data"
52
+ / "direct_asset_scores.csv"
53
+ )
54
+
55
+ EXCLUDED_MODELS = {"cdtd", "codi", "goggle"}
56
+ MODEL_ALIASES = {"rtf": "realtabformer"}
57
+ MODEL_LABELS = {
58
+ "arf": "ARF",
59
+ "bayesnet": "BayesNet",
60
+ "ctgan": "CTGAN",
61
+ "forestdiffusion": "ForestDiffusion",
62
+ "realtabformer": "RealTabFormer",
63
+ "tabbyflow": "TabbyFlow",
64
+ "tabddpm": "TabDDPM",
65
+ "tabdiff": "TabDiff",
66
+ "tabpfgen": "TabPFGen",
67
+ "tabsyn": "TabSyn",
68
+ "tvae": "TVAE",
69
+ }
70
+ MODEL_COLORS = {
71
+ "realtabformer": "#332288",
72
+ "tvae": "#4477AA",
73
+ "forestdiffusion": "#228833",
74
+ "tabddpm": "#EE7733",
75
+ "tabsyn": "#66CCEE",
76
+ "tabdiff": "#AA3377",
77
+ "ctgan": "#EE6677",
78
+ "arf": "#777777",
79
+ "bayesnet": "#CCBB44",
80
+ "tabpfgen": "#009988",
81
+ "tabbyflow": "#882255",
82
+ }
83
+ MODEL_ORDER = [
84
+ "arf",
85
+ "bayesnet",
86
+ "ctgan",
87
+ "forestdiffusion",
88
+ "realtabformer",
89
+ "tabbyflow",
90
+ "tabddpm",
91
+ "tabdiff",
92
+ "tabpfgen",
93
+ "tabsyn",
94
+ "tvae",
95
+ ]
96
+
97
+
98
+ def _ensure_dirs() -> None:
99
+ for path in (OUTPUT_ROOT, DATA_DIR, FIG_DIR, NOTES_DIR):
100
+ path.mkdir(parents=True, exist_ok=True)
101
+
102
+
103
+ def _normalize_model(model_id: Any) -> str:
104
+ key = str(model_id or "").strip().lower()
105
+ return MODEL_ALIASES.get(key, key)
106
+
107
+
108
+ def _model_label(model_id: str) -> str:
109
+ return MODEL_LABELS.get(model_id, model_id)
110
+
111
+
112
+ def _write_csv(df: pd.DataFrame, path: Path) -> None:
113
+ df.to_csv(path, index=False, encoding="utf-8-sig")
114
+
115
+
116
+ def _binary_missing_indicator(series: pd.Series) -> np.ndarray:
117
+ return series.map(normalize_missing).to_numpy(dtype=float)
118
+
119
+
120
+ def _load_syn_target_df(synthetic_csv_path: Path, target_columns: list[str]) -> pd.DataFrame:
121
+ try:
122
+ syn_df = pd.read_csv(
123
+ synthetic_csv_path,
124
+ dtype=str,
125
+ keep_default_na=False,
126
+ usecols=lambda name: str(name) in set(target_columns),
127
+ )
128
+ except ValueError:
129
+ syn_df = pd.read_csv(synthetic_csv_path, dtype=str, keep_default_na=False)
130
+ syn_df = syn_df[[col for col in target_columns if col in syn_df.columns]]
131
+ for column in target_columns:
132
+ if column not in syn_df.columns:
133
+ syn_df[column] = ""
134
+ return syn_df[target_columns]
135
+
136
+
137
+ def _state_codes_from_indicator(indicator: np.ndarray) -> np.ndarray:
138
+ # 0 = non-missing, 1 = missing
139
+ return indicator.astype(np.int16, copy=False)
140
+
141
+
142
+ def _conditional_rate_stats(missing_indicator: np.ndarray, related_codes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
143
+ support_counts = np.bincount(related_codes, minlength=2)
144
+ missing_sums = np.bincount(related_codes, weights=missing_indicator, minlength=2)
145
+ rates = np.zeros(2, dtype=float)
146
+ nonzero = support_counts > 0
147
+ rates[nonzero] = missing_sums[nonzero] / support_counts[nonzero]
148
+ return support_counts, rates
149
+
150
+
151
+ def _strict_pair_score(
152
+ real_target: np.ndarray,
153
+ real_related: np.ndarray,
154
+ syn_target: np.ndarray,
155
+ syn_related: np.ndarray,
156
+ ) -> tuple[float, float, float]:
157
+ real_global_missing_rate = float(np.mean(real_target))
158
+ real_related_codes = _state_codes_from_indicator(real_related)
159
+ syn_related_codes = _state_codes_from_indicator(syn_related)
160
+
161
+ real_support_counts, real_conditional_rates = _conditional_rate_stats(real_target, real_related_codes)
162
+ supported_state_indices = tuple(int(idx) for idx in np.where(real_support_counts > 0)[0].tolist())
163
+ real_state_probabilities = real_support_counts.astype(float) / max(1, len(real_target))
164
+ real_strength = _relation_strength(real_global_missing_rate, real_state_probabilities, real_conditional_rates)
165
+
166
+ syn_support_counts, syn_conditional_rates = _conditional_rate_stats(syn_target, syn_related_codes)
167
+ syn_rates_fallback = syn_conditional_rates.copy()
168
+ zero_support = syn_support_counts <= 0
169
+ syn_rates_fallback[zero_support] = float(np.mean(syn_target))
170
+
171
+ profile_distance = 0.0
172
+ for idx in supported_state_indices:
173
+ profile_distance += float(real_state_probabilities[idx]) * abs(
174
+ float(real_conditional_rates[idx]) - float(syn_rates_fallback[idx])
175
+ )
176
+ profile_score = _clip01(1.0 - profile_distance)
177
+
178
+ denom = max(real_global_missing_rate * (1.0 - real_global_missing_rate), 1e-12)
179
+ syn_weighted_var = 0.0
180
+ for idx in supported_state_indices:
181
+ syn_weighted_var += float(real_state_probabilities[idx]) * (
182
+ (float(syn_rates_fallback[idx]) - real_global_missing_rate) ** 2
183
+ )
184
+ syn_strength = _clip01(syn_weighted_var / denom)
185
+ strength_score = _clip01(1.0 - abs(real_strength - syn_strength))
186
+
187
+ edge_score = _clip01((0.7 * profile_score) + (0.3 * strength_score))
188
+ return edge_score, profile_score, strength_score
189
+
190
+
191
+ def _ordered_edge_score_from_counts(
192
+ target_idx: int,
193
+ related_idx: int,
194
+ row_count: int,
195
+ real_missing_counts: np.ndarray,
196
+ syn_missing_counts: np.ndarray,
197
+ real_joint_missing_counts: np.ndarray,
198
+ syn_joint_missing_counts: np.ndarray,
199
+ ) -> float:
200
+ real_target_rate = float(real_missing_counts[target_idx] / row_count)
201
+ syn_target_rate = float(syn_missing_counts[target_idx] / row_count)
202
+
203
+ real_related_missing = float(real_missing_counts[related_idx])
204
+ real_related_nonmissing = float(row_count - real_related_missing)
205
+ real_state_probs = np.array(
206
+ [real_related_nonmissing / row_count, real_related_missing / row_count],
207
+ dtype=float,
208
+ )
209
+
210
+ real_joint = float(real_joint_missing_counts[target_idx, related_idx])
211
+ real_cond_nonmissing = (float(real_missing_counts[target_idx]) - real_joint) / max(real_related_nonmissing, 1.0)
212
+ real_cond_missing = real_joint / max(real_related_missing, 1.0)
213
+ real_conditional_rates = np.array([real_cond_nonmissing, real_cond_missing], dtype=float)
214
+ real_strength = _relation_strength(real_target_rate, real_state_probs, real_conditional_rates)
215
+
216
+ syn_related_missing = float(syn_missing_counts[related_idx])
217
+ syn_related_nonmissing = float(row_count - syn_related_missing)
218
+ syn_joint = float(syn_joint_missing_counts[target_idx, related_idx])
219
+
220
+ syn_cond_nonmissing = (float(syn_missing_counts[target_idx]) - syn_joint) / max(syn_related_nonmissing, 1.0)
221
+ syn_cond_missing = syn_joint / max(syn_related_missing, 1.0)
222
+ syn_conditional_rates = np.array([syn_cond_nonmissing, syn_cond_missing], dtype=float)
223
+ if syn_related_nonmissing <= 0:
224
+ syn_conditional_rates[0] = syn_target_rate
225
+ if syn_related_missing <= 0:
226
+ syn_conditional_rates[1] = syn_target_rate
227
+
228
+ profile_distance = float(
229
+ real_state_probs[0] * abs(real_conditional_rates[0] - syn_conditional_rates[0])
230
+ + real_state_probs[1] * abs(real_conditional_rates[1] - syn_conditional_rates[1])
231
+ )
232
+ profile_score = _clip01(1.0 - profile_distance)
233
+
234
+ denom = max(syn_target_rate * (1.0 - syn_target_rate), 1e-12)
235
+ syn_weighted_var = float(
236
+ real_state_probs[0] * ((syn_conditional_rates[0] - syn_target_rate) ** 2)
237
+ + real_state_probs[1] * ((syn_conditional_rates[1] - syn_target_rate) ** 2)
238
+ )
239
+ syn_strength = _clip01(syn_weighted_var / denom)
240
+ strength_score = _clip01(1.0 - abs(real_strength - syn_strength))
241
+ return _clip01((0.7 * profile_score) + (0.3 * strength_score))
242
+
243
+
244
+ @lru_cache(maxsize=None)
245
+ def _get_dataset_context(dataset_id: str):
246
+ return build_dataset_context(dataset_id)
247
+
248
+
249
+ @lru_cache(maxsize=None)
250
+ def _get_real_df(dataset_id: str) -> pd.DataFrame:
251
+ return pd.read_csv(resolve_real_split_path(dataset_id, split="train"), dtype=str, keep_default_na=False)
252
+
253
+
254
+ def _strict_pairwise_score_for_asset(dataset_id: str, synthetic_csv_path: Path) -> dict[str, Any]:
255
+ try:
256
+ context = _get_dataset_context(dataset_id)
257
+ except FileNotFoundError:
258
+ return {
259
+ "strict_status": "real_train_csv_missing_locally",
260
+ "strict_pairwise_score": None,
261
+ "strict_pair_count": 0,
262
+ "active_missing_target_count": 0,
263
+ }
264
+ missing_targets = [target.column for target in context.missing_targets]
265
+
266
+ if len(missing_targets) < 2:
267
+ return {
268
+ "strict_status": "not_applicable_fewer_than_2_missing_targets",
269
+ "strict_pairwise_score": None,
270
+ "strict_pair_count": 0,
271
+ "active_missing_target_count": len(missing_targets),
272
+ }
273
+
274
+ real_df = _get_real_df(dataset_id)
275
+ syn_df = _load_syn_target_df(synthetic_csv_path, missing_targets)
276
+
277
+ row_count = len(real_df)
278
+ real_matrix = np.column_stack([_binary_missing_indicator(real_df[col]) for col in missing_targets]).astype(np.float32)
279
+ syn_matrix = np.column_stack([_binary_missing_indicator(syn_df[col]) for col in missing_targets]).astype(np.float32)
280
+ real_missing_counts = real_matrix.sum(axis=0)
281
+ syn_missing_counts = syn_matrix.sum(axis=0)
282
+ real_joint_missing_counts = real_matrix.T @ real_matrix
283
+ syn_joint_missing_counts = syn_matrix.T @ syn_matrix
284
+
285
+ pair_scores: list[float] = []
286
+ for left_idx in range(len(missing_targets)):
287
+ for right_idx in range(left_idx + 1, len(missing_targets)):
288
+ left_given_right = _ordered_edge_score_from_counts(
289
+ left_idx,
290
+ right_idx,
291
+ row_count,
292
+ real_missing_counts,
293
+ syn_missing_counts,
294
+ real_joint_missing_counts,
295
+ syn_joint_missing_counts,
296
+ )
297
+ right_given_left = _ordered_edge_score_from_counts(
298
+ right_idx,
299
+ left_idx,
300
+ row_count,
301
+ real_missing_counts,
302
+ syn_missing_counts,
303
+ real_joint_missing_counts,
304
+ syn_joint_missing_counts,
305
+ )
306
+ pair_scores.append(float(mean([left_given_right, right_given_left])))
307
+
308
+ return {
309
+ "strict_status": "ok",
310
+ "strict_pairwise_score": round(float(mean(pair_scores)), 6),
311
+ "strict_pair_count": len(pair_scores),
312
+ "active_missing_target_count": len(missing_targets),
313
+ "pair_rows": [],
314
+ }
315
+
316
+
317
+ def _review_one_asset(row_dict: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
318
+ result = _strict_pairwise_score_for_asset(str(row_dict["dataset_id"]), Path(str(row_dict["synthetic_csv_path"])))
319
+ payload = {
320
+ "dataset_id": str(row_dict["dataset_id"]),
321
+ "model_id": str(row_dict["model_id"]),
322
+ "model_label": _model_label(str(row_dict["model_id"])),
323
+ "current_broad_comissing_score": float(row_dict["co_missingness_pattern_consistency"]),
324
+ "current_marginal_score": float(row_dict["marginal_missing_rate_consistency"]),
325
+ "current_family_score": float(row_dict["missingness_structure_score"]),
326
+ "strict_status": result["strict_status"],
327
+ "strict_pairwise_comissing_score": result["strict_pairwise_score"],
328
+ "strict_pair_count": int(result["strict_pair_count"]),
329
+ "active_missing_target_count": int(result["active_missing_target_count"]),
330
+ }
331
+ if result["strict_pairwise_score"] is not None:
332
+ payload["delta_strict_minus_current"] = round(
333
+ float(result["strict_pairwise_score"]) - float(row_dict["co_missingness_pattern_consistency"]), 6
334
+ )
335
+ else:
336
+ payload["delta_strict_minus_current"] = None
337
+
338
+ pair_rows = [
339
+ {
340
+ "dataset_id": str(row_dict["dataset_id"]),
341
+ "model_id": str(row_dict["model_id"]),
342
+ "model_label": _model_label(str(row_dict["model_id"])),
343
+ **pair_row,
344
+ }
345
+ for pair_row in result.get("pair_rows", [])
346
+ ]
347
+ return payload, pair_rows
348
+
349
+
350
+ def _build_review_outputs() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
351
+ asset_df = pd.read_csv(CURRENT_ASSET_CSV, encoding="utf-8-sig")
352
+ asset_df["model_id"] = asset_df["model_id"].map(_normalize_model)
353
+ asset_df = asset_df.loc[
354
+ (asset_df["status"] == "ok")
355
+ & (~asset_df["model_id"].isin(EXCLUDED_MODELS))
356
+ & asset_df["model_id"].isin(MODEL_ORDER)
357
+ ].copy()
358
+
359
+ review_rows: list[dict[str, Any]] = []
360
+ pair_rows: list[dict[str, Any]] = []
361
+
362
+ row_dicts = asset_df.to_dict(orient="records")
363
+ with ThreadPoolExecutor(max_workers=6) as executor:
364
+ futures = [executor.submit(_review_one_asset, row_dict) for row_dict in row_dicts]
365
+ for future in as_completed(futures):
366
+ payload, pair_payloads = future.result()
367
+ review_rows.append(payload)
368
+ pair_rows.extend(pair_payloads)
369
+
370
+ review_df = pd.DataFrame(review_rows).sort_values(["dataset_id", "model_label"]).reset_index(drop=True)
371
+ pair_df = pd.DataFrame(pair_rows)
372
+
373
+ overlap_df = review_df.loc[review_df["strict_pairwise_comissing_score"].notna()].copy()
374
+ grouped = []
375
+ for model_id, group in overlap_df.groupby("model_id", sort=False):
376
+ grouped.append(
377
+ {
378
+ "model_id": model_id,
379
+ "model_label": _model_label(model_id),
380
+ "dataset_count_overlap": int(group["dataset_id"].nunique()),
381
+ "panel_count_overlap": int(group.shape[0]),
382
+ "current_broad_comissing_score__mean": round(float(group["current_broad_comissing_score"].mean()), 6),
383
+ "strict_pairwise_comissing_score__mean": round(float(group["strict_pairwise_comissing_score"].mean()), 6),
384
+ "delta_strict_minus_current__mean": round(float(group["delta_strict_minus_current"].mean()), 6),
385
+ }
386
+ )
387
+ model_df = pd.DataFrame(grouped)
388
+ if not model_df.empty:
389
+ model_df["model_order"] = model_df["model_id"].map({m: i for i, m in enumerate(MODEL_ORDER)})
390
+ model_df = model_df.sort_values("model_order").drop(columns=["model_order"]).reset_index(drop=True)
391
+
392
+ coverage_rows = []
393
+ for dataset_id, group in review_df.groupby("dataset_id", sort=False):
394
+ coverage_rows.append(
395
+ {
396
+ "dataset_id": dataset_id,
397
+ "model_panel_count": int(group.shape[0]),
398
+ "strict_applicable_panel_count": int(group["strict_pairwise_comissing_score"].notna().sum()),
399
+ "active_missing_target_count": int(group["active_missing_target_count"].max()),
400
+ "strict_pair_count": int(pd.to_numeric(group["strict_pair_count"], errors="coerce").fillna(0).max()),
401
+ }
402
+ )
403
+ coverage_df = pd.DataFrame(coverage_rows).sort_values("dataset_id").reset_index(drop=True)
404
+ return review_df, pair_df, model_df, coverage_df
405
+
406
+
407
+ def _plot_review_figure(review_df: pd.DataFrame, model_df: pd.DataFrame, out_path: Path) -> None:
408
+ overlap_df = review_df.loc[review_df["strict_pairwise_comissing_score"].notna()].copy()
409
+
410
+ fig, axes = plt.subplots(1, 2, figsize=(14.0, 6.2), constrained_layout=True)
411
+ ax0, ax1 = axes
412
+
413
+ if not model_df.empty:
414
+ y_positions = np.arange(len(model_df))
415
+ for idx, row in enumerate(model_df.itertuples()):
416
+ current = float(row.current_broad_comissing_score__mean)
417
+ strict = float(row.strict_pairwise_comissing_score__mean)
418
+ color = MODEL_COLORS.get(str(row.model_id), "#777777")
419
+ ax0.plot([current, strict], [idx, idx], color=color, linewidth=2.0, alpha=0.9)
420
+ ax0.scatter(current, idx, s=60, color="white", edgecolor=color, linewidth=1.8, zorder=3)
421
+ ax0.scatter(strict, idx, s=60, color=color, edgecolor=color, linewidth=1.2, zorder=4)
422
+ ax0.set_yticks(y_positions)
423
+ ax0.set_yticklabels(list(model_df["model_label"]))
424
+ ax0.set_xlim(0.0, 1.02)
425
+ ax0.set_xlabel("Mean co-missingness score on overlap panels")
426
+ ax0.set_title("Model-level comparison\nhollow = current broad, solid = strict pairwise")
427
+ ax0.grid(axis="x", alpha=0.25, linewidth=0.8)
428
+ else:
429
+ ax0.text(0.5, 0.5, "No overlap panels available", ha="center", va="center", transform=ax0.transAxes)
430
+ ax0.set_axis_off()
431
+
432
+ if not overlap_df.empty:
433
+ ax1.scatter(
434
+ overlap_df["current_broad_comissing_score"],
435
+ overlap_df["strict_pairwise_comissing_score"],
436
+ s=34,
437
+ color="#4C78A8",
438
+ alpha=0.75,
439
+ edgecolors="none",
440
+ )
441
+ ax1.plot([0, 1], [0, 1], linestyle="--", color="#666666", linewidth=1.2)
442
+ ax1.set_xlim(0.0, 1.02)
443
+ ax1.set_ylim(0.0, 1.02)
444
+ ax1.set_xlabel("Current broad co-missingness score")
445
+ ax1.set_ylabel("Strict pairwise co-missingness score")
446
+ ax1.set_title(
447
+ "Dataset-model panels\n"
448
+ f"overlap n={overlap_df.shape[0]}, datasets={overlap_df['dataset_id'].nunique()}"
449
+ )
450
+ ax1.grid(alpha=0.25, linewidth=0.8)
451
+ else:
452
+ ax1.text(0.5, 0.5, "No strict-pairwise-applicable panels", ha="center", va="center", transform=ax1.transAxes)
453
+ ax1.set_axis_off()
454
+
455
+ fig.suptitle(
456
+ "Review audit: broad structured missingness vs strict pairwise co-missingness",
457
+ fontsize=14,
458
+ )
459
+ fig.savefig(out_path, dpi=220, bbox_inches="tight")
460
+ fig.savefig(out_path.with_suffix(".pdf"), bbox_inches="tight")
461
+ plt.close(fig)
462
+
463
+
464
+ def run_review() -> dict[str, Any]:
465
+ _ensure_dirs()
466
+ review_df, pair_df, model_df, coverage_df = _build_review_outputs()
467
+
468
+ _write_csv(review_df, DATA_DIR / "current_vs_strict_pairwise_asset_review.csv")
469
+ _write_csv(pair_df, DATA_DIR / "strict_pairwise_pair_scores.csv")
470
+ _write_csv(model_df, DATA_DIR / "current_vs_strict_pairwise_model_summary.csv")
471
+ _write_csv(coverage_df, DATA_DIR / "strict_pairwise_dataset_coverage.csv")
472
+
473
+ figure_path = FIG_DIR / "current_vs_strict_pairwise_review.png"
474
+ _plot_review_figure(review_df, model_df, figure_path)
475
+
476
+ overlap_df = review_df.loc[review_df["strict_pairwise_comissing_score"].notna()].copy()
477
+ note_lines = [
478
+ "# Strict Pairwise Review",
479
+ "",
480
+ "This is a temporary audit only. It does not change the official missingness bundle.",
481
+ "",
482
+ "## Audit definition",
483
+ "",
484
+ "- Current broad score: official `co_missingness_pattern_consistency` from the direct evaluator.",
485
+ "- Strict pairwise score: only use unordered pairs of active missing-target columns.",
486
+ "- 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.",
487
+ "- Final strict pairwise score = mean over all unordered missing-target pairs.",
488
+ "",
489
+ "## Coverage",
490
+ "",
491
+ f"- Asset/panel rows reviewed: `{review_df.shape[0]}`",
492
+ f"- Overlap rows with strict pairwise defined: `{overlap_df.shape[0]}`",
493
+ f"- Datasets with strict pairwise defined: `{overlap_df['dataset_id'].nunique() if not overlap_df.empty else 0}`",
494
+ f"- Models with strict pairwise defined: `{overlap_df['model_id'].nunique() if not overlap_df.empty else 0}`",
495
+ "",
496
+ "## Main caveat",
497
+ "",
498
+ "- Strict pairwise is undefined when a dataset has fewer than 2 active missing-target columns.",
499
+ "- So this review is a support-reduced audit, not a drop-in replacement for the official broad score.",
500
+ ]
501
+ (NOTES_DIR / "review.md").write_text("\n".join(note_lines) + "\n", encoding="utf-8")
502
+
503
+ return {
504
+ "review_csv": DATA_DIR / "current_vs_strict_pairwise_asset_review.csv",
505
+ "pair_csv": DATA_DIR / "strict_pairwise_pair_scores.csv",
506
+ "model_csv": DATA_DIR / "current_vs_strict_pairwise_model_summary.csv",
507
+ "coverage_csv": DATA_DIR / "strict_pairwise_dataset_coverage.csv",
508
+ "figure_png": figure_path,
509
+ "figure_pdf": figure_path.with_suffix(".pdf"),
510
+ "note_md": NOTES_DIR / "review.md",
511
+ "panel_count": int(review_df.shape[0]),
512
+ "overlap_panel_count": int(overlap_df.shape[0]),
513
+ }
514
+
515
+
516
+ if __name__ == "__main__":
517
+ outputs = run_review()
518
+ for key, value in outputs.items():
519
+ print(f"{key}: {value}")
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/runner.py ADDED
@@ -0,0 +1,1171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build a standardized missingness breakdown bundle.
3
+
4
+ This runner follows the same four-core-figure contract as the other
5
+ query five-part breakdown tasks:
6
+
7
+ 1. `missingness_tradeoff_scatter_main`
8
+ 2. `missingness_prefix_bars_appendix`
9
+ 3. `missingness_dataset_model_heatmap_appendix`
10
+ 4. `missingness_model_subitem_heatmap_appendix`
11
+
12
+ If the current unified analysis run still has no missingness query rows,
13
+ the runner emits explicit placeholder artifacts instead of silently
14
+ leaving the slot empty.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import csv
20
+ import json
21
+ import math
22
+ import subprocess
23
+ import sys
24
+ import argparse
25
+ from collections import defaultdict
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ import matplotlib
30
+
31
+ matplotlib.use("Agg")
32
+ import matplotlib.pyplot as plt
33
+ import pandas as pd
34
+
35
+ PROJECT_ROOT = Path(__file__).resolve().parents[4]
36
+ if str(PROJECT_ROOT) not in sys.path:
37
+ sys.path.insert(0, str(PROJECT_ROOT))
38
+
39
+ from src.eval.analytics_contract import annotate_query_row_with_contract
40
+ from src.eval.query_fivepart_breakdown.common_final import render_final_readme, sync_final_outputs
41
+ from src.eval.common import (
42
+ DEFAULT_SQL_SOURCE_VERSION,
43
+ resolve_requested_sql_source_version,
44
+ resolve_task_run_dir_for_sql_source,
45
+ sql_source_label,
46
+ )
47
+ from src.eval.query_fivepart_breakdown.common_final import versioned_name
48
+ from src.eval.query_fivepart_breakdown.common_heatmap_palette import (
49
+ format_heatmap_latex_cell,
50
+ get_heatmap_cmap,
51
+ )
52
+ from src.eval.query_fivepart_breakdown.common_model_subitem_grouped_bars import (
53
+ plot_model_subitem_grouped_bar_preview,
54
+ write_model_subitem_grouped_bar_tex,
55
+ )
56
+ from src.eval.query_fivepart_breakdown.common_model_subitem_heatmap import (
57
+ build_model_subitem_heatmap_df,
58
+ plot_model_subitem_heatmap_preview,
59
+ write_model_subitem_heatmap_tex,
60
+ )
61
+
62
+
63
+ EVALUATION_ROOT = PROJECT_ROOT / "Evaluation"
64
+ ANALYSIS_ROOT = EVALUATION_ROOT / "analysis"
65
+ OUTPUT_ROOT = EVALUATION_ROOT / "query_fivepart_breakdown" / "missingness_breakdown"
66
+ DATA_DIR = OUTPUT_ROOT / "data"
67
+ FIG_DIR = OUTPUT_ROOT / "figures"
68
+ FINAL_DIR = OUTPUT_ROOT / "final"
69
+ OUTPUT_VERSION_TAG = resolve_requested_sql_source_version("analysis", DEFAULT_SQL_SOURCE_VERSION)
70
+
71
+ TARGET_FAMILY = "missingness_structure"
72
+ REAL_MODEL_ID = "real"
73
+ SUBITEM_ORDER = [
74
+ "marginal_missing_rate_consistency",
75
+ "co_missingness_pattern_consistency",
76
+ ]
77
+ EXTRA_INSIGHT_METRICS = [
78
+ "co_missing_strength_score",
79
+ "co_missing_composite_score",
80
+ ]
81
+ SUBITEM_LABELS = {
82
+ "marginal_missing_rate_consistency": "Marginal missing-rate consistency",
83
+ "co_missingness_pattern_consistency": "Co-missingness pattern consistency",
84
+ }
85
+ MODEL_LABELS = {
86
+ "real": "REAL",
87
+ "arf": "ARF",
88
+ "bayesnet": "BayesNet",
89
+ "cdtd": "CDTD",
90
+ "codi": "CoDi",
91
+ "ctgan": "CTGAN",
92
+ "forestdiffusion": "ForestDiffusion",
93
+ "goggle": "GOGGLE",
94
+ "realtabformer": "RealTabFormer",
95
+ "rtf": "RealTabFormer",
96
+ "tabbyflow": "TabbyFlow",
97
+ "tabddpm": "TabDDPM",
98
+ "tabdiff": "TabDiff",
99
+ "tabpfgen": "TabPFGen",
100
+ "tabsyn": "TabSyn",
101
+ "tvae": "TVAE",
102
+ }
103
+ MODEL_COLORS = {
104
+ "real": "#000000",
105
+ "realtabformer": "#332288",
106
+ "tvae": "#4477AA",
107
+ "forestdiffusion": "#228833",
108
+ "tabddpm": "#EE7733",
109
+ "tabsyn": "#66CCEE",
110
+ "tabdiff": "#AA3377",
111
+ "ctgan": "#EE6677",
112
+ "arf": "#777777",
113
+ "bayesnet": "#CCBB44",
114
+ "tabpfgen": "#009988",
115
+ "tabbyflow": "#882255",
116
+ }
117
+ MODEL_ORDER = [
118
+ "arf",
119
+ "bayesnet",
120
+ "ctgan",
121
+ "forestdiffusion",
122
+ "realtabformer",
123
+ "tabbyflow",
124
+ "tabddpm",
125
+ "tabdiff",
126
+ "tabpfgen",
127
+ "tabsyn",
128
+ "tvae",
129
+ ]
130
+ EXCLUDED_MODELS = {"cdtd", "codi", "goggle"}
131
+ MODEL_ALIASES = {"rtf": "realtabformer"}
132
+ SERVER_PRIORITY = {"rtx_5090": 2, "rtx_pro_6000": 1}
133
+ ROOT_PRIORITY = {"SynOutput-5090": 2, "SynOutput": 1}
134
+
135
+
136
+ def _ensure_dirs() -> None:
137
+ for path in [OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR]:
138
+ path.mkdir(parents=True, exist_ok=True)
139
+
140
+
141
+ def _normalize_model(model_id: Any) -> str:
142
+ key = str(model_id or "").strip().lower()
143
+ return MODEL_ALIASES.get(key, key)
144
+
145
+
146
+ def _model_label(model_id: str) -> str:
147
+ return MODEL_LABELS.get(model_id, model_id)
148
+
149
+
150
+ def _model_sort_key(model_id: str) -> tuple[int, str]:
151
+ if str(model_id).strip().lower() == REAL_MODEL_ID:
152
+ return (0, _model_label(model_id))
153
+ return (1, _model_label(model_id).lower())
154
+
155
+
156
+ def _sorted_model_ids(model_ids: list[str] | set[str]) -> list[str]:
157
+ return sorted({str(item) for item in model_ids}, key=_model_sort_key)
158
+
159
+
160
+ def _dataset_prefix(dataset_id: str) -> str:
161
+ return str(dataset_id or "").strip().lower()[:1]
162
+
163
+
164
+ def _dataset_sort_key(dataset_id: str) -> tuple[int, int, str]:
165
+ text = str(dataset_id or "").strip()
166
+ if len(text) < 2 or not text[1:].isdigit():
167
+ return (99, 10**9, text)
168
+ prefix_order = {"c": 0, "m": 1, "n": 2}.get(text[0].lower(), 50)
169
+ return (prefix_order, int(text[1:]), text)
170
+
171
+
172
+ def _asset_sort_key(row: dict[str, Any]) -> tuple[int, int, str, str]:
173
+ server = str(row.get("server_type") or "").strip().lower()
174
+ root_name = str(row.get("root_name") or "").strip()
175
+ run_id = str(row.get("run_id") or "").strip()
176
+ asset_key = str(row.get("asset_key") or "").strip()
177
+ return (
178
+ SERVER_PRIORITY.get(server, 0),
179
+ ROOT_PRIORITY.get(root_name, 0),
180
+ run_id,
181
+ asset_key,
182
+ )
183
+
184
+
185
+ def _find_primary_analysis_run() -> Path:
186
+ resolved = resolve_task_run_dir_for_sql_source("analysis", OUTPUT_VERSION_TAG)
187
+ if resolved is not None:
188
+ return resolved
189
+ raise FileNotFoundError(f"No analysis run found for sql_source_version={OUTPUT_VERSION_TAG!r}.")
190
+
191
+
192
+ def _run_direct_missingness_eval() -> dict[str, Path]:
193
+ from tests.comissing_condition_eval import evaluate_all_synthetic_assets
194
+
195
+ direct_root = DATA_DIR / "_direct_eval"
196
+ expected = {
197
+ "dataset_context": direct_root / "co_missing_dataset_context.csv",
198
+ "asset_scores": direct_root / "co_missing_asset_scores.csv",
199
+ "target_scores": direct_root / "co_missing_target_scores.csv",
200
+ "model_dataset_summary": direct_root / "co_missing_model_dataset_summary.csv",
201
+ "model_overall_summary": direct_root / "co_missing_model_overall_summary.csv",
202
+ }
203
+ if all(path.exists() for path in expected.values()):
204
+ try:
205
+ asset_df = pd.read_csv(expected["asset_scores"], encoding="utf-8-sig", nrows=5)
206
+ model_dataset_df = pd.read_csv(expected["model_dataset_summary"], encoding="utf-8-sig", nrows=5)
207
+ required_columns = {"co_missing_strength_score", "co_missing_composite_score"}
208
+ if required_columns.issubset(set(asset_df.columns)) and required_columns.issubset(set(model_dataset_df.columns)):
209
+ return expected
210
+ except Exception:
211
+ pass
212
+ return evaluate_all_synthetic_assets(direct_root)
213
+
214
+
215
+ def _load_primary_assets(asset_csv: Path) -> tuple[dict[tuple[str, str], dict[str, Any]], list[dict[str, Any]]]:
216
+ with asset_csv.open("r", encoding="utf-8-sig", newline="") as handle:
217
+ rows = [dict(row) for row in csv.DictReader(handle)]
218
+
219
+ grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
220
+ for row in rows:
221
+ dataset_id = str(row.get("dataset_id") or "").strip()
222
+ model_id = _normalize_model(row.get("model_id"))
223
+ if not dataset_id or not model_id or model_id in EXCLUDED_MODELS:
224
+ continue
225
+ row["model_id"] = model_id
226
+ row["model_label"] = _model_label(model_id)
227
+ grouped[(dataset_id, model_id)].append(row)
228
+
229
+ chosen: dict[tuple[str, str], dict[str, Any]] = {}
230
+ audit_rows: list[dict[str, Any]] = []
231
+ for key, items in grouped.items():
232
+ ranked = sorted(items, key=_asset_sort_key, reverse=True)
233
+ chosen[key] = ranked[0]
234
+ for dropped in ranked[1:]:
235
+ audit_rows.append(
236
+ {
237
+ "dataset_id": key[0],
238
+ "model_id": key[1],
239
+ "kept_asset_key": ranked[0].get("asset_key"),
240
+ "dropped_asset_key": dropped.get("asset_key"),
241
+ "kept_run_id": ranked[0].get("run_id"),
242
+ "dropped_run_id": dropped.get("run_id"),
243
+ }
244
+ )
245
+ return chosen, audit_rows
246
+
247
+
248
+ def _stream_missingness_query_rows(
249
+ query_jsonl: Path,
250
+ primary_assets: dict[tuple[str, str], dict[str, Any]],
251
+ ) -> list[dict[str, Any]]:
252
+ chosen_keys = {
253
+ (dataset_id, model_id): str(row.get("asset_key") or "")
254
+ for (dataset_id, model_id), row in primary_assets.items()
255
+ }
256
+ out: list[dict[str, Any]] = []
257
+ with query_jsonl.open("r", encoding="utf-8") as handle:
258
+ for raw in handle:
259
+ line = raw.strip()
260
+ if not line:
261
+ continue
262
+ row = json.loads(line)
263
+ dataset_id = str(row.get("dataset_id") or "").strip()
264
+ model_id = _normalize_model(row.get("model_id"))
265
+ if not dataset_id or not model_id or model_id in EXCLUDED_MODELS:
266
+ continue
267
+ if chosen_keys.get((dataset_id, model_id)) != str(row.get("asset_key") or ""):
268
+ continue
269
+ if str(row.get("family_id") or "").strip().lower() != TARGET_FAMILY:
270
+ continue
271
+ annotated = dict(row)
272
+ if not annotated.get("canonical_subitem_id"):
273
+ annotated = annotate_query_row_with_contract(annotated)
274
+ subitem_id = str(annotated.get("canonical_subitem_id") or "").strip()
275
+ if subitem_id not in SUBITEM_ORDER:
276
+ continue
277
+ try:
278
+ score_value = float(annotated.get("query_score"))
279
+ except Exception:
280
+ continue
281
+ out.append(
282
+ {
283
+ "dataset_id": dataset_id,
284
+ "dataset_prefix": _dataset_prefix(dataset_id),
285
+ "model_id": model_id,
286
+ "model_label": _model_label(model_id),
287
+ "asset_key": str(annotated.get("asset_key") or ""),
288
+ "subitem_id": subitem_id,
289
+ "subitem_label": SUBITEM_LABELS[subitem_id],
290
+ "query_id": str(annotated.get("query_id") or ""),
291
+ "query_score": score_value,
292
+ "template_id": str(annotated.get("template_id") or ""),
293
+ "template_name": str(annotated.get("template_name") or ""),
294
+ "question": str(annotated.get("question") or ""),
295
+ "sql_engine": str(annotated.get("sql_engine") or ""),
296
+ }
297
+ )
298
+ return out
299
+
300
+
301
+ def _inject_real_rows(query_rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
302
+ by_dataset_query: dict[tuple[str, str], dict[str, Any]] = {}
303
+ for row in query_rows:
304
+ key = (str(row["dataset_id"]), str(row["query_id"]))
305
+ if key not in by_dataset_query:
306
+ by_dataset_query[key] = row
307
+
308
+ real_rows: list[dict[str, Any]] = []
309
+ for (dataset_id, _query_id), row in sorted(by_dataset_query.items(), key=lambda item: (_dataset_sort_key(item[0][0]), item[0][1])):
310
+ real_rows.append(
311
+ {
312
+ **row,
313
+ "model_id": REAL_MODEL_ID,
314
+ "model_label": _model_label(REAL_MODEL_ID),
315
+ "asset_key": f"{dataset_id}__real_reference",
316
+ "query_score": 1.0,
317
+ "sql_engine": "real-reference",
318
+ }
319
+ )
320
+ return query_rows + real_rows
321
+
322
+
323
+ def _write_csv(df: pd.DataFrame, path: Path) -> None:
324
+ df.to_csv(path, index=False, encoding="utf-8")
325
+
326
+
327
+ def _metric_stats(series: pd.Series) -> dict[str, float | int | None]:
328
+ clean = pd.to_numeric(series, errors="coerce").dropna()
329
+ n = int(clean.shape[0])
330
+ if n == 0:
331
+ return {
332
+ "n": 0,
333
+ "mean": None,
334
+ "std": None,
335
+ "se": None,
336
+ "ci95_low": None,
337
+ "ci95_high": None,
338
+ "ci95_radius": None,
339
+ }
340
+ mean_val = float(clean.mean())
341
+ std_val = float(clean.std(ddof=1)) if n > 1 else 0.0
342
+ se_val = float(std_val / math.sqrt(n)) if n > 1 else 0.0
343
+ ci_radius = 1.96 * se_val
344
+ return {
345
+ "n": n,
346
+ "mean": round(mean_val, 6),
347
+ "std": round(std_val, 6),
348
+ "se": round(se_val, 6),
349
+ "ci95_low": round(mean_val - ci_radius, 6),
350
+ "ci95_high": round(mean_val + ci_radius, 6),
351
+ "ci95_radius": round(ci_radius, 6),
352
+ }
353
+
354
+
355
+ def _escape_tex(text: str) -> str:
356
+ replacements = {
357
+ "\\": r"\textbackslash{}",
358
+ "&": r"\&",
359
+ "%": r"\%",
360
+ "$": r"\$",
361
+ "#": r"\#",
362
+ "_": r"\_",
363
+ "{": r"\{",
364
+ "}": r"\}",
365
+ }
366
+ out = str(text)
367
+ for src, dst in replacements.items():
368
+ out = out.replace(src, dst)
369
+ return out
370
+
371
+
372
+ def _tex_preamble() -> str:
373
+ return "\n".join(
374
+ [
375
+ r"\documentclass[tikz,border=4pt]{standalone}",
376
+ r"\usepackage{pgfplots}",
377
+ r"\usepgfplotslibrary{groupplots}",
378
+ r"\usepackage{xcolor}",
379
+ r"\pgfplotsset{compat=1.18}",
380
+ "",
381
+ ]
382
+ )
383
+
384
+
385
+ def _build_dataset_model_scores(query_df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
386
+ subitems = (
387
+ query_df.groupby(
388
+ ["dataset_id", "dataset_prefix", "model_id", "model_label", "subitem_id", "subitem_label"],
389
+ as_index=False,
390
+ )
391
+ .agg(query_count=("query_id", "count"), subitem_score=("query_score", "mean"))
392
+ .reset_index(drop=True)
393
+ )
394
+ pivot = (
395
+ subitems.pivot_table(
396
+ index=["dataset_id", "dataset_prefix", "model_id", "model_label"],
397
+ columns="subitem_id",
398
+ values="subitem_score",
399
+ aggfunc="mean",
400
+ )
401
+ .reset_index()
402
+ .rename_axis(None, axis=1)
403
+ )
404
+ counts = (
405
+ subitems.pivot_table(
406
+ index=["dataset_id", "dataset_prefix", "model_id", "model_label"],
407
+ columns="subitem_id",
408
+ values="query_count",
409
+ aggfunc="sum",
410
+ )
411
+ .reset_index()
412
+ .rename_axis(None, axis=1)
413
+ )
414
+ wide = pivot.merge(counts, on=["dataset_id", "dataset_prefix", "model_id", "model_label"], suffixes=("", "__query_count"))
415
+ for metric in SUBITEM_ORDER:
416
+ wide[metric] = pd.to_numeric(wide[metric], errors="coerce")
417
+ wide["missingness_structure_score"] = wide[SUBITEM_ORDER].mean(axis=1, skipna=True)
418
+ wide["marginal_minus_comissing"] = wide["marginal_missing_rate_consistency"] - wide["co_missingness_pattern_consistency"]
419
+ wide["active_subitem_count"] = wide[SUBITEM_ORDER].notna().sum(axis=1)
420
+ wide["dataset_sort"] = wide["dataset_id"].map(_dataset_sort_key)
421
+ wide["model_sort"] = wide["model_id"].map(_model_sort_key)
422
+ wide = wide.sort_values(["dataset_sort", "model_sort"]).drop(columns=["dataset_sort", "model_sort"]).reset_index(drop=True)
423
+ return subitems, wide
424
+
425
+
426
+ def _build_dataset_model_scores_from_direct_summary(model_dataset_df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
427
+ if model_dataset_df.empty:
428
+ return (
429
+ pd.DataFrame(
430
+ columns=[
431
+ "dataset_id",
432
+ "dataset_prefix",
433
+ "model_id",
434
+ "model_label",
435
+ "subitem_id",
436
+ "subitem_label",
437
+ "query_count",
438
+ "subitem_score",
439
+ ]
440
+ ),
441
+ pd.DataFrame(
442
+ columns=[
443
+ "dataset_id",
444
+ "dataset_prefix",
445
+ "model_id",
446
+ "model_label",
447
+ *SUBITEM_ORDER,
448
+ *EXTRA_INSIGHT_METRICS,
449
+ "missingness_structure_score",
450
+ "marginal_minus_comissing",
451
+ "profile_minus_strength",
452
+ "active_subitem_count",
453
+ "asset_count",
454
+ "applicable_asset_count",
455
+ ]
456
+ ),
457
+ )
458
+
459
+ df = model_dataset_df.copy()
460
+ df["model_id"] = df["model_id"].map(_normalize_model)
461
+ df = df.loc[~df["model_id"].isin(EXCLUDED_MODELS)].copy()
462
+ df["model_label"] = df["model_id"].map(_model_label)
463
+ df["dataset_prefix"] = df["dataset_id"].map(_dataset_prefix)
464
+ for metric in SUBITEM_ORDER + EXTRA_INSIGHT_METRICS + ["missingness_structure_score"]:
465
+ if metric not in df.columns:
466
+ df[metric] = pd.NA
467
+ df[metric] = pd.to_numeric(df[metric], errors="coerce")
468
+ df["marginal_minus_comissing"] = df["marginal_missing_rate_consistency"] - df["co_missingness_pattern_consistency"]
469
+ df["profile_minus_strength"] = df["co_missingness_pattern_consistency"] - df["co_missing_strength_score"]
470
+ df["active_subitem_count"] = df[SUBITEM_ORDER].notna().sum(axis=1)
471
+ df["dataset_sort"] = df["dataset_id"].map(_dataset_sort_key)
472
+ df["model_sort"] = df["model_id"].map(_model_sort_key)
473
+ wide = (
474
+ df.sort_values(["dataset_sort", "model_sort"])[
475
+ [
476
+ "dataset_id",
477
+ "dataset_prefix",
478
+ "model_id",
479
+ "model_label",
480
+ *SUBITEM_ORDER,
481
+ *EXTRA_INSIGHT_METRICS,
482
+ "missingness_structure_score",
483
+ "marginal_minus_comissing",
484
+ "profile_minus_strength",
485
+ "active_subitem_count",
486
+ "asset_count",
487
+ "applicable_asset_count",
488
+ ]
489
+ ]
490
+ .reset_index(drop=True)
491
+ )
492
+
493
+ subitem_rows: list[dict[str, Any]] = []
494
+ for row in wide.itertuples(index=False):
495
+ applicable_count = int(getattr(row, "applicable_asset_count", 0) or 0)
496
+ for subitem_id in SUBITEM_ORDER:
497
+ subitem_rows.append(
498
+ {
499
+ "dataset_id": row.dataset_id,
500
+ "dataset_prefix": row.dataset_prefix,
501
+ "model_id": row.model_id,
502
+ "model_label": row.model_label,
503
+ "subitem_id": subitem_id,
504
+ "subitem_label": SUBITEM_LABELS[subitem_id],
505
+ "query_count": applicable_count,
506
+ "subitem_score": getattr(row, subitem_id, None),
507
+ }
508
+ )
509
+ return pd.DataFrame(subitem_rows), wide
510
+
511
+
512
+ def _build_model_summary(dataset_model_df: pd.DataFrame) -> pd.DataFrame:
513
+ rows: list[dict[str, Any]] = []
514
+ metrics = SUBITEM_ORDER + EXTRA_INSIGHT_METRICS + ["missingness_structure_score", "marginal_minus_comissing", "profile_minus_strength"]
515
+ for model_id, group in dataset_model_df.groupby("model_id", sort=False):
516
+ payload = {
517
+ "model_id": model_id,
518
+ "model_label": _model_label(model_id),
519
+ "dataset_count": int(group["dataset_id"].nunique()),
520
+ "dataset_prefixes": ",".join(sorted(group["dataset_prefix"].dropna().astype(str).unique())),
521
+ }
522
+ for metric in metrics:
523
+ stats = _metric_stats(group[metric])
524
+ payload[f"{metric}__mean"] = stats["mean"]
525
+ payload[f"{metric}__std"] = stats["std"]
526
+ payload[f"{metric}__se"] = stats["se"]
527
+ payload[f"{metric}__ci95_low"] = stats["ci95_low"]
528
+ payload[f"{metric}__ci95_high"] = stats["ci95_high"]
529
+ payload[f"{metric}__ci95_radius"] = stats["ci95_radius"]
530
+ rows.append(payload)
531
+
532
+ summary = pd.DataFrame(rows)
533
+ if summary.empty:
534
+ return summary
535
+ summary["model_sort"] = summary["model_id"].map(_model_sort_key)
536
+ return summary.sort_values(["model_sort", "model_id"]).drop(columns=["model_sort"]).reset_index(drop=True)
537
+
538
+
539
+ def _build_prefix_summary(dataset_model_df: pd.DataFrame) -> pd.DataFrame:
540
+ rows: list[dict[str, Any]] = []
541
+ for (model_id, prefix), group in dataset_model_df.groupby(["model_id", "dataset_prefix"], sort=False):
542
+ rows.append(
543
+ {
544
+ "model_id": model_id,
545
+ "model_label": _model_label(model_id),
546
+ "dataset_prefix": prefix,
547
+ "dataset_count": int(group["dataset_id"].nunique()),
548
+ "marginal_missing_rate_consistency": round(float(pd.to_numeric(group["marginal_missing_rate_consistency"], errors="coerce").dropna().mean()), 6),
549
+ "co_missingness_pattern_consistency": round(float(pd.to_numeric(group["co_missingness_pattern_consistency"], errors="coerce").dropna().mean()), 6),
550
+ "co_missing_strength_score": round(float(pd.to_numeric(group["co_missing_strength_score"], errors="coerce").dropna().mean()), 6),
551
+ "missingness_structure_score": round(float(pd.to_numeric(group["missingness_structure_score"], errors="coerce").dropna().mean()), 6),
552
+ }
553
+ )
554
+ summary = pd.DataFrame(rows)
555
+ if summary.empty:
556
+ return summary
557
+ summary["model_sort"] = summary["model_id"].map(_model_sort_key)
558
+ return summary.sort_values(["dataset_prefix", "model_sort"]).drop(columns=["model_sort"]).reset_index(drop=True)
559
+
560
+
561
+ def _build_dataset_summary(dataset_model_df: pd.DataFrame) -> pd.DataFrame:
562
+ rows: list[dict[str, Any]] = []
563
+ for dataset_id, group in dataset_model_df.groupby("dataset_id", sort=False):
564
+ rows.append(
565
+ {
566
+ "dataset_id": dataset_id,
567
+ "dataset_prefix": _dataset_prefix(dataset_id),
568
+ "model_count": int(group["model_id"].nunique()),
569
+ "missingness_structure_score": round(float(pd.to_numeric(group["missingness_structure_score"], errors="coerce").dropna().mean()), 6),
570
+ }
571
+ )
572
+ summary = pd.DataFrame(rows)
573
+ if summary.empty:
574
+ return summary
575
+ summary["dataset_sort"] = summary["dataset_id"].map(_dataset_sort_key)
576
+ return summary.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True)
577
+
578
+
579
+ def _build_heatmap_data(dataset_model_df: pd.DataFrame) -> pd.DataFrame:
580
+ heatmap = (
581
+ dataset_model_df.pivot_table(
582
+ index="dataset_id",
583
+ columns="model_id",
584
+ values="missingness_structure_score",
585
+ aggfunc="mean",
586
+ )
587
+ .reset_index()
588
+ .rename_axis(None, axis=1)
589
+ )
590
+ if heatmap.empty:
591
+ return heatmap
592
+ ordered_models = [item for item in _sorted_model_ids(dataset_model_df["model_id"].tolist()) if item in heatmap.columns]
593
+ heatmap["dataset_sort"] = heatmap["dataset_id"].map(_dataset_sort_key)
594
+ heatmap = heatmap.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True)
595
+ return heatmap[["dataset_id"] + ordered_models]
596
+
597
+
598
+ def _build_prefix_plot_data(prefix_summary_df: pd.DataFrame) -> pd.DataFrame:
599
+ rows: list[dict[str, Any]] = []
600
+ for model_id in _sorted_model_ids(prefix_summary_df["model_id"].tolist()):
601
+ payload: dict[str, Any] = {"model_id": model_id, "model_label": _model_label(model_id)}
602
+ subset = prefix_summary_df.loc[prefix_summary_df["model_id"] == model_id]
603
+ for prefix in ["c", "m", "n"]:
604
+ match = subset.loc[subset["dataset_prefix"] == prefix, "missingness_structure_score"]
605
+ payload[prefix] = float(match.iloc[0]) if not match.empty else None
606
+ rows.append(payload)
607
+ return pd.DataFrame(rows)
608
+
609
+
610
+ def _write_tradeoff_tex(model_summary_df: pd.DataFrame, path: Path) -> None:
611
+ color_defs = [
612
+ rf"\definecolor{{model{row.model_id}}}{{HTML}}{{{MODEL_COLORS[row.model_id].replace('#', '')}}}"
613
+ for row in model_summary_df.itertuples()
614
+ if row.model_id in MODEL_COLORS
615
+ ]
616
+ lines = [
617
+ _tex_preamble(),
618
+ *color_defs,
619
+ r"\begin{document}",
620
+ r"\begin{tikzpicture}",
621
+ r"""\begin{axis}[
622
+ width=11.2cm,
623
+ height=8.4cm,
624
+ xmin=0, xmax=1.02,
625
+ ymin=0, ymax=1.02,
626
+ xlabel={Marginal missing-rate consistency},
627
+ ylabel={Co-missingness pattern consistency},
628
+ grid=major,
629
+ grid style={gray!20},
630
+ ]""",
631
+ ]
632
+ for row in model_summary_df.itertuples():
633
+ x = getattr(row, "marginal_missing_rate_consistency__mean")
634
+ y = getattr(row, "co_missingness_pattern_consistency__mean")
635
+ if x is None or y is None:
636
+ continue
637
+ color_name = f"model{row.model_id}"
638
+ lines.append(
639
+ rf"\addplot[only marks, mark=*, mark size=2.2pt, {color_name}] coordinates {{({float(x):.6f},{float(y):.6f})}};"
640
+ )
641
+ lines.append(
642
+ rf"\node[anchor=west, font=\scriptsize, text={color_name}] at (axis cs:{float(x):.6f},{float(y):.6f}) {{{_escape_tex(row.model_label)}}};"
643
+ )
644
+ lines.extend([r"\end{axis}", r"\end{tikzpicture}", r"\end{document}", ""])
645
+ path.write_text("\n".join(lines), encoding="utf-8")
646
+
647
+
648
+ def _write_prefix_bar_tex(prefix_plot_df: pd.DataFrame, path: Path) -> None:
649
+ model_labels = [_escape_tex(str(item)) for item in prefix_plot_df["model_label"].tolist()]
650
+ xticklabels = ",".join(model_labels)
651
+ color_defs = [
652
+ rf"\definecolor{{model{row.model_id}}}{{HTML}}{{{MODEL_COLORS[row.model_id].replace('#', '')}}}"
653
+ for row in prefix_plot_df.itertuples()
654
+ if row.model_id in MODEL_COLORS
655
+ ]
656
+ lines = [
657
+ _tex_preamble(),
658
+ *color_defs,
659
+ r"\begin{document}",
660
+ r"\begin{tikzpicture}",
661
+ r"""\begin{groupplot}[
662
+ group style={group size=3 by 1, horizontal sep=1.0cm},
663
+ width=0.31\textwidth,
664
+ height=0.46\textwidth,
665
+ ymin=0, ymax=1.02,
666
+ xtick={1,...,%d},
667
+ xticklabels={%s},
668
+ x tick label style={rotate=60, anchor=east, font=\scriptsize},
669
+ grid=major,
670
+ grid style={gray!20},
671
+ ]"""
672
+ % (len(model_labels), xticklabels),
673
+ ]
674
+ for prefix in ["c", "m", "n"]:
675
+ lines.append(rf"\nextgroupplot[title={{{prefix.upper()} datasets}}, ylabel={{Mean score}}]")
676
+ for idx, row in enumerate(prefix_plot_df.itertuples(), start=1):
677
+ value = getattr(row, prefix, None)
678
+ if value is None or pd.isna(value):
679
+ continue
680
+ color_name = f"model{row.model_id}" if row.model_id in MODEL_COLORS else "gray"
681
+ lines.append(rf"\addplot[ybar, draw={color_name}, fill={color_name}] coordinates {{({idx},{float(value):.6f})}};")
682
+ lines.extend([r"\end{groupplot}", r"\end{tikzpicture}", r"\end{document}", ""])
683
+ path.write_text("\n".join(lines), encoding="utf-8")
684
+
685
+
686
+ def _write_heatmap_tex(heatmap_df: pd.DataFrame, path: Path) -> None:
687
+ ordered = heatmap_df.copy()
688
+ model_cols = [column for column in ordered.columns if column != "dataset_id"]
689
+ display = ordered[["dataset_id"] + model_cols].copy().fillna("")
690
+ lines = [
691
+ r"\documentclass{standalone}",
692
+ r"\usepackage[table]{xcolor}",
693
+ r"\usepackage{xcolor}",
694
+ r"\usepackage{booktabs}",
695
+ r"\begin{document}",
696
+ r"\scriptsize",
697
+ r"\textbf{Missingness dataset-model heatmap}\\[0.4em]",
698
+ r"\emph{Score, 0--1; missing cells stay white.}\\[0.5em]",
699
+ r"\setlength{\tabcolsep}{4pt}",
700
+ rf"\begin{{tabular}}{{l{'c' * len(model_cols)}}}",
701
+ r"\toprule",
702
+ "Dataset & " + " & ".join(_escape_tex(column) for column in model_cols) + r" \\",
703
+ r"\midrule",
704
+ ]
705
+ for row in display.itertuples(index=False):
706
+ cells = [_escape_tex(str(getattr(row, "dataset_id")))]
707
+ for model in model_cols:
708
+ cells.append(format_heatmap_latex_cell(getattr(row, model)))
709
+ lines.append(" & ".join(cells) + r" \\")
710
+ lines.extend([r"\bottomrule", r"\end{tabular}", r"\end{document}", ""])
711
+ path.write_text("\n".join(lines), encoding="utf-8")
712
+
713
+
714
+ def _plot_tradeoff_preview(model_summary_df: pd.DataFrame, pdf_path: Path, png_path: Path) -> None:
715
+ fig, ax = plt.subplots(figsize=(8.2, 6.0))
716
+ for row in model_summary_df.itertuples():
717
+ x = getattr(row, "marginal_missing_rate_consistency__mean")
718
+ y = getattr(row, "co_missingness_pattern_consistency__mean")
719
+ if x is None or y is None:
720
+ continue
721
+ color = MODEL_COLORS.get(str(row.model_id), "#777777")
722
+ ax.scatter(float(x), float(y), s=56, color=color)
723
+ ax.text(float(x) + 0.012, float(y) + 0.008, str(row.model_label), fontsize=8, color=color)
724
+ ax.set_xlim(0.0, 1.02)
725
+ ax.set_ylim(0.0, 1.02)
726
+ ax.set_xlabel("Marginal missing-rate consistency")
727
+ ax.set_ylabel("Co-missingness pattern consistency")
728
+ ax.set_title("Missingness trade-off scatter")
729
+ ax.grid(alpha=0.25)
730
+ fig.tight_layout()
731
+ fig.savefig(pdf_path, bbox_inches="tight")
732
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
733
+ plt.close(fig)
734
+
735
+
736
+ def _plot_prefix_bar_preview(prefix_plot_df: pd.DataFrame, pdf_path: Path, png_path: Path) -> None:
737
+ fig, axes = plt.subplots(1, 3, figsize=(14.4, 6.2), sharey=True)
738
+ for ax, prefix in zip(axes, ["c", "m", "n"]):
739
+ values = pd.to_numeric(prefix_plot_df[prefix], errors="coerce")
740
+ colors = [MODEL_COLORS.get(model_id, "#777777") for model_id in prefix_plot_df["model_id"]]
741
+ ax.bar(range(len(prefix_plot_df)), values, color=colors)
742
+ ax.set_title(f"{prefix.upper()} datasets")
743
+ ax.set_ylim(0.0, 1.02)
744
+ ax.set_xticks(range(len(prefix_plot_df)))
745
+ ax.set_xticklabels(prefix_plot_df["model_label"], rotation=60, ha="right", fontsize=8)
746
+ ax.grid(axis="y", alpha=0.25)
747
+ axes[0].set_ylabel("Mean score")
748
+ fig.tight_layout()
749
+ fig.savefig(pdf_path, bbox_inches="tight")
750
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
751
+ plt.close(fig)
752
+
753
+
754
+ def _plot_heatmap_preview(heatmap_df: pd.DataFrame, pdf_path: Path, png_path: Path) -> None:
755
+ ordered = heatmap_df.copy()
756
+ model_cols = [column for column in ordered.columns if column != "dataset_id"]
757
+ matrix = ordered[model_cols].to_numpy(dtype=float)
758
+ fig_height = max(7.2, 0.22 * len(ordered) + 1.8)
759
+ fig, ax = plt.subplots(figsize=(10.4, fig_height))
760
+ im = ax.imshow(matrix, vmin=0.0, vmax=1.0, aspect="auto", cmap=get_heatmap_cmap())
761
+ ax.set_xticks(range(len(model_cols)))
762
+ ax.set_xticklabels(model_cols, rotation=60, ha="right", fontsize=8)
763
+ ax.set_yticks(range(len(ordered)))
764
+ ax.set_yticklabels(ordered["dataset_id"], fontsize=7)
765
+ ax.set_title("Missingness dataset-model heatmap")
766
+ fig.colorbar(im, ax=ax, fraction=0.035, pad=0.02)
767
+ fig.tight_layout()
768
+ fig.savefig(pdf_path, bbox_inches="tight")
769
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
770
+ plt.close(fig)
771
+
772
+
773
+ def _write_placeholder_tex(path: Path, title: str, message: str) -> None:
774
+ content = "\n".join(
775
+ [
776
+ _tex_preamble(),
777
+ r"\begin{document}",
778
+ r"\begin{tikzpicture}",
779
+ r"\node[draw=gray!60, rounded corners=4pt, fill=gray!8, text width=11.5cm, align=center, inner sep=12pt] {",
780
+ rf"\textbf{{{_escape_tex(title)}}}\\[0.7em]{_escape_tex(message)}",
781
+ r"};",
782
+ r"\end{tikzpicture}",
783
+ r"\end{document}",
784
+ "",
785
+ ]
786
+ )
787
+ path.write_text(content, encoding="utf-8")
788
+
789
+
790
+ def _plot_placeholder_preview(pdf_path: Path, png_path: Path, title: str, message: str) -> None:
791
+ fig, ax = plt.subplots(figsize=(8.6, 4.8))
792
+ ax.axis("off")
793
+ ax.text(
794
+ 0.5,
795
+ 0.62,
796
+ title,
797
+ ha="center",
798
+ va="center",
799
+ fontsize=15,
800
+ fontweight="bold",
801
+ )
802
+ ax.text(
803
+ 0.5,
804
+ 0.38,
805
+ message,
806
+ ha="center",
807
+ va="center",
808
+ fontsize=11,
809
+ wrap=True,
810
+ )
811
+ fig.tight_layout()
812
+ fig.savefig(pdf_path, bbox_inches="tight")
813
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
814
+ plt.close(fig)
815
+
816
+
817
+ def _try_compile_tex(tex_path: Path) -> tuple[bool, str]:
818
+ try:
819
+ proc = subprocess.run(
820
+ ["latexmk", "-pdf", tex_path.name],
821
+ cwd=tex_path.parent,
822
+ stdout=subprocess.PIPE,
823
+ stderr=subprocess.STDOUT,
824
+ text=True,
825
+ check=False,
826
+ )
827
+ except FileNotFoundError:
828
+ return False, "latexmk not available"
829
+ return proc.returncode == 0, proc.stdout[-1200:]
830
+
831
+
832
+ def _write_placeholder_bundle(run_dir: Path, audit_rows: list[dict[str, Any]]) -> dict[str, Any]:
833
+ message = (
834
+ "No `missingness_structure` query rows were found in the current unified analysis run. "
835
+ "These standardized placeholders keep the five-part appendix structure stable until missingness queries are emitted."
836
+ )
837
+ placeholder_specs = [
838
+ ("missingness_tradeoff_scatter_main", "Missingness Trade-Off Placeholder"),
839
+ ("missingness_prefix_bars_appendix", "Missingness Prefix Placeholder"),
840
+ ("missingness_dataset_model_heatmap_appendix", "Missingness Heatmap Placeholder"),
841
+ ("missingness_model_subitem_heatmap_appendix", "Missingness Model-Subitem Placeholder"),
842
+ ("missingness_family_subitem_bars_appendix", "Missingness Family/Subitem Bars Placeholder"),
843
+ ]
844
+ final_files: list[Path] = [DATA_DIR / "duplicate_asset_audit.csv", DATA_DIR / "missingness_query_rows.csv", OUTPUT_ROOT / "analysis_report.md"]
845
+ must_do_aliases: dict[str, Path] = {}
846
+ compile_notes: dict[str, tuple[bool, str]] = {}
847
+ for stem, title in placeholder_specs:
848
+ tex_path = FIG_DIR / f"{stem}.tex"
849
+ pdf_path = FIG_DIR / f"{stem}.pdf"
850
+ png_path = FIG_DIR / f"{stem}.png"
851
+ _write_placeholder_tex(tex_path, title, message)
852
+ _plot_placeholder_preview(pdf_path, png_path, title, message)
853
+ compile_notes[stem] = _try_compile_tex(tex_path)
854
+ final_files.extend([tex_path, pdf_path, png_path])
855
+ must_do_aliases[f"{stem}.tex"] = tex_path
856
+ must_do_aliases[f"{stem}.pdf"] = pdf_path
857
+ must_do_aliases[f"{stem}.png"] = png_path
858
+
859
+ _write_csv(pd.DataFrame(audit_rows), DATA_DIR / "duplicate_asset_audit.csv")
860
+ _write_csv(pd.DataFrame(columns=["dataset_id", "model_id", "subitem_id", "query_id", "query_score"]), DATA_DIR / "missingness_query_rows.csv")
861
+ (OUTPUT_ROOT / "analysis_report.md").write_text(
862
+ "\n".join(
863
+ [
864
+ "# Missingness Breakdown",
865
+ "",
866
+ f"- Source analysis run: `{run_dir.name}`",
867
+ "- Current status: no missingness query rows available in the unified analysis export.",
868
+ "- Action taken: emitted standardized placeholder must-do figures so the five-part appendix structure stays complete.",
869
+ "",
870
+ ]
871
+ ),
872
+ encoding="utf-8",
873
+ )
874
+ version_tag = OUTPUT_VERSION_TAG
875
+ readme = render_final_readme(
876
+ title="Missingness Breakdown Final",
877
+ 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.",
878
+ primary_files=[versioned_name(name, version_tag) for name in [
879
+ "missingness_tradeoff_scatter_main.tex",
880
+ "missingness_tradeoff_scatter_main.pdf",
881
+ "missingness_tradeoff_scatter_main.png",
882
+ "missingness_prefix_bars_appendix.tex",
883
+ "missingness_prefix_bars_appendix.pdf",
884
+ "missingness_prefix_bars_appendix.png",
885
+ "missingness_dataset_model_heatmap_appendix.tex",
886
+ "missingness_dataset_model_heatmap_appendix.pdf",
887
+ "missingness_dataset_model_heatmap_appendix.png",
888
+ "missingness_model_subitem_heatmap_appendix.tex",
889
+ "missingness_model_subitem_heatmap_appendix.pdf",
890
+ "missingness_model_subitem_heatmap_appendix.png",
891
+ "missingness_family_subitem_bars_appendix.tex",
892
+ "missingness_family_subitem_bars_appendix.pdf",
893
+ "missingness_family_subitem_bars_appendix.png",
894
+ ]],
895
+ must_do_files=[versioned_name(name, version_tag) for name in must_do_aliases.keys()],
896
+ support_files=[
897
+ *[versioned_name(name, version_tag) for name in [
898
+ "analysis_report.md",
899
+ "missingness_query_rows.csv",
900
+ "duplicate_asset_audit.csv",
901
+ ]],
902
+ ],
903
+ notes=[
904
+ "These placeholders are intentional and should be replaced automatically once missingness queries are present in the unified analysis run.",
905
+ ],
906
+ )
907
+ sync_final_outputs(FINAL_DIR, final_files, must_do_aliases, version_tag=version_tag, copy_plain_files=False)
908
+ (FINAL_DIR / "README.md").write_text(readme, encoding="utf-8")
909
+ manifest = {
910
+ "task": "missingness_breakdown",
911
+ "sql_source_version": version_tag,
912
+ "sql_source_label": sql_source_label(version_tag),
913
+ "source_analysis_run": run_dir.name,
914
+ "query_row_count": 0,
915
+ "status": "placeholder_no_query_rows",
916
+ "compile_notes": {key: {"success": value[0], "note": value[1]} for key, value in compile_notes.items()},
917
+ }
918
+ (OUTPUT_ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
919
+ return manifest
920
+
921
+
922
+ def run_missingness_breakdown(*, analysis_run_dir: Path | None = None) -> dict[str, Any]:
923
+ _ensure_dirs()
924
+ analysis_run_dir = analysis_run_dir.resolve() if analysis_run_dir is not None else _find_primary_analysis_run()
925
+ audit_rows: list[dict[str, Any]] = []
926
+ direct_outputs = _run_direct_missingness_eval()
927
+ direct_dataset_context_df = pd.read_csv(direct_outputs["dataset_context"], encoding="utf-8-sig")
928
+ direct_asset_scores_df = pd.read_csv(direct_outputs["asset_scores"], encoding="utf-8-sig")
929
+ direct_target_scores_df = pd.read_csv(direct_outputs["target_scores"], encoding="utf-8-sig")
930
+ direct_model_dataset_df = pd.read_csv(direct_outputs["model_dataset_summary"], encoding="utf-8-sig")
931
+ direct_model_overall_df = pd.read_csv(direct_outputs["model_overall_summary"], encoding="utf-8-sig")
932
+
933
+ subitem_df, dataset_model_df = _build_dataset_model_scores_from_direct_summary(direct_model_dataset_df)
934
+ if dataset_model_df.empty:
935
+ return _write_placeholder_bundle(analysis_run_dir, audit_rows)
936
+
937
+ model_summary_df = _build_model_summary(dataset_model_df)
938
+ prefix_summary_df = _build_prefix_summary(dataset_model_df)
939
+ dataset_summary_df = _build_dataset_summary(dataset_model_df)
940
+ heatmap_df = _build_heatmap_data(dataset_model_df)
941
+ prefix_plot_df = _build_prefix_plot_data(prefix_summary_df)
942
+ model_subitem_heatmap_df = build_model_subitem_heatmap_df(
943
+ model_summary_df.loc[model_summary_df["model_id"].isin(MODEL_ORDER)].copy(),
944
+ model_id_col="model_id",
945
+ model_order=MODEL_ORDER,
946
+ subitem_specs=[
947
+ (subitem_id, SUBITEM_LABELS[subitem_id], f"{subitem_id}__mean")
948
+ for subitem_id in SUBITEM_ORDER
949
+ ],
950
+ summary_row_spec=("family_mean", "Family mean", "missingness_structure_score__mean"),
951
+ )
952
+
953
+ _write_csv(pd.DataFrame(audit_rows), DATA_DIR / "duplicate_asset_audit.csv")
954
+ _write_csv(
955
+ dataset_model_df[
956
+ [
957
+ "dataset_id",
958
+ "dataset_prefix",
959
+ "model_id",
960
+ "model_label",
961
+ "marginal_missing_rate_consistency",
962
+ "co_missingness_pattern_consistency",
963
+ "co_missing_strength_score",
964
+ "co_missing_composite_score",
965
+ "missingness_structure_score",
966
+ "profile_minus_strength",
967
+ "asset_count",
968
+ "applicable_asset_count",
969
+ ]
970
+ ],
971
+ DATA_DIR / "missingness_query_rows.csv",
972
+ )
973
+ _write_csv(subitem_df, DATA_DIR / "dataset_model_subitems.csv")
974
+ _write_csv(dataset_model_df, DATA_DIR / "dataset_model_scores.csv")
975
+ _write_csv(model_summary_df, DATA_DIR / "model_summary.csv")
976
+ _write_csv(prefix_summary_df, DATA_DIR / "prefix_summary.csv")
977
+ _write_csv(dataset_summary_df, DATA_DIR / "dataset_summary.csv")
978
+ _write_csv(heatmap_df, DATA_DIR / "dataset_model_heatmap.csv")
979
+ _write_csv(prefix_plot_df, DATA_DIR / "prefix_plot_data.csv")
980
+ _write_csv(model_subitem_heatmap_df, DATA_DIR / "model_subitem_heatmap.csv")
981
+ _write_csv(direct_dataset_context_df, DATA_DIR / "direct_dataset_context.csv")
982
+ _write_csv(direct_asset_scores_df, DATA_DIR / "direct_asset_scores.csv")
983
+ _write_csv(direct_target_scores_df, DATA_DIR / "direct_target_scores.csv")
984
+ _write_csv(direct_model_dataset_df, DATA_DIR / "direct_model_dataset_summary.csv")
985
+ _write_csv(direct_model_overall_df, DATA_DIR / "direct_model_overall_summary.csv")
986
+
987
+ tradeoff_tex = FIG_DIR / "missingness_tradeoff_scatter_main.tex"
988
+ tradeoff_pdf = FIG_DIR / "missingness_tradeoff_scatter_main.pdf"
989
+ tradeoff_png = FIG_DIR / "missingness_tradeoff_scatter_main.png"
990
+ prefix_tex = FIG_DIR / "missingness_prefix_bars_appendix.tex"
991
+ prefix_pdf = FIG_DIR / "missingness_prefix_bars_appendix.pdf"
992
+ prefix_png = FIG_DIR / "missingness_prefix_bars_appendix.png"
993
+ heatmap_tex = FIG_DIR / "missingness_dataset_model_heatmap_appendix.tex"
994
+ heatmap_pdf = FIG_DIR / "missingness_dataset_model_heatmap_appendix.pdf"
995
+ heatmap_png = FIG_DIR / "missingness_dataset_model_heatmap_appendix.png"
996
+ model_subitem_heatmap_tex = FIG_DIR / "missingness_model_subitem_heatmap_appendix.tex"
997
+ model_subitem_heatmap_pdf = FIG_DIR / "missingness_model_subitem_heatmap_appendix.pdf"
998
+ model_subitem_heatmap_png = FIG_DIR / "missingness_model_subitem_heatmap_appendix.png"
999
+ grouped_bars_tex = FIG_DIR / "missingness_family_subitem_bars_appendix.tex"
1000
+ grouped_bars_pdf = FIG_DIR / "missingness_family_subitem_bars_appendix.pdf"
1001
+ grouped_bars_png = FIG_DIR / "missingness_family_subitem_bars_appendix.png"
1002
+
1003
+ _write_tradeoff_tex(model_summary_df, tradeoff_tex)
1004
+ _write_prefix_bar_tex(prefix_plot_df, prefix_tex)
1005
+ _write_heatmap_tex(heatmap_df, heatmap_tex)
1006
+ write_model_subitem_heatmap_tex(
1007
+ model_subitem_heatmap_df,
1008
+ model_order=MODEL_ORDER,
1009
+ model_label_map=MODEL_LABELS,
1010
+ title="Missingness model-subitem heatmap",
1011
+ colorbar_title="Mean score",
1012
+ path=model_subitem_heatmap_tex,
1013
+ )
1014
+ write_model_subitem_grouped_bar_tex(
1015
+ model_subitem_heatmap_df,
1016
+ model_order=MODEL_ORDER,
1017
+ model_label_map=MODEL_LABELS,
1018
+ model_color_map=MODEL_COLORS,
1019
+ title="Missingness family and subitem bars",
1020
+ y_label="Score",
1021
+ path=grouped_bars_tex,
1022
+ )
1023
+ _plot_tradeoff_preview(model_summary_df, tradeoff_pdf, tradeoff_png)
1024
+ _plot_prefix_bar_preview(prefix_plot_df, prefix_pdf, prefix_png)
1025
+ _plot_heatmap_preview(heatmap_df, heatmap_pdf, heatmap_png)
1026
+ plot_model_subitem_heatmap_preview(
1027
+ model_subitem_heatmap_df,
1028
+ model_order=MODEL_ORDER,
1029
+ model_label_map=MODEL_LABELS,
1030
+ title="Missingness model-subitem heatmap",
1031
+ pdf_path=model_subitem_heatmap_pdf,
1032
+ png_path=model_subitem_heatmap_png,
1033
+ )
1034
+ plot_model_subitem_grouped_bar_preview(
1035
+ model_subitem_heatmap_df,
1036
+ model_order=MODEL_ORDER,
1037
+ model_label_map=MODEL_LABELS,
1038
+ model_color_map=MODEL_COLORS,
1039
+ title="Missingness family and subitem bars",
1040
+ y_label="Score",
1041
+ pdf_path=grouped_bars_pdf,
1042
+ png_path=grouped_bars_png,
1043
+ )
1044
+
1045
+ compile_notes = {
1046
+ "tradeoff": _try_compile_tex(tradeoff_tex),
1047
+ "prefix": _try_compile_tex(prefix_tex),
1048
+ "heatmap": _try_compile_tex(heatmap_tex),
1049
+ "model_subitem_heatmap": _try_compile_tex(model_subitem_heatmap_tex),
1050
+ "family_subitem_bars": _try_compile_tex(grouped_bars_tex),
1051
+ }
1052
+ (OUTPUT_ROOT / "analysis_report.md").write_text(
1053
+ "\n".join(
1054
+ [
1055
+ "# Missingness Breakdown",
1056
+ "",
1057
+ "- Source mode: `direct_missingness_evaluator`",
1058
+ f"- Reference analysis run: `{analysis_run_dir.name}`",
1059
+ f"- Included models: `{model_summary_df.shape[0]}`",
1060
+ f"- Deduplicated dataset-model panels: `{dataset_model_df.shape[0]}`",
1061
+ f"- Direct model-dataset rows used: `{dataset_model_df.shape[0]}`",
1062
+ f"- Direct target rows used: `{direct_target_scores_df.shape[0]}`",
1063
+ "",
1064
+ "## Canonical decomposition",
1065
+ "",
1066
+ "- `missingness_structure = 0.5 * marginal_missing_rate_consistency + 0.5 * co_missingness_pattern_consistency`",
1067
+ "- Canonical `co_missingness_pattern_consistency` now uses profile-only edge averaging.",
1068
+ "- `co_missing_strength_score` is exported separately as an auxiliary diagnostic and is not folded into the two-subitem family score.",
1069
+ "- `co_missing_composite_score` preserves the previous 0.7-profile / 0.3-strength blend for sensitivity analysis only.",
1070
+ "- This bundle bypasses SQL query analysis and uses the canonical direct co-missing evaluator over real-train vs synthetic CSV pairs.",
1071
+ "- The standardized appendix bundle now mirrors tradeoff, prefix, and heatmap views just like the other query families.",
1072
+ "",
1073
+ ]
1074
+ ),
1075
+ encoding="utf-8",
1076
+ )
1077
+
1078
+ final_files = [
1079
+ tradeoff_tex,
1080
+ tradeoff_pdf,
1081
+ tradeoff_png,
1082
+ prefix_tex,
1083
+ prefix_pdf,
1084
+ prefix_png,
1085
+ heatmap_tex,
1086
+ heatmap_pdf,
1087
+ heatmap_png,
1088
+ model_subitem_heatmap_tex,
1089
+ model_subitem_heatmap_pdf,
1090
+ model_subitem_heatmap_png,
1091
+ grouped_bars_tex,
1092
+ grouped_bars_pdf,
1093
+ grouped_bars_png,
1094
+ DATA_DIR / "model_summary.csv",
1095
+ DATA_DIR / "prefix_summary.csv",
1096
+ OUTPUT_ROOT / "analysis_report.md",
1097
+ ]
1098
+ must_do_aliases = {
1099
+ f"{stem}.{suffix}": FIG_DIR / f"{stem}.{suffix}"
1100
+ for stem in [
1101
+ "missingness_tradeoff_scatter_main",
1102
+ "missingness_prefix_bars_appendix",
1103
+ "missingness_dataset_model_heatmap_appendix",
1104
+ "missingness_model_subitem_heatmap_appendix",
1105
+ "missingness_family_subitem_bars_appendix",
1106
+ ]
1107
+ for suffix in ["tex", "pdf", "png"]
1108
+ }
1109
+ version_tag = OUTPUT_VERSION_TAG
1110
+ sync_final_outputs(FINAL_DIR, final_files, must_do_aliases, version_tag=version_tag, copy_plain_files=False)
1111
+ final_readme = render_final_readme(
1112
+ title="Missingness Breakdown Final",
1113
+ 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/`.",
1114
+ primary_files=[versioned_name(name, version_tag) for name in [
1115
+ "missingness_tradeoff_scatter_main.tex",
1116
+ "missingness_tradeoff_scatter_main.pdf",
1117
+ "missingness_tradeoff_scatter_main.png",
1118
+ "missingness_prefix_bars_appendix.tex",
1119
+ "missingness_prefix_bars_appendix.pdf",
1120
+ "missingness_prefix_bars_appendix.png",
1121
+ "missingness_dataset_model_heatmap_appendix.tex",
1122
+ "missingness_dataset_model_heatmap_appendix.pdf",
1123
+ "missingness_dataset_model_heatmap_appendix.png",
1124
+ "missingness_model_subitem_heatmap_appendix.tex",
1125
+ "missingness_model_subitem_heatmap_appendix.pdf",
1126
+ "missingness_model_subitem_heatmap_appendix.png",
1127
+ "missingness_family_subitem_bars_appendix.tex",
1128
+ "missingness_family_subitem_bars_appendix.pdf",
1129
+ "missingness_family_subitem_bars_appendix.png",
1130
+ "model_summary.csv",
1131
+ "prefix_summary.csv",
1132
+ ]],
1133
+ must_do_files=[versioned_name(name, version_tag) for name in must_do_aliases.keys()],
1134
+ support_files=[versioned_name("analysis_report.md", version_tag)],
1135
+ notes=[
1136
+ f"The active published version tag for this bundle is `{sql_source_label(version_tag)}` (`{version_tag}`).",
1137
+ "The `.tex` files are standalone LaTeX sources. The `.pdf/.png` files are immediate previews for reading in the current environment.",
1138
+ ],
1139
+ )
1140
+ (FINAL_DIR / "README.md").write_text(final_readme, encoding="utf-8")
1141
+
1142
+ manifest = {
1143
+ "task": "missingness_breakdown",
1144
+ "sql_source_version": version_tag,
1145
+ "sql_source_label": sql_source_label(version_tag),
1146
+ "source_mode": "direct_missingness_evaluator",
1147
+ "reference_analysis_run": analysis_run_dir.name,
1148
+ "included_models": model_summary_df["model_id"].tolist(),
1149
+ "dataset_panel_count": int(dataset_model_df.shape[0]),
1150
+ "query_row_count": int(dataset_model_df.shape[0]),
1151
+ "status": "implemented_direct",
1152
+ "compile_notes": {key: {"success": value[0], "note": value[1]} for key, value in compile_notes.items()},
1153
+ }
1154
+ (OUTPUT_ROOT / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
1155
+ return manifest
1156
+
1157
+
1158
+ def parse_args() -> argparse.Namespace:
1159
+ parser = argparse.ArgumentParser(description="Build the missingness breakdown bundle.")
1160
+ parser.add_argument("--analysis-run-dir", type=Path, default=None, help="Optional analysis run dir.")
1161
+ return parser.parse_args()
1162
+
1163
+
1164
+ def main() -> None:
1165
+ args = parse_args()
1166
+ manifest = run_missingness_breakdown(analysis_run_dir=args.analysis_run_dir)
1167
+ print(json.dumps(manifest, indent=2))
1168
+
1169
+
1170
+ if __name__ == "__main__":
1171
+ main()
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Strength diagnostic for missingness breakdown."""
2
+
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strength_diagnostic/runner.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Paper-facing auxiliary diagnostic for missingness relation-strength fidelity."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from pathlib import Path
7
+ import sys
8
+ from typing import Any
9
+
10
+ import matplotlib
11
+
12
+ matplotlib.use("Agg")
13
+ import matplotlib.pyplot as plt
14
+ from matplotlib.lines import Line2D
15
+ from matplotlib.patches import Patch, Rectangle
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ PROJECT_ROOT = Path(__file__).resolve().parents[5]
20
+ if str(PROJECT_ROOT) not in sys.path:
21
+ sys.path.insert(0, str(PROJECT_ROOT))
22
+
23
+ from src.eval.query_fivepart_breakdown.common_final import render_final_readme, sync_final_outputs
24
+ from src.eval.query_fivepart_breakdown.common_heatmap_palette import get_heatmap_cmap
25
+
26
+ MISSINGNESS_ROOT = PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown"
27
+ INPUT_DATA_DIR = MISSINGNESS_ROOT / "data"
28
+ OUTPUT_ROOT = MISSINGNESS_ROOT / "strength_diagnostic"
29
+ DATA_DIR = OUTPUT_ROOT / "data"
30
+ FIG_DIR = OUTPUT_ROOT / "figures"
31
+ FINAL_DIR = OUTPUT_ROOT / "final"
32
+
33
+ MODEL_ORDER = [
34
+ "arf",
35
+ "bayesnet",
36
+ "ctgan",
37
+ "forestdiffusion",
38
+ "realtabformer",
39
+ "tabbyflow",
40
+ "tabddpm",
41
+ "tabdiff",
42
+ "tabpfgen",
43
+ "tabsyn",
44
+ "tvae",
45
+ ]
46
+ MODEL_LABELS = {
47
+ "arf": "ARF",
48
+ "bayesnet": "BayesNet",
49
+ "ctgan": "CTGAN",
50
+ "forestdiffusion": "ForestDiffusion",
51
+ "realtabformer": "RealTabFormer",
52
+ "tabbyflow": "TabbyFlow",
53
+ "tabddpm": "TabDDPM",
54
+ "tabdiff": "TabDiff",
55
+ "tabpfgen": "TabPFGen",
56
+ "tabsyn": "TabSyn",
57
+ "tvae": "TVAE",
58
+ }
59
+ MODEL_COLORS = {
60
+ "realtabformer": "#332288",
61
+ "tvae": "#4477AA",
62
+ "forestdiffusion": "#228833",
63
+ "tabddpm": "#EE7733",
64
+ "tabsyn": "#66CCEE",
65
+ "tabdiff": "#AA3377",
66
+ "ctgan": "#EE6677",
67
+ "arf": "#777777",
68
+ "bayesnet": "#CCBB44",
69
+ "tabpfgen": "#009988",
70
+ "tabbyflow": "#882255",
71
+ }
72
+ PROFILE_COLOR = "#E76F51"
73
+ STRENGTH_COLOR = "#2A9D8F"
74
+
75
+
76
+ def _ensure_dirs() -> None:
77
+ for path in (OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR):
78
+ path.mkdir(parents=True, exist_ok=True)
79
+
80
+
81
+ def _model_label(model_id: str) -> str:
82
+ return MODEL_LABELS.get(model_id, model_id)
83
+
84
+
85
+ def _dataset_sort_key(dataset_id: str) -> tuple[int, int, str]:
86
+ text = str(dataset_id or "").strip()
87
+ if len(text) < 2 or not text[1:].isdigit():
88
+ return (99, 10**9, text)
89
+ prefix_order = {"c": 0, "m": 1, "n": 2}.get(text[0].lower(), 50)
90
+ return (prefix_order, int(text[1:]), text)
91
+
92
+
93
+ def _write_csv(df: pd.DataFrame, path: Path) -> None:
94
+ df.to_csv(path, index=False, encoding="utf-8-sig")
95
+
96
+
97
+ def _write_include_tex(path: Path, title: str, pdf_name: str) -> None:
98
+ path.write_text(
99
+ "\n".join(
100
+ [
101
+ r"\documentclass[border=4pt]{standalone}",
102
+ r"\usepackage{graphicx}",
103
+ r"\begin{document}",
104
+ rf"\textbf{{{title}}}\\[0.5em]",
105
+ rf"\includegraphics[width=\textwidth]{{{pdf_name}}}",
106
+ r"\end{document}",
107
+ "",
108
+ ]
109
+ ),
110
+ encoding="utf-8",
111
+ )
112
+
113
+
114
+ def _load_inputs() -> tuple[pd.DataFrame, pd.DataFrame]:
115
+ dataset_model_df = pd.read_csv(INPUT_DATA_DIR / "dataset_model_scores.csv", encoding="utf-8-sig")
116
+ model_summary_df = pd.read_csv(INPUT_DATA_DIR / "model_summary.csv", encoding="utf-8-sig")
117
+ for column in [
118
+ "co_missingness_pattern_consistency",
119
+ "co_missing_strength_score",
120
+ "co_missing_composite_score",
121
+ "profile_minus_strength",
122
+ ]:
123
+ if column in dataset_model_df.columns:
124
+ dataset_model_df[column] = pd.to_numeric(dataset_model_df[column], errors="coerce")
125
+ return dataset_model_df, model_summary_df
126
+
127
+
128
+ def _build_dataset_model_strength_df(dataset_model_df: pd.DataFrame) -> pd.DataFrame:
129
+ df = dataset_model_df.copy()
130
+ df = df.loc[df["co_missing_strength_score"].notna()].copy()
131
+ df["strength_minus_profile"] = df["co_missing_strength_score"] - df["co_missingness_pattern_consistency"]
132
+ df["dataset_sort"] = df["dataset_id"].map(_dataset_sort_key)
133
+ df["model_order"] = df["model_id"].map({model_id: idx for idx, model_id in enumerate(MODEL_ORDER)})
134
+ df = df.sort_values(["dataset_sort", "model_order"]).drop(columns=["dataset_sort", "model_order"]).reset_index(drop=True)
135
+ return df[
136
+ [
137
+ "dataset_id",
138
+ "dataset_prefix",
139
+ "model_id",
140
+ "model_label",
141
+ "co_missingness_pattern_consistency",
142
+ "co_missing_strength_score",
143
+ "co_missing_composite_score",
144
+ "profile_minus_strength",
145
+ "strength_minus_profile",
146
+ "asset_count",
147
+ "applicable_asset_count",
148
+ ]
149
+ ]
150
+
151
+
152
+ def _build_model_strength_summary(dataset_model_strength_df: pd.DataFrame) -> pd.DataFrame:
153
+ rows: list[dict[str, Any]] = []
154
+ for model_id in MODEL_ORDER:
155
+ subset = dataset_model_strength_df.loc[dataset_model_strength_df["model_id"] == model_id].copy()
156
+ if subset.empty:
157
+ continue
158
+ rows.append(
159
+ {
160
+ "model_id": model_id,
161
+ "model_label": _model_label(model_id),
162
+ "dataset_count": int(subset["dataset_id"].nunique()),
163
+ "panel_count": int(subset.shape[0]),
164
+ "profile_score_mean": round(float(subset["co_missingness_pattern_consistency"].mean()), 6),
165
+ "strength_score_mean": round(float(subset["co_missing_strength_score"].mean()), 6),
166
+ "composite_score_mean": round(float(subset["co_missing_composite_score"].mean()), 6),
167
+ "strength_minus_profile_mean": round(float(subset["strength_minus_profile"].mean()), 6),
168
+ }
169
+ )
170
+ return pd.DataFrame(rows)
171
+
172
+
173
+ def _plot_model_dumbbell(summary_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
174
+ fig, ax = plt.subplots(figsize=(9.4, 6.8))
175
+ y_positions = list(range(len(summary_df)))
176
+ for idx, row in enumerate(summary_df.itertuples()):
177
+ model_id = str(row.model_id)
178
+ color = MODEL_COLORS.get(model_id, "#777777")
179
+ profile = float(row.profile_score_mean)
180
+ strength = float(row.strength_score_mean)
181
+ ax.plot([profile, strength], [idx, idx], color=color, linewidth=2.2, alpha=0.95)
182
+ ax.scatter(profile, idx, s=70, facecolors="white", edgecolors=color, linewidth=1.8, zorder=3)
183
+ ax.scatter(strength, idx, s=70, facecolors=color, edgecolors=color, marker="s", linewidth=1.0, zorder=4)
184
+ ax.set_yticks(y_positions)
185
+ ax.set_yticklabels(summary_df["model_label"])
186
+ ax.set_xlim(0.0, 1.02)
187
+ ax.set_xlabel("Mean score over applicable dataset-model panels")
188
+ ax.set_title("Missingness auxiliary insight: profile vs strength")
189
+ ax.grid(axis="x", alpha=0.25)
190
+ ax.text(0.01, 1.01, "Hollow circle = canonical profile-only score; filled square = strength-only score", transform=ax.transAxes, fontsize=8.5)
191
+ fig.tight_layout()
192
+ fig.savefig(pdf_path, bbox_inches="tight")
193
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
194
+ fig.savefig(svg_path, bbox_inches="tight")
195
+ plt.close(fig)
196
+
197
+
198
+ def _plot_gap_bars(summary_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
199
+ fig, ax = plt.subplots(figsize=(10.4, 5.8))
200
+ colors = [MODEL_COLORS.get(str(model_id), "#777777") for model_id in summary_df["model_id"]]
201
+ values = pd.to_numeric(summary_df["strength_minus_profile_mean"], errors="coerce").fillna(0.0)
202
+ ax.bar(range(len(summary_df)), values, color=colors, edgecolor=colors)
203
+ ax.axhline(0.0, color="#444444", linewidth=1.0)
204
+ ax.set_xticks(range(len(summary_df)))
205
+ ax.set_xticklabels(summary_df["model_label"], rotation=60, ha="right", fontsize=8)
206
+ ax.set_ylabel("Strength minus profile")
207
+ ax.set_title("How much relation-strength fidelity differs from canonical profile fidelity")
208
+ ax.grid(axis="y", alpha=0.25)
209
+ fig.tight_layout()
210
+ fig.savefig(pdf_path, bbox_inches="tight")
211
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
212
+ fig.savefig(svg_path, bbox_inches="tight")
213
+ plt.close(fig)
214
+
215
+
216
+ def _plot_strength_heatmap(dataset_model_strength_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
217
+ pivot = (
218
+ dataset_model_strength_df.pivot_table(
219
+ index="dataset_id",
220
+ columns="model_id",
221
+ values="co_missing_strength_score",
222
+ aggfunc="mean",
223
+ )
224
+ .reset_index()
225
+ .rename_axis(None, axis=1)
226
+ )
227
+ ordered_models = [model_id for model_id in MODEL_ORDER if model_id in pivot.columns]
228
+ pivot["dataset_sort"] = pivot["dataset_id"].map(_dataset_sort_key)
229
+ pivot = pivot.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True)
230
+ matrix = pivot[ordered_models].to_numpy(dtype=float)
231
+ fig_height = max(5.8, 0.35 * len(pivot) + 1.8)
232
+ fig, ax = plt.subplots(figsize=(9.8, fig_height))
233
+ im = ax.imshow(matrix, vmin=0.0, vmax=1.0, aspect="auto", cmap=get_heatmap_cmap())
234
+ ax.set_xticks(range(len(ordered_models)))
235
+ ax.set_xticklabels([_model_label(model_id) for model_id in ordered_models], rotation=60, ha="right", fontsize=8)
236
+ ax.set_yticks(range(len(pivot)))
237
+ ax.set_yticklabels(pivot["dataset_id"], fontsize=7)
238
+ ax.set_title("Dataset-model heatmap of missingness relation-strength fidelity")
239
+ fig.colorbar(im, ax=ax, fraction=0.035, pad=0.02)
240
+ fig.tight_layout()
241
+ fig.savefig(pdf_path, bbox_inches="tight")
242
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
243
+ fig.savefig(svg_path, bbox_inches="tight")
244
+ plt.close(fig)
245
+
246
+
247
+ def _draw_distribution_summary(
248
+ ax: plt.Axes,
249
+ center: float,
250
+ values: list[float],
251
+ color: str,
252
+ offset: float,
253
+ box_width: float = 0.18,
254
+ ) -> None:
255
+ cleaned = [float(value) for value in values if pd.notna(value)]
256
+ if not cleaned:
257
+ return
258
+ arr = np.asarray(cleaned, dtype=float)
259
+ mean = float(arr.mean())
260
+ q1 = float(np.quantile(arr, 0.25))
261
+ q3 = float(np.quantile(arr, 0.75))
262
+ ymin = float(arr.min())
263
+ ymax = float(arr.max())
264
+ xpos = center + offset
265
+ ax.vlines(xpos, ymin, ymax, color=color, linewidth=1.1, alpha=0.95, zorder=2)
266
+ ax.hlines([ymin, ymax], xpos - box_width * 0.26, xpos + box_width * 0.26, color=color, linewidth=1.1, alpha=0.95, zorder=2)
267
+ ax.add_patch(
268
+ Rectangle(
269
+ (xpos - box_width / 2, q1),
270
+ box_width,
271
+ max(0.0, q3 - q1),
272
+ facecolor=color,
273
+ edgecolor="none",
274
+ alpha=0.24,
275
+ zorder=1,
276
+ )
277
+ )
278
+ ax.scatter([xpos], [mean], s=28, marker="s", facecolor=color, edgecolor=color, linewidth=0.8, zorder=3)
279
+
280
+
281
+ def _plot_profile_strength_distribution(dataset_model_strength_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
282
+ fig, ax = plt.subplots(figsize=(11.8, 4.8))
283
+ x_positions = list(range(len(MODEL_ORDER)))
284
+ profile_offset = -0.17
285
+ strength_offset = 0.17
286
+
287
+ for idx, model_id in enumerate(MODEL_ORDER):
288
+ subset = dataset_model_strength_df.loc[dataset_model_strength_df["model_id"] == model_id].copy()
289
+ if subset.empty:
290
+ continue
291
+ _draw_distribution_summary(
292
+ ax,
293
+ center=float(idx),
294
+ values=subset["co_missingness_pattern_consistency"].tolist(),
295
+ color=PROFILE_COLOR,
296
+ offset=profile_offset,
297
+ )
298
+ _draw_distribution_summary(
299
+ ax,
300
+ center=float(idx),
301
+ values=subset["co_missing_strength_score"].tolist(),
302
+ color=STRENGTH_COLOR,
303
+ offset=strength_offset,
304
+ )
305
+
306
+ ax.set_xlim(-0.6, len(MODEL_ORDER) - 0.4)
307
+ ax.set_ylim(0.0, 1.02)
308
+ ax.set_xticks(x_positions)
309
+ ax.set_xticklabels([_model_label(model_id) for model_id in MODEL_ORDER], rotation=35, ha="right")
310
+ ax.set_ylabel("Score")
311
+ ax.set_xlabel("Model")
312
+ ax.set_title("Co-missingness: profile vs strength across dataset-model panels")
313
+ ax.grid(axis="y", alpha=0.28, linestyle=":")
314
+ ax.grid(axis="x", alpha=0.12)
315
+
316
+ legend_handles = [
317
+ Patch(facecolor=PROFILE_COLOR, edgecolor="none", alpha=0.6, label="Profile-only co-missing"),
318
+ Patch(facecolor=STRENGTH_COLOR, edgecolor="none", alpha=0.6, label="Strength-only co-missing"),
319
+ Line2D([0], [0], marker="s", color="#444444", markerfacecolor="#444444", markersize=5, linewidth=0, label="Mean over datasets"),
320
+ Line2D([0], [0], color="#444444", linewidth=1.1, label="Min-max over datasets"),
321
+ Patch(facecolor="#999999", edgecolor="none", alpha=0.24, label="IQR over datasets"),
322
+ ]
323
+ 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)
324
+
325
+ fig.tight_layout()
326
+ fig.savefig(pdf_path, bbox_inches="tight")
327
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
328
+ fig.savefig(svg_path, bbox_inches="tight")
329
+ plt.close(fig)
330
+
331
+
332
+ def run_strength_diagnostic() -> dict[str, Any]:
333
+ _ensure_dirs()
334
+ dataset_model_df, _ = _load_inputs()
335
+ dataset_model_strength_df = _build_dataset_model_strength_df(dataset_model_df)
336
+ model_strength_summary_df = _build_model_strength_summary(dataset_model_strength_df)
337
+
338
+ _write_csv(dataset_model_strength_df, DATA_DIR / "dataset_model_strength_scores.csv")
339
+ _write_csv(model_strength_summary_df, DATA_DIR / "model_strength_summary.csv")
340
+
341
+ main_pdf = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.pdf"
342
+ main_png = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.png"
343
+ main_svg = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.svg"
344
+ main_tex = FIG_DIR / "missing_strength_profile_vs_strength_model_dumbbell_main.tex"
345
+ gap_pdf = FIG_DIR / "missing_strength_gap_bars_appendix.pdf"
346
+ gap_png = FIG_DIR / "missing_strength_gap_bars_appendix.png"
347
+ gap_svg = FIG_DIR / "missing_strength_gap_bars_appendix.svg"
348
+ gap_tex = FIG_DIR / "missing_strength_gap_bars_appendix.tex"
349
+ heat_pdf = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.pdf"
350
+ heat_png = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.png"
351
+ heat_svg = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.svg"
352
+ heat_tex = FIG_DIR / "missing_strength_dataset_model_heatmap_appendix.tex"
353
+ dist_pdf = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.pdf"
354
+ dist_png = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.png"
355
+ dist_svg = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.svg"
356
+ dist_tex = FIG_DIR / "missing_strength_profile_vs_strength_distribution_main.tex"
357
+
358
+ _plot_model_dumbbell(model_strength_summary_df, main_pdf, main_png, main_svg)
359
+ _plot_gap_bars(model_strength_summary_df, gap_pdf, gap_png, gap_svg)
360
+ _plot_strength_heatmap(dataset_model_strength_df, heat_pdf, heat_png, heat_svg)
361
+ _plot_profile_strength_distribution(dataset_model_strength_df, dist_pdf, dist_png, dist_svg)
362
+ _write_include_tex(main_tex, "Missingness auxiliary insight: profile vs strength", main_pdf.name)
363
+ _write_include_tex(gap_tex, "Strength minus profile", gap_pdf.name)
364
+ _write_include_tex(heat_tex, "Dataset-model strength heatmap", heat_pdf.name)
365
+ _write_include_tex(dist_tex, "Co-missing profile vs strength distribution", dist_pdf.name)
366
+
367
+ report_lines = [
368
+ "# Missingness Strength Diagnostic",
369
+ "",
370
+ "- Canonical missingness family score now keeps `co_missingness_pattern_consistency` as profile-only.",
371
+ "- 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.",
372
+ f"- Applicable dataset-model panels: `{dataset_model_strength_df.shape[0]}`",
373
+ f"- Applicable datasets: `{dataset_model_strength_df['dataset_id'].nunique() if not dataset_model_strength_df.empty else 0}`",
374
+ "",
375
+ ]
376
+ (OUTPUT_ROOT / "analysis_report.md").write_text("\n".join(report_lines), encoding="utf-8")
377
+ (OUTPUT_ROOT / "paper_caption.txt").write_text(
378
+ "Auxiliary missingness diagnostic comparing canonical profile-only co-missing fidelity against relation-strength fidelity. "
379
+ "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.",
380
+ encoding="utf-8",
381
+ )
382
+ (OUTPUT_ROOT / "paper_paragraphs.md").write_text(
383
+ "\n".join(
384
+ [
385
+ "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.",
386
+ "",
387
+ "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.",
388
+ "",
389
+ ]
390
+ ),
391
+ encoding="utf-8",
392
+ )
393
+
394
+ final_files = [
395
+ DATA_DIR / "dataset_model_strength_scores.csv",
396
+ DATA_DIR / "model_strength_summary.csv",
397
+ OUTPUT_ROOT / "analysis_report.md",
398
+ OUTPUT_ROOT / "paper_caption.txt",
399
+ OUTPUT_ROOT / "paper_paragraphs.md",
400
+ main_pdf,
401
+ main_png,
402
+ main_svg,
403
+ main_tex,
404
+ dist_pdf,
405
+ dist_png,
406
+ dist_svg,
407
+ dist_tex,
408
+ gap_pdf,
409
+ gap_png,
410
+ gap_svg,
411
+ gap_tex,
412
+ heat_pdf,
413
+ heat_png,
414
+ heat_svg,
415
+ heat_tex,
416
+ ]
417
+ must_do = {
418
+ main_pdf.name: main_pdf,
419
+ main_png.name: main_png,
420
+ main_svg.name: main_svg,
421
+ main_tex.name: main_tex,
422
+ dist_pdf.name: dist_pdf,
423
+ dist_png.name: dist_png,
424
+ dist_svg.name: dist_svg,
425
+ dist_tex.name: dist_tex,
426
+ gap_pdf.name: gap_pdf,
427
+ gap_png.name: gap_png,
428
+ gap_svg.name: gap_svg,
429
+ gap_tex.name: gap_tex,
430
+ heat_pdf.name: heat_pdf,
431
+ heat_png.name: heat_png,
432
+ heat_svg.name: heat_svg,
433
+ heat_tex.name: heat_tex,
434
+ }
435
+ sync_final_outputs(FINAL_DIR, final_files, must_do)
436
+ (FINAL_DIR / "README.md").write_text(
437
+ render_final_readme(
438
+ title="Missingness Strength Diagnostic",
439
+ summary="Auxiliary paper-facing bundle isolating relation-strength fidelity from the canonical profile-only co-missing score.",
440
+ primary_files=[item.name for item in final_files if item.name.endswith((".png", ".pdf", ".tex"))][:12],
441
+ must_do_files=list(must_do.keys()),
442
+ support_files=[
443
+ "dataset_model_strength_scores.csv",
444
+ "model_strength_summary.csv",
445
+ "analysis_report.md",
446
+ "paper_caption.txt",
447
+ "paper_paragraphs.md",
448
+ ],
449
+ ),
450
+ encoding="utf-8",
451
+ )
452
+ return {
453
+ "dataset_model_strength_scores": DATA_DIR / "dataset_model_strength_scores.csv",
454
+ "model_strength_summary": DATA_DIR / "model_strength_summary.csv",
455
+ "main_figure_png": main_png,
456
+ "heatmap_png": heat_png,
457
+ }
458
+
459
+
460
+ if __name__ == "__main__":
461
+ outputs = run_strength_diagnostic()
462
+ for key, value in outputs.items():
463
+ print(f"{key}: {value}")
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Strict pairwise co-missing diagnostic for missingness breakdown."""
2
+
evaluation/query_family/code_support/src/eval/query_fivepart_breakdown/missingness_breakdown/strict_pairwise_diagnostic/runner.py ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Paper-facing auxiliary diagnostic for strict missing-only pairwise co-missingness."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections import defaultdict
7
+ from pathlib import Path
8
+ import sys
9
+ from typing import Any
10
+
11
+ import matplotlib
12
+
13
+ matplotlib.use("Agg")
14
+ import matplotlib.pyplot as plt
15
+ from matplotlib.lines import Line2D
16
+ from matplotlib.patches import Patch, Rectangle
17
+ import numpy as np
18
+ import pandas as pd
19
+
20
+ PROJECT_ROOT = Path(__file__).resolve().parents[5]
21
+ if str(PROJECT_ROOT) not in sys.path:
22
+ sys.path.insert(0, str(PROJECT_ROOT))
23
+
24
+ from src.eval.query_fivepart_breakdown.common_final import render_final_readme, sync_final_outputs
25
+ from src.eval.query_fivepart_breakdown.missingness_breakdown.review_strict_pairwise import _strict_pairwise_score_for_asset
26
+
27
+ MISSINGNESS_ROOT = PROJECT_ROOT / "Evaluation" / "query_fivepart_breakdown" / "missingness_breakdown"
28
+ INPUT_DATA_DIR = MISSINGNESS_ROOT / "data"
29
+ OUTPUT_ROOT = MISSINGNESS_ROOT / "strict_pairwise_diagnostic"
30
+ DATA_DIR = OUTPUT_ROOT / "data"
31
+ FIG_DIR = OUTPUT_ROOT / "figures"
32
+ FINAL_DIR = OUTPUT_ROOT / "final"
33
+
34
+ MODEL_ORDER = [
35
+ "arf",
36
+ "bayesnet",
37
+ "ctgan",
38
+ "forestdiffusion",
39
+ "realtabformer",
40
+ "tabbyflow",
41
+ "tabddpm",
42
+ "tabdiff",
43
+ "tabpfgen",
44
+ "tabsyn",
45
+ "tvae",
46
+ ]
47
+ MODEL_LABELS = {
48
+ "arf": "ARF",
49
+ "bayesnet": "BayesNet",
50
+ "ctgan": "CTGAN",
51
+ "forestdiffusion": "ForestDiffusion",
52
+ "realtabformer": "RealTabFormer",
53
+ "tabbyflow": "TabbyFlow",
54
+ "tabddpm": "TabDDPM",
55
+ "tabdiff": "TabDiff",
56
+ "tabpfgen": "TabPFGen",
57
+ "tabsyn": "TabSyn",
58
+ "tvae": "TVAE",
59
+ }
60
+ MODEL_COLORS = {
61
+ "realtabformer": "#332288",
62
+ "tvae": "#4477AA",
63
+ "forestdiffusion": "#228833",
64
+ "tabddpm": "#EE7733",
65
+ "tabsyn": "#66CCEE",
66
+ "tabdiff": "#AA3377",
67
+ "ctgan": "#EE6677",
68
+ "arf": "#777777",
69
+ "bayesnet": "#CCBB44",
70
+ "tabpfgen": "#009988",
71
+ "tabbyflow": "#882255",
72
+ }
73
+ EXCLUDED_MODELS = {"cdtd", "codi", "goggle"}
74
+ MODEL_ALIASES = {"rtf": "realtabformer"}
75
+ SERVER_PRIORITY = {"rtx_5090": 2, "rtx_pro_6000": 1}
76
+ ROOT_PRIORITY = {"SynOutput-5090": 2, "SynOutput": 1}
77
+ BROAD_PROFILE_COLOR = "#E76F51"
78
+ STRICT_PAIRWISE_COLOR = "#6D597A"
79
+
80
+
81
+ def _ensure_dirs() -> None:
82
+ for path in (OUTPUT_ROOT, DATA_DIR, FIG_DIR, FINAL_DIR):
83
+ path.mkdir(parents=True, exist_ok=True)
84
+
85
+
86
+ def _normalize_model(model_id: Any) -> str:
87
+ key = str(model_id or "").strip().lower()
88
+ return MODEL_ALIASES.get(key, key)
89
+
90
+
91
+ def _model_label(model_id: str) -> str:
92
+ return MODEL_LABELS.get(model_id, model_id)
93
+
94
+
95
+ def _dataset_sort_key(dataset_id: str) -> tuple[int, int, str]:
96
+ text = str(dataset_id or "").strip()
97
+ if len(text) < 2 or not text[1:].isdigit():
98
+ return (99, 10**9, text)
99
+ prefix_order = {"c": 0, "m": 1, "n": 2}.get(text[0].lower(), 50)
100
+ return (prefix_order, int(text[1:]), text)
101
+
102
+
103
+ def _write_csv(df: pd.DataFrame, path: Path) -> None:
104
+ df.to_csv(path, index=False, encoding="utf-8-sig")
105
+
106
+
107
+ def _write_include_tex(path: Path, title: str, pdf_name: str) -> None:
108
+ path.write_text(
109
+ "\n".join(
110
+ [
111
+ r"\documentclass[border=4pt]{standalone}",
112
+ r"\usepackage{graphicx}",
113
+ r"\begin{document}",
114
+ rf"\textbf{{{title}}}\\[0.5em]",
115
+ rf"\includegraphics[width=\textwidth]{{{pdf_name}}}",
116
+ r"\end{document}",
117
+ "",
118
+ ]
119
+ ),
120
+ encoding="utf-8",
121
+ )
122
+
123
+
124
+ def _asset_sort_key(row: dict[str, Any]) -> tuple[int, int, str, str]:
125
+ server = str(row.get("server_type") or "").strip().lower()
126
+ root_name = str(row.get("root_name") or "").strip()
127
+ run_id = str(row.get("run_id") or "").strip()
128
+ asset_key = str(row.get("asset_key") or "").strip()
129
+ return (
130
+ SERVER_PRIORITY.get(server, 0),
131
+ ROOT_PRIORITY.get(root_name, 0),
132
+ run_id,
133
+ asset_key,
134
+ )
135
+
136
+
137
+ def _load_primary_asset_rows() -> pd.DataFrame:
138
+ asset_df = pd.read_csv(INPUT_DATA_DIR / "direct_asset_scores.csv", encoding="utf-8-sig")
139
+ asset_df["model_id"] = asset_df["model_id"].map(_normalize_model)
140
+ asset_df = asset_df.loc[
141
+ (asset_df["status"] == "ok")
142
+ & (~asset_df["model_id"].isin(EXCLUDED_MODELS))
143
+ & asset_df["model_id"].isin(MODEL_ORDER)
144
+ ].copy()
145
+
146
+ grouped: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
147
+ for row in asset_df.to_dict(orient="records"):
148
+ grouped[(str(row["dataset_id"]), str(row["model_id"]))].append(row)
149
+
150
+ chosen_rows: list[dict[str, Any]] = []
151
+ for key, items in grouped.items():
152
+ ranked = sorted(items, key=_asset_sort_key, reverse=True)
153
+ chosen_rows.append(ranked[0])
154
+ return pd.DataFrame(chosen_rows)
155
+
156
+
157
+ def _build_strict_panel_df(asset_df: pd.DataFrame) -> pd.DataFrame:
158
+ rows: list[dict[str, Any]] = []
159
+ for row in asset_df.itertuples(index=False):
160
+ strict = _strict_pairwise_score_for_asset(str(row.dataset_id), Path(str(row.synthetic_csv_path)))
161
+ rows.append(
162
+ {
163
+ "dataset_id": str(row.dataset_id),
164
+ "dataset_prefix": str(row.dataset_id)[0].lower(),
165
+ "model_id": str(row.model_id),
166
+ "model_label": _model_label(str(row.model_id)),
167
+ "current_broad_profile_score": float(row.co_missingness_pattern_consistency),
168
+ "current_strength_score": float(getattr(row, "co_missing_strength_score", float("nan"))),
169
+ "strict_status": strict["strict_status"],
170
+ "strict_pairwise_score": strict["strict_pairwise_score"],
171
+ "strict_pair_count": int(strict["strict_pair_count"]),
172
+ "active_missing_target_count": int(strict["active_missing_target_count"]),
173
+ }
174
+ )
175
+ df = pd.DataFrame(rows)
176
+ df["delta_strict_minus_broad"] = pd.to_numeric(df["strict_pairwise_score"], errors="coerce") - pd.to_numeric(df["current_broad_profile_score"], errors="coerce")
177
+ df["dataset_sort"] = df["dataset_id"].map(_dataset_sort_key)
178
+ df["model_order"] = df["model_id"].map({model_id: idx for idx, model_id in enumerate(MODEL_ORDER)})
179
+ df = df.sort_values(["dataset_sort", "model_order"]).drop(columns=["dataset_sort", "model_order"]).reset_index(drop=True)
180
+ return df
181
+
182
+
183
+ def _build_model_summary(panel_df: pd.DataFrame) -> pd.DataFrame:
184
+ overlap_df = panel_df.loc[panel_df["strict_pairwise_score"].notna()].copy()
185
+ rows: list[dict[str, Any]] = []
186
+ for model_id in MODEL_ORDER:
187
+ subset = overlap_df.loc[overlap_df["model_id"] == model_id].copy()
188
+ if subset.empty:
189
+ continue
190
+ rows.append(
191
+ {
192
+ "model_id": model_id,
193
+ "model_label": _model_label(model_id),
194
+ "dataset_count_overlap": int(subset["dataset_id"].nunique()),
195
+ "panel_count_overlap": int(subset.shape[0]),
196
+ "broad_profile_score_mean": round(float(subset["current_broad_profile_score"].mean()), 6),
197
+ "strict_pairwise_score_mean": round(float(subset["strict_pairwise_score"].mean()), 6),
198
+ "delta_strict_minus_broad_mean": round(float(subset["delta_strict_minus_broad"].mean()), 6),
199
+ }
200
+ )
201
+ return pd.DataFrame(rows)
202
+
203
+
204
+ def _build_coverage_summary(panel_df: pd.DataFrame) -> pd.DataFrame:
205
+ rows: list[dict[str, Any]] = []
206
+ for dataset_id, group in panel_df.groupby("dataset_id", sort=False):
207
+ rows.append(
208
+ {
209
+ "dataset_id": dataset_id,
210
+ "model_panel_count": int(group.shape[0]),
211
+ "strict_applicable_panel_count": int(group["strict_pairwise_score"].notna().sum()),
212
+ "active_missing_target_count": int(pd.to_numeric(group["active_missing_target_count"], errors="coerce").fillna(0).max()),
213
+ "strict_pair_count": int(pd.to_numeric(group["strict_pair_count"], errors="coerce").fillna(0).max()),
214
+ }
215
+ )
216
+ coverage_df = pd.DataFrame(rows)
217
+ if coverage_df.empty:
218
+ return coverage_df
219
+ coverage_df["dataset_sort"] = coverage_df["dataset_id"].map(_dataset_sort_key)
220
+ return coverage_df.sort_values(["dataset_sort", "dataset_id"]).drop(columns=["dataset_sort"]).reset_index(drop=True)
221
+
222
+
223
+ def _plot_model_dumbbell(summary_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
224
+ fig, ax = plt.subplots(figsize=(9.5, 6.8))
225
+ y_positions = list(range(len(summary_df)))
226
+ for idx, row in enumerate(summary_df.itertuples()):
227
+ model_id = str(row.model_id)
228
+ color = MODEL_COLORS.get(model_id, "#777777")
229
+ broad = float(row.broad_profile_score_mean)
230
+ strict = float(row.strict_pairwise_score_mean)
231
+ ax.plot([broad, strict], [idx, idx], color=color, linewidth=2.2, alpha=0.95)
232
+ ax.scatter(broad, idx, s=70, facecolors="white", edgecolors=color, linewidth=1.8, zorder=3)
233
+ ax.scatter(strict, idx, s=70, facecolors=color, edgecolors=color, marker="D", linewidth=1.0, zorder=4)
234
+ ax.set_yticks(y_positions)
235
+ ax.set_yticklabels(summary_df["model_label"])
236
+ ax.set_xlim(0.0, 1.02)
237
+ ax.set_xlabel("Mean score over strict-overlap panels")
238
+ ax.set_title("Broad structured missingness vs strict missing-only pairwise co-missingness")
239
+ ax.grid(axis="x", alpha=0.25)
240
+ 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)
241
+ fig.tight_layout()
242
+ fig.savefig(pdf_path, bbox_inches="tight")
243
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
244
+ fig.savefig(svg_path, bbox_inches="tight")
245
+ plt.close(fig)
246
+
247
+
248
+ def _plot_panel_scatter(panel_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
249
+ overlap_df = panel_df.loc[panel_df["strict_pairwise_score"].notna()].copy()
250
+ fig, ax = plt.subplots(figsize=(7.8, 6.8))
251
+ ax.scatter(
252
+ overlap_df["current_broad_profile_score"],
253
+ overlap_df["strict_pairwise_score"],
254
+ s=34,
255
+ color="#4C78A8",
256
+ alpha=0.78,
257
+ edgecolors="none",
258
+ )
259
+ ax.plot([0.0, 1.0], [0.0, 1.0], linestyle="--", color="#666666", linewidth=1.1)
260
+ ax.set_xlim(0.0, 1.02)
261
+ ax.set_ylim(0.0, 1.02)
262
+ ax.set_xlabel("Broad profile-only co-missing score")
263
+ ax.set_ylabel("Strict missing-only pairwise score")
264
+ ax.set_title(
265
+ "Dataset-model overlap panels\n"
266
+ f"n={overlap_df.shape[0]}, datasets={overlap_df['dataset_id'].nunique() if not overlap_df.empty else 0}"
267
+ )
268
+ ax.grid(alpha=0.25)
269
+ fig.tight_layout()
270
+ fig.savefig(pdf_path, bbox_inches="tight")
271
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
272
+ fig.savefig(svg_path, bbox_inches="tight")
273
+ plt.close(fig)
274
+
275
+
276
+ def _plot_coverage_bars(coverage_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
277
+ x = range(len(coverage_df))
278
+ width = 0.38
279
+ fig, ax = plt.subplots(figsize=(11.8, 5.8))
280
+ 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")
281
+ 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")
282
+ ax.set_xticks(list(x))
283
+ ax.set_xticklabels(coverage_df["dataset_id"], rotation=60, ha="right", fontsize=8)
284
+ ax.set_ylabel("Panel count")
285
+ ax.set_title("Coverage shrinkage when only missing-only pairs are retained")
286
+ ax.grid(axis="y", alpha=0.25)
287
+ ax.legend(frameon=False, fontsize=8)
288
+ fig.tight_layout()
289
+ fig.savefig(pdf_path, bbox_inches="tight")
290
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
291
+ fig.savefig(svg_path, bbox_inches="tight")
292
+ plt.close(fig)
293
+
294
+
295
+ def _draw_distribution_summary(
296
+ ax: plt.Axes,
297
+ center: float,
298
+ values: list[float],
299
+ color: str,
300
+ offset: float,
301
+ box_width: float = 0.18,
302
+ ) -> None:
303
+ cleaned = [float(value) for value in values if pd.notna(value)]
304
+ if not cleaned:
305
+ return
306
+ arr = np.asarray(cleaned, dtype=float)
307
+ mean = float(arr.mean())
308
+ q1 = float(np.quantile(arr, 0.25))
309
+ q3 = float(np.quantile(arr, 0.75))
310
+ ymin = float(arr.min())
311
+ ymax = float(arr.max())
312
+ xpos = center + offset
313
+ ax.vlines(xpos, ymin, ymax, color=color, linewidth=1.1, alpha=0.95, zorder=2)
314
+ ax.hlines([ymin, ymax], xpos - box_width * 0.26, xpos + box_width * 0.26, color=color, linewidth=1.1, alpha=0.95, zorder=2)
315
+ ax.add_patch(
316
+ Rectangle(
317
+ (xpos - box_width / 2, q1),
318
+ box_width,
319
+ max(0.0, q3 - q1),
320
+ facecolor=color,
321
+ edgecolor="none",
322
+ alpha=0.24,
323
+ zorder=1,
324
+ )
325
+ )
326
+ ax.scatter([xpos], [mean], s=28, marker="s", facecolor=color, edgecolor=color, linewidth=0.8, zorder=3)
327
+
328
+
329
+ def _plot_broad_vs_strict_distribution(panel_df: pd.DataFrame, pdf_path: Path, png_path: Path, svg_path: Path) -> None:
330
+ overlap_df = panel_df.loc[panel_df["strict_pairwise_score"].notna()].copy()
331
+ fig, ax = plt.subplots(figsize=(11.8, 4.8))
332
+ x_positions = list(range(len(MODEL_ORDER)))
333
+ broad_offset = -0.17
334
+ strict_offset = 0.17
335
+
336
+ for idx, model_id in enumerate(MODEL_ORDER):
337
+ subset = overlap_df.loc[overlap_df["model_id"] == model_id].copy()
338
+ if subset.empty:
339
+ continue
340
+ _draw_distribution_summary(
341
+ ax,
342
+ center=float(idx),
343
+ values=subset["current_broad_profile_score"].tolist(),
344
+ color=BROAD_PROFILE_COLOR,
345
+ offset=broad_offset,
346
+ )
347
+ _draw_distribution_summary(
348
+ ax,
349
+ center=float(idx),
350
+ values=subset["strict_pairwise_score"].tolist(),
351
+ color=STRICT_PAIRWISE_COLOR,
352
+ offset=strict_offset,
353
+ )
354
+
355
+ ax.set_xlim(-0.6, len(MODEL_ORDER) - 0.4)
356
+ ax.set_ylim(0.0, 1.02)
357
+ ax.set_xticks(x_positions)
358
+ ax.set_xticklabels([_model_label(model_id) for model_id in MODEL_ORDER], rotation=35, ha="right")
359
+ ax.set_ylabel("Score")
360
+ ax.set_xlabel("Model")
361
+ ax.set_title("Profile-only co-missing: broad vs missing-only pairwise")
362
+ ax.grid(axis="y", alpha=0.28, linestyle=":")
363
+ ax.grid(axis="x", alpha=0.12)
364
+
365
+ legend_handles = [
366
+ Patch(facecolor=BROAD_PROFILE_COLOR, edgecolor="none", alpha=0.6, label="Broad co-missing profile"),
367
+ Patch(facecolor=STRICT_PAIRWISE_COLOR, edgecolor="none", alpha=0.6, label="Missing-only pairwise profile"),
368
+ Line2D([0], [0], marker="s", color="#444444", markerfacecolor="#444444", markersize=5, linewidth=0, label="Mean over overlap datasets"),
369
+ Line2D([0], [0], color="#444444", linewidth=1.1, label="Min-max over overlap datasets"),
370
+ Patch(facecolor="#999999", edgecolor="none", alpha=0.24, label="IQR over overlap datasets"),
371
+ ]
372
+ 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)
373
+
374
+ fig.tight_layout()
375
+ fig.savefig(pdf_path, bbox_inches="tight")
376
+ fig.savefig(png_path, dpi=220, bbox_inches="tight")
377
+ fig.savefig(svg_path, bbox_inches="tight")
378
+ plt.close(fig)
379
+
380
+
381
+ def run_strict_pairwise_diagnostic() -> dict[str, Any]:
382
+ _ensure_dirs()
383
+ asset_df = _load_primary_asset_rows()
384
+ panel_df = _build_strict_panel_df(asset_df)
385
+ model_df = _build_model_summary(panel_df)
386
+ coverage_df = _build_coverage_summary(panel_df)
387
+
388
+ _write_csv(panel_df, DATA_DIR / "strict_pairwise_panel_scores.csv")
389
+ _write_csv(model_df, DATA_DIR / "strict_pairwise_model_summary.csv")
390
+ _write_csv(coverage_df, DATA_DIR / "strict_pairwise_coverage_summary.csv")
391
+
392
+ main_pdf = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.pdf"
393
+ main_png = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.png"
394
+ main_svg = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.svg"
395
+ main_tex = FIG_DIR / "strict_pairwise_vs_broad_model_dumbbell_main.tex"
396
+ scatter_pdf = FIG_DIR / "strict_pairwise_panel_scatter_appendix.pdf"
397
+ scatter_png = FIG_DIR / "strict_pairwise_panel_scatter_appendix.png"
398
+ scatter_svg = FIG_DIR / "strict_pairwise_panel_scatter_appendix.svg"
399
+ scatter_tex = FIG_DIR / "strict_pairwise_panel_scatter_appendix.tex"
400
+ coverage_pdf = FIG_DIR / "strict_pairwise_coverage_bars_appendix.pdf"
401
+ coverage_png = FIG_DIR / "strict_pairwise_coverage_bars_appendix.png"
402
+ coverage_svg = FIG_DIR / "strict_pairwise_coverage_bars_appendix.svg"
403
+ coverage_tex = FIG_DIR / "strict_pairwise_coverage_bars_appendix.tex"
404
+ dist_pdf = FIG_DIR / "strict_pairwise_profile_distribution_main.pdf"
405
+ dist_png = FIG_DIR / "strict_pairwise_profile_distribution_main.png"
406
+ dist_svg = FIG_DIR / "strict_pairwise_profile_distribution_main.svg"
407
+ dist_tex = FIG_DIR / "strict_pairwise_profile_distribution_main.tex"
408
+
409
+ _plot_model_dumbbell(model_df, main_pdf, main_png, main_svg)
410
+ _plot_panel_scatter(panel_df, scatter_pdf, scatter_png, scatter_svg)
411
+ _plot_coverage_bars(coverage_df, coverage_pdf, coverage_png, coverage_svg)
412
+ _plot_broad_vs_strict_distribution(panel_df, dist_pdf, dist_png, dist_svg)
413
+ _write_include_tex(main_tex, "Strict pairwise vs broad co-missingness", main_pdf.name)
414
+ _write_include_tex(scatter_tex, "Strict pairwise overlap scatter", scatter_pdf.name)
415
+ _write_include_tex(coverage_tex, "Strict pairwise coverage shrinkage", coverage_pdf.name)
416
+ _write_include_tex(dist_tex, "Profile-only broad vs strict pairwise distribution", dist_pdf.name)
417
+
418
+ status_counts = panel_df["strict_status"].value_counts(dropna=False).to_dict()
419
+ report_lines = [
420
+ "# Strict Pairwise Co-Missing Diagnostic",
421
+ "",
422
+ "- Canonical missingness family score keeps the broader profile-only structured-missingness view.",
423
+ "- This auxiliary diagnostic restricts the second axis to missing-only column pairs.",
424
+ f"- Primary asset panels reviewed: `{panel_df.shape[0]}`",
425
+ f"- Strict-overlap panels: `{int(panel_df['strict_pairwise_score'].notna().sum())}`",
426
+ f"- Strict-overlap datasets: `{int(panel_df.loc[panel_df['strict_pairwise_score'].notna(), 'dataset_id'].nunique())}`",
427
+ "",
428
+ "## Status counts",
429
+ "",
430
+ ]
431
+ report_lines.extend([f"- `{key}`: `{value}`" for key, value in status_counts.items()])
432
+ (OUTPUT_ROOT / "analysis_report.md").write_text("\n".join(report_lines) + "\n", encoding="utf-8")
433
+ (OUTPUT_ROOT / "paper_caption.txt").write_text(
434
+ "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. "
435
+ "Coverage bars show that the stricter definition is more selective because datasets with only one active missing target column become inapplicable.",
436
+ encoding="utf-8",
437
+ )
438
+ (OUTPUT_ROOT / "paper_paragraphs.md").write_text(
439
+ "\n".join(
440
+ [
441
+ "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.",
442
+ "",
443
+ "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.",
444
+ "",
445
+ ]
446
+ ),
447
+ encoding="utf-8",
448
+ )
449
+
450
+ final_files = [
451
+ DATA_DIR / "strict_pairwise_panel_scores.csv",
452
+ DATA_DIR / "strict_pairwise_model_summary.csv",
453
+ DATA_DIR / "strict_pairwise_coverage_summary.csv",
454
+ OUTPUT_ROOT / "analysis_report.md",
455
+ OUTPUT_ROOT / "paper_caption.txt",
456
+ OUTPUT_ROOT / "paper_paragraphs.md",
457
+ main_pdf,
458
+ main_png,
459
+ main_svg,
460
+ main_tex,
461
+ dist_pdf,
462
+ dist_png,
463
+ dist_svg,
464
+ dist_tex,
465
+ scatter_pdf,
466
+ scatter_png,
467
+ scatter_svg,
468
+ scatter_tex,
469
+ coverage_pdf,
470
+ coverage_png,
471
+ coverage_svg,
472
+ coverage_tex,
473
+ ]
474
+ must_do = {
475
+ main_pdf.name: main_pdf,
476
+ main_png.name: main_png,
477
+ main_svg.name: main_svg,
478
+ main_tex.name: main_tex,
479
+ dist_pdf.name: dist_pdf,
480
+ dist_png.name: dist_png,
481
+ dist_svg.name: dist_svg,
482
+ dist_tex.name: dist_tex,
483
+ scatter_pdf.name: scatter_pdf,
484
+ scatter_png.name: scatter_png,
485
+ scatter_svg.name: scatter_svg,
486
+ scatter_tex.name: scatter_tex,
487
+ coverage_pdf.name: coverage_pdf,
488
+ coverage_png.name: coverage_png,
489
+ coverage_svg.name: coverage_svg,
490
+ coverage_tex.name: coverage_tex,
491
+ }
492
+ sync_final_outputs(FINAL_DIR, final_files, must_do)
493
+ (FINAL_DIR / "README.md").write_text(
494
+ render_final_readme(
495
+ title="Strict Pairwise Co-Missing Diagnostic",
496
+ summary="Auxiliary paper-facing bundle that restricts co-missingness to missing-only column pairs and reports the resulting coverage shrinkage.",
497
+ primary_files=[item.name for item in final_files if item.name.endswith((".png", ".pdf", ".tex"))][:12],
498
+ must_do_files=list(must_do.keys()),
499
+ support_files=[
500
+ "strict_pairwise_panel_scores.csv",
501
+ "strict_pairwise_model_summary.csv",
502
+ "strict_pairwise_coverage_summary.csv",
503
+ "analysis_report.md",
504
+ "paper_caption.txt",
505
+ "paper_paragraphs.md",
506
+ ],
507
+ ),
508
+ encoding="utf-8",
509
+ )
510
+ return {
511
+ "strict_pairwise_panel_scores": DATA_DIR / "strict_pairwise_panel_scores.csv",
512
+ "strict_pairwise_model_summary": DATA_DIR / "strict_pairwise_model_summary.csv",
513
+ "main_figure_png": main_png,
514
+ "coverage_png": coverage_png,
515
+ }
516
+
517
+
518
+ if __name__ == "__main__":
519
+ outputs = run_strict_pairwise_diagnostic()
520
+ for key, value in outputs.items():
521
+ print(f"{key}: {value}")
evaluation/query_family/code_support/tests/comissing_condition_eval.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import math
5
+ from collections import defaultdict
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ from dataclasses import dataclass
8
+ from os import cpu_count
9
+ from pathlib import Path
10
+ from statistics import mean
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from src.eval.common import (
17
+ SyntheticAsset,
18
+ discover_synthetic_assets,
19
+ list_dataset_ids,
20
+ load_field_type_hints,
21
+ normalize_missing,
22
+ resolve_real_split_path,
23
+ write_csv,
24
+ )
25
+
26
+ STATE_OTHER = "__OTHER__"
27
+ STATE_MISSING = "__Z_MISSING__"
28
+ CANONICAL_MARGINAL_AGGREGATION = "direct_mean_over_missing_targets"
29
+ CANONICAL_COMISSING_AGGREGATION = "direct_mean_over_edge_profiles"
30
+ COMPARISON_COMISSING_AGGREGATION = "weighted_by_real_relation_strength"
31
+ COMPOSITE_COMISSING_AGGREGATION = "direct_mean_over_edge_composites_0p7profile_0p3strength"
32
+ EPS = 1e-12
33
+ TOP_CATEGORIES = 8
34
+ NUMERIC_BINS = 5
35
+ MIN_MISSING_COUNT_ABS = 5
36
+ MIN_MISSING_RATE = 0.005
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class ColumnStateEncoder:
41
+ column: str
42
+ kind: str
43
+ states: tuple[str, ...]
44
+ top_categories: tuple[str, ...] = ()
45
+ bin_edges: tuple[float, ...] = ()
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class EdgeDefinition:
50
+ missing_target: str
51
+ related_column: str
52
+ encoder: ColumnStateEncoder
53
+ real_missing_rate: float
54
+ supported_state_indices: tuple[int, ...]
55
+ real_state_probabilities: tuple[float, ...]
56
+ real_conditional_missing_rates: tuple[float, ...]
57
+ real_relation_strength: float
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class TargetDefinition:
62
+ column: str
63
+ missing_count: int
64
+ missing_rate: float
65
+ info_weight: float
66
+ edges: tuple[EdgeDefinition, ...]
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class DatasetContext:
71
+ dataset_id: str
72
+ row_count: int
73
+ columns: tuple[str, ...]
74
+ column_kinds: dict[str, str]
75
+ encoders: dict[str, ColumnStateEncoder]
76
+ missing_targets: tuple[TargetDefinition, ...]
77
+
78
+
79
+ def _clip01(value: float) -> float:
80
+ return max(0.0, min(1.0, float(value)))
81
+
82
+
83
+ def _binary_entropy(p: float) -> float:
84
+ p = min(max(float(p), 0.0), 1.0)
85
+ if p <= 0.0 or p >= 1.0:
86
+ return 0.0
87
+ return -(p * math.log2(p) + (1.0 - p) * math.log2(1.0 - p))
88
+
89
+
90
+ def _load_real_df(dataset_id: str) -> pd.DataFrame:
91
+ real_path = resolve_real_split_path(dataset_id, split="train")
92
+ if not real_path.exists():
93
+ raise FileNotFoundError(f"Train split missing for {dataset_id}: {real_path}")
94
+ try:
95
+ return pd.read_csv(real_path, dtype=str, keep_default_na=False)
96
+ except pd.errors.ParserError:
97
+ sample = real_path.read_text(encoding="utf-8", errors="replace")[:8192]
98
+ try:
99
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
100
+ delimiter = dialect.delimiter
101
+ except csv.Error:
102
+ delimiter = ","
103
+ return pd.read_csv(real_path, dtype=str, keep_default_na=False, sep=delimiter)
104
+
105
+
106
+ def _load_syn_df(synthetic_csv_path: Path, expected_columns: list[str]) -> pd.DataFrame:
107
+ syn_df = pd.read_csv(synthetic_csv_path, dtype=str, keep_default_na=False)
108
+ for column in expected_columns:
109
+ if column not in syn_df.columns:
110
+ syn_df[column] = ""
111
+ syn_df = syn_df[expected_columns]
112
+ return syn_df
113
+
114
+
115
+ def _infer_column_kind(series: pd.Series, hint: str) -> str:
116
+ token = (hint or "").lower()
117
+ if any(word in token for word in ["numeric", "integer", "float", "double", "decimal", "continuous"]):
118
+ return "numeric"
119
+ if any(word in token for word in ["categorical", "string", "text", "boolean", "ordinal"]):
120
+ return "categorical"
121
+ non_missing = series[~series.map(normalize_missing)]
122
+ if non_missing.empty:
123
+ return "categorical"
124
+ parsed = pd.to_numeric(non_missing, errors="coerce")
125
+ ratio = float(parsed.notna().mean()) if len(parsed) else 0.0
126
+ return "numeric" if ratio >= 0.95 else "categorical"
127
+
128
+
129
+ def _build_categorical_encoder(column: str, real_series: pd.Series) -> ColumnStateEncoder:
130
+ non_missing = real_series[~real_series.map(normalize_missing)].astype(str)
131
+ counts = non_missing.value_counts(dropna=False)
132
+ top_categories = tuple(str(item) for item in counts.head(TOP_CATEGORIES).index.tolist())
133
+ states = list(top_categories)
134
+ if len(counts) > len(top_categories):
135
+ states.append(STATE_OTHER)
136
+ if bool(real_series.map(normalize_missing).any()):
137
+ states.append(STATE_MISSING)
138
+ return ColumnStateEncoder(
139
+ column=column,
140
+ kind="categorical",
141
+ states=tuple(states),
142
+ top_categories=top_categories,
143
+ )
144
+
145
+
146
+ def _build_numeric_encoder(column: str, real_series: pd.Series) -> ColumnStateEncoder | None:
147
+ parsed = pd.to_numeric(real_series[~real_series.map(normalize_missing)], errors="coerce").dropna()
148
+ if len(parsed) < 8 or int(parsed.nunique()) < 4:
149
+ return None
150
+ quantiles = np.linspace(0.0, 1.0, NUMERIC_BINS + 1)
151
+ edges = np.quantile(parsed.to_numpy(dtype=float), quantiles)
152
+ edges = np.unique(edges.astype(float))
153
+ if len(edges) < 3:
154
+ return None
155
+ inner_edges = tuple(float(value) for value in edges[1:-1].tolist())
156
+ bin_count = len(inner_edges) + 1
157
+ states = [f"bin_{idx}" for idx in range(bin_count)]
158
+ if bool(real_series.map(normalize_missing).any()):
159
+ states.append(STATE_MISSING)
160
+ return ColumnStateEncoder(
161
+ column=column,
162
+ kind="numeric",
163
+ states=tuple(states),
164
+ bin_edges=inner_edges,
165
+ )
166
+
167
+
168
+ def _build_encoder(column: str, real_series: pd.Series, hint: str) -> ColumnStateEncoder:
169
+ inferred_kind = _infer_column_kind(real_series, hint)
170
+ if inferred_kind == "numeric":
171
+ numeric_encoder = _build_numeric_encoder(column, real_series)
172
+ if numeric_encoder is not None:
173
+ return numeric_encoder
174
+ return _build_categorical_encoder(column, real_series)
175
+
176
+
177
+ def _encode_series(series: pd.Series, encoder: ColumnStateEncoder) -> pd.Series:
178
+ normalized = series.fillna("").astype(str)
179
+ if encoder.kind == "categorical":
180
+ top = set(encoder.top_categories)
181
+
182
+ def _map_value(value: str) -> str:
183
+ if normalize_missing(value):
184
+ return STATE_MISSING if STATE_MISSING in encoder.states else STATE_OTHER
185
+ if value in top:
186
+ return value
187
+ return STATE_OTHER if STATE_OTHER in encoder.states else encoder.states[0]
188
+
189
+ return normalized.map(_map_value)
190
+
191
+ parsed = pd.to_numeric(normalized.where(~normalized.map(normalize_missing), np.nan), errors="coerce")
192
+ bins = [-np.inf, *encoder.bin_edges, np.inf]
193
+ labels = [state for state in encoder.states if state != STATE_MISSING]
194
+ encoded = pd.cut(parsed, bins=bins, labels=labels, include_lowest=True).astype("object")
195
+ if STATE_MISSING in encoder.states:
196
+ encoded = encoded.where(~normalized.map(normalize_missing), STATE_MISSING)
197
+ encoded = encoded.fillna(labels[0] if labels else STATE_MISSING)
198
+ return encoded.astype(str)
199
+
200
+
201
+ def _encode_codes(series: pd.Series, encoder: ColumnStateEncoder) -> np.ndarray:
202
+ encoded = _encode_series(series, encoder)
203
+ return pd.Categorical(encoded, categories=list(encoder.states)).codes.astype(np.int16, copy=False)
204
+
205
+
206
+ def _state_support_counts(encoded_codes: np.ndarray, state_count: int) -> np.ndarray:
207
+ valid = encoded_codes >= 0
208
+ if not bool(np.any(valid)):
209
+ return np.zeros(state_count, dtype=np.int64)
210
+ return np.bincount(encoded_codes[valid], minlength=state_count)
211
+
212
+
213
+ def _conditional_rate_stats(missing_indicator: np.ndarray, encoded_codes: np.ndarray, state_count: int) -> tuple[np.ndarray, np.ndarray]:
214
+ valid = encoded_codes >= 0
215
+ if not bool(np.any(valid)):
216
+ return np.zeros(state_count, dtype=np.int64), np.zeros(state_count, dtype=float)
217
+ support_counts = np.bincount(encoded_codes[valid], minlength=state_count)
218
+ missing_sums = np.bincount(encoded_codes[valid], weights=missing_indicator[valid], minlength=state_count)
219
+ rates = np.zeros(state_count, dtype=float)
220
+ nonzero = support_counts > 0
221
+ rates[nonzero] = missing_sums[nonzero] / support_counts[nonzero]
222
+ return support_counts, rates
223
+
224
+
225
+ def _relation_strength(global_missing_rate: float, state_probabilities: np.ndarray, conditional_rates: np.ndarray) -> float:
226
+ denom = max(global_missing_rate * (1.0 - global_missing_rate), EPS)
227
+ weighted_var = 0.0
228
+ for weight, rate in zip(state_probabilities, conditional_rates):
229
+ weighted_var += float(weight) * ((float(rate) - global_missing_rate) ** 2)
230
+ return _clip01(weighted_var / denom)
231
+
232
+
233
+ def build_dataset_context(dataset_id: str) -> DatasetContext:
234
+ real_df = _load_real_df(dataset_id)
235
+ row_count = len(real_df)
236
+ columns = [str(col) for col in real_df.columns]
237
+ missing_counts = {
238
+ col: int(real_df[col].map(normalize_missing).sum())
239
+ for col in columns
240
+ }
241
+ target_defs: list[TargetDefinition] = []
242
+ min_missing_count = max(MIN_MISSING_COUNT_ABS, int(math.ceil(row_count * MIN_MISSING_RATE)))
243
+
244
+ active_target_columns = [
245
+ col
246
+ for col in columns
247
+ if missing_counts[col] >= min_missing_count
248
+ and 0 < missing_counts[col] < row_count
249
+ ]
250
+ if not active_target_columns:
251
+ return DatasetContext(
252
+ dataset_id=dataset_id,
253
+ row_count=row_count,
254
+ columns=tuple(columns),
255
+ column_kinds={},
256
+ encoders={},
257
+ missing_targets=(),
258
+ )
259
+
260
+ hints = load_field_type_hints(dataset_id)
261
+ column_kinds = {col: _infer_column_kind(real_df[col], hints.get(col, "")) for col in columns}
262
+ encoders = {col: _build_encoder(col, real_df[col], hints.get(col, "")) for col in columns}
263
+ real_encoded_cache = {
264
+ col: _encode_codes(real_df[col], encoders[col])
265
+ for col in columns
266
+ }
267
+
268
+ for target_col in active_target_columns:
269
+ missing_indicator = real_df[target_col].map(normalize_missing).to_numpy(dtype=float)
270
+ missing_count = missing_counts[target_col]
271
+ missing_rate = float(missing_count / max(1, row_count))
272
+
273
+ info_weight = _binary_entropy(missing_rate) * math.log1p(missing_count)
274
+ edge_defs: list[EdgeDefinition] = []
275
+ for related_col in columns:
276
+ if related_col == target_col:
277
+ continue
278
+ encoder = encoders[related_col]
279
+ encoded_real = real_encoded_cache[related_col]
280
+ support_counts = _state_support_counts(encoded_real, len(encoder.states))
281
+ supported_state_indices = tuple(int(idx) for idx in np.where(support_counts > 0)[0].tolist())
282
+ if len(supported_state_indices) < 2:
283
+ continue
284
+ state_probabilities = support_counts.astype(float) / max(1, row_count)
285
+ _, conditional_rates = _conditional_rate_stats(missing_indicator, encoded_real, len(encoder.states))
286
+ strength = _relation_strength(missing_rate, state_probabilities, conditional_rates)
287
+ edge_defs.append(
288
+ EdgeDefinition(
289
+ missing_target=target_col,
290
+ related_column=related_col,
291
+ encoder=encoder,
292
+ real_missing_rate=missing_rate,
293
+ supported_state_indices=supported_state_indices,
294
+ real_state_probabilities=tuple(float(v) for v in state_probabilities.tolist()),
295
+ real_conditional_missing_rates=tuple(float(v) for v in conditional_rates.tolist()),
296
+ real_relation_strength=strength,
297
+ )
298
+ )
299
+
300
+ if edge_defs:
301
+ target_defs.append(
302
+ TargetDefinition(
303
+ column=target_col,
304
+ missing_count=missing_count,
305
+ missing_rate=missing_rate,
306
+ info_weight=float(info_weight),
307
+ edges=tuple(edge_defs),
308
+ )
309
+ )
310
+
311
+ return DatasetContext(
312
+ dataset_id=dataset_id,
313
+ row_count=row_count,
314
+ columns=tuple(columns),
315
+ column_kinds=column_kinds,
316
+ encoders=encoders,
317
+ missing_targets=tuple(target_defs),
318
+ )
319
+
320
+
321
+ def _score_edge(
322
+ target: TargetDefinition,
323
+ edge: EdgeDefinition,
324
+ missing_indicator: np.ndarray,
325
+ encoded_syn: np.ndarray,
326
+ ) -> tuple[float, float, float]:
327
+ global_missing_rate = float(np.mean(missing_indicator))
328
+ support_counts, synthetic_rates = _conditional_rate_stats(missing_indicator, encoded_syn, len(edge.encoder.states))
329
+
330
+ profile_distance = 0.0
331
+ synthetic_rates_fallback = synthetic_rates.copy()
332
+ zero_support = support_counts <= 0
333
+ synthetic_rates_fallback[zero_support] = global_missing_rate
334
+ for idx in edge.supported_state_indices:
335
+ real_weight = edge.real_state_probabilities[idx]
336
+ syn_rate = synthetic_rates_fallback[idx]
337
+ real_rate = edge.real_conditional_missing_rates[idx]
338
+ profile_distance += float(real_weight) * abs(float(real_rate) - float(syn_rate))
339
+ profile_score = _clip01(1.0 - profile_distance)
340
+
341
+ denom = max(global_missing_rate * (1.0 - global_missing_rate), EPS)
342
+ weighted_var = 0.0
343
+ for idx in edge.supported_state_indices:
344
+ weighted_var += float(edge.real_state_probabilities[idx]) * ((float(synthetic_rates_fallback[idx]) - global_missing_rate) ** 2)
345
+ synthetic_strength = _clip01(weighted_var / denom)
346
+ strength_score = _clip01(1.0 - abs(edge.real_relation_strength - synthetic_strength))
347
+
348
+ edge_score = _clip01((0.7 * profile_score) + (0.3 * strength_score))
349
+ return edge_score, profile_score, strength_score
350
+
351
+
352
+ def score_synthetic_df(context: DatasetContext, syn_df: pd.DataFrame) -> tuple[dict[str, Any], list[dict[str, Any]]]:
353
+ if not context.missing_targets:
354
+ return (
355
+ {
356
+ "status": "not_applicable_no_missing_targets",
357
+ "marginal_aggregation_scheme": CANONICAL_MARGINAL_AGGREGATION,
358
+ "canonical_aggregation_scheme": CANONICAL_COMISSING_AGGREGATION,
359
+ "comparison_aggregation_scheme": COMPARISON_COMISSING_AGGREGATION,
360
+ "marginal_missing_rate_consistency": None,
361
+ "co_missingness_pattern_consistency": None,
362
+ "missingness_structure_score": None,
363
+ "comparison_missingness_structure_score": None,
364
+ "canonical_score": None,
365
+ "direct_mean_score": None,
366
+ "weighted_score": None,
367
+ "missing_target_count": 0,
368
+ "edge_count": 0,
369
+ },
370
+ [],
371
+ )
372
+
373
+ target_rows: list[dict[str, Any]] = []
374
+ marginal_target_scores: list[float] = []
375
+ all_edge_scores: list[float] = []
376
+ all_profile_scores: list[float] = []
377
+ all_strength_scores: list[float] = []
378
+ weighted_target_scores: list[tuple[float, float]] = []
379
+ encoded_cache = {
380
+ column: _encode_codes(syn_df[column], encoder)
381
+ for column, encoder in context.encoders.items()
382
+ }
383
+ missing_indicator_cache = {
384
+ target.column: syn_df[target.column].map(normalize_missing).to_numpy(dtype=float)
385
+ for target in context.missing_targets
386
+ }
387
+
388
+ for target in context.missing_targets:
389
+ missing_indicator = missing_indicator_cache[target.column]
390
+ synthetic_missing_rate = float(np.mean(missing_indicator))
391
+ marginal_target_score = _clip01(1.0 - abs(float(target.missing_rate) - synthetic_missing_rate))
392
+ edge_scores: list[float] = []
393
+ edge_weights: list[float] = []
394
+ mean_profile_scores: list[float] = []
395
+ mean_strength_scores: list[float] = []
396
+ informative_edge_count = 0
397
+
398
+ for edge in target.edges:
399
+ edge_score, profile_score, strength_score = _score_edge(
400
+ target,
401
+ edge,
402
+ missing_indicator,
403
+ encoded_cache[edge.related_column],
404
+ )
405
+ edge_scores.append(edge_score)
406
+ edge_weights.append(edge.real_relation_strength)
407
+ mean_profile_scores.append(profile_score)
408
+ mean_strength_scores.append(strength_score)
409
+ all_edge_scores.append(edge_score)
410
+ all_profile_scores.append(profile_score)
411
+ all_strength_scores.append(strength_score)
412
+ if edge.real_relation_strength > 0:
413
+ informative_edge_count += 1
414
+
415
+ if not edge_scores:
416
+ continue
417
+
418
+ marginal_target_scores.append(marginal_target_score)
419
+ direct_target_score = float(mean(mean_profile_scores))
420
+ strength_target_score = float(mean(mean_strength_scores))
421
+ composite_target_score = float(mean(edge_scores))
422
+ total_weight = float(sum(edge_weights))
423
+ if total_weight > 0:
424
+ weighted_target_score = float(sum(score * weight for score, weight in zip(edge_scores, edge_weights)) / total_weight)
425
+ else:
426
+ weighted_target_score = composite_target_score
427
+
428
+ weighted_target_scores.append((weighted_target_score, target.info_weight))
429
+ target_rows.append(
430
+ {
431
+ "missing_target": target.column,
432
+ "missing_count_real": target.missing_count,
433
+ "missing_rate_real": round(target.missing_rate, 6),
434
+ "missing_rate_synthetic": round(synthetic_missing_rate, 6),
435
+ "marginal_target_score": round(marginal_target_score, 6),
436
+ "target_info_weight": round(target.info_weight, 6),
437
+ "edge_count": len(edge_scores),
438
+ "informative_edge_count": informative_edge_count,
439
+ "co_missing_direct_target_score": round(direct_target_score, 6),
440
+ "co_missing_profile_target_score": round(direct_target_score, 6),
441
+ "co_missing_strength_target_score": round(strength_target_score, 6),
442
+ "co_missing_composite_target_score": round(composite_target_score, 6),
443
+ "co_missing_weighted_target_score": round(weighted_target_score, 6),
444
+ "missingness_structure_target_score": round(float(mean([marginal_target_score, direct_target_score])), 6),
445
+ "mean_profile_score": round(float(mean(mean_profile_scores)), 6),
446
+ "mean_strength_score": round(float(mean(mean_strength_scores)), 6),
447
+ }
448
+ )
449
+
450
+ if not all_profile_scores or not target_rows or not marginal_target_scores:
451
+ return (
452
+ {
453
+ "status": "not_applicable_no_edges",
454
+ "marginal_aggregation_scheme": CANONICAL_MARGINAL_AGGREGATION,
455
+ "canonical_aggregation_scheme": CANONICAL_COMISSING_AGGREGATION,
456
+ "composite_aggregation_scheme": COMPOSITE_COMISSING_AGGREGATION,
457
+ "comparison_aggregation_scheme": COMPARISON_COMISSING_AGGREGATION,
458
+ "marginal_missing_rate_consistency": None,
459
+ "co_missingness_pattern_consistency": None,
460
+ "co_missing_strength_score": None,
461
+ "co_missing_composite_score": None,
462
+ "missingness_structure_score": None,
463
+ "comparison_missingness_structure_score": None,
464
+ "canonical_score": None,
465
+ "direct_mean_score": None,
466
+ "weighted_score": None,
467
+ "missing_target_count": len(context.missing_targets),
468
+ "edge_count": 0,
469
+ },
470
+ target_rows,
471
+ )
472
+
473
+ marginal_missing_rate_consistency = float(mean(marginal_target_scores))
474
+ direct_mean_score = float(mean(all_profile_scores))
475
+ strength_score = float(mean(all_strength_scores))
476
+ composite_score = float(mean(all_edge_scores))
477
+ weight_sum = float(sum(weight for _, weight in weighted_target_scores))
478
+ if weight_sum > 0:
479
+ weighted_score = float(sum(score * weight for score, weight in weighted_target_scores) / weight_sum)
480
+ else:
481
+ weighted_score = float(mean(score for score, _ in weighted_target_scores))
482
+ missingness_structure_score = float(mean([marginal_missing_rate_consistency, direct_mean_score]))
483
+ comparison_missingness_structure_score = float(mean([marginal_missing_rate_consistency, weighted_score]))
484
+
485
+ return (
486
+ {
487
+ "status": "ok",
488
+ "marginal_aggregation_scheme": CANONICAL_MARGINAL_AGGREGATION,
489
+ "canonical_aggregation_scheme": CANONICAL_COMISSING_AGGREGATION,
490
+ "composite_aggregation_scheme": COMPOSITE_COMISSING_AGGREGATION,
491
+ "comparison_aggregation_scheme": COMPARISON_COMISSING_AGGREGATION,
492
+ "marginal_missing_rate_consistency": round(marginal_missing_rate_consistency, 6),
493
+ "co_missingness_pattern_consistency": round(direct_mean_score, 6),
494
+ "co_missing_strength_score": round(strength_score, 6),
495
+ "co_missing_composite_score": round(composite_score, 6),
496
+ "missingness_structure_score": round(missingness_structure_score, 6),
497
+ "comparison_missingness_structure_score": round(comparison_missingness_structure_score, 6),
498
+ "canonical_score": round(direct_mean_score, 6),
499
+ "direct_mean_score": round(direct_mean_score, 6),
500
+ "weighted_score": round(weighted_score, 6),
501
+ "missing_target_count": len(target_rows),
502
+ "edge_count": len(all_edge_scores),
503
+ "score_gap_weighted_minus_direct": round(weighted_score - direct_mean_score, 6),
504
+ },
505
+ target_rows,
506
+ )
507
+
508
+
509
+ def _dataset_context_rows(context: DatasetContext) -> dict[str, Any]:
510
+ return {
511
+ "dataset_id": context.dataset_id,
512
+ "row_count": context.row_count,
513
+ "column_count": len(context.columns),
514
+ "missing_target_count": len(context.missing_targets),
515
+ "edge_count": sum(len(target.edges) for target in context.missing_targets),
516
+ "missing_targets": ",".join(target.column for target in context.missing_targets),
517
+ }
518
+
519
+
520
+ def _evaluate_dataset_assets(dataset_id: str, dataset_assets: list[SyntheticAsset]) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
521
+ context = build_dataset_context(dataset_id)
522
+ context_row = _dataset_context_rows(context)
523
+ asset_rows: list[dict[str, Any]] = []
524
+ target_rows: list[dict[str, Any]] = []
525
+
526
+ for asset in dataset_assets:
527
+ syn_df = _load_syn_df(Path(asset.synthetic_csv_path), list(context.columns))
528
+ score_row, per_target_rows = score_synthetic_df(context, syn_df)
529
+ asset_row = {
530
+ **asset.to_dict(),
531
+ "dataset_id": dataset_id,
532
+ **score_row,
533
+ }
534
+ asset_rows.append(asset_row)
535
+ for target_row in per_target_rows:
536
+ target_rows.append(
537
+ {
538
+ **asset.to_dict(),
539
+ "dataset_id": dataset_id,
540
+ "status": score_row.get("status"),
541
+ **target_row,
542
+ }
543
+ )
544
+
545
+ return context_row, asset_rows, target_rows
546
+
547
+
548
+ def _mean_or_none(values: list[float | None]) -> float | None:
549
+ cleaned = [float(value) for value in values if value is not None]
550
+ if not cleaned:
551
+ return None
552
+ return float(mean(cleaned))
553
+
554
+
555
+ def _summarize_asset_rows(asset_rows: list[dict[str, Any]], group_keys: tuple[str, ...]) -> list[dict[str, Any]]:
556
+ grouped: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list)
557
+ for row in asset_rows:
558
+ grouped[tuple(str(row.get(key) or "") for key in group_keys)].append(row)
559
+
560
+ summary_rows: list[dict[str, Any]] = []
561
+ for key, rows in sorted(grouped.items()):
562
+ payload = {field: value for field, value in zip(group_keys, key)}
563
+ payload["asset_count"] = len(rows)
564
+ payload["applicable_asset_count"] = sum(1 for row in rows if row.get("status") == "ok")
565
+ payload["marginal_aggregation_scheme"] = CANONICAL_MARGINAL_AGGREGATION
566
+ payload["canonical_aggregation_scheme"] = CANONICAL_COMISSING_AGGREGATION
567
+ payload["composite_aggregation_scheme"] = COMPOSITE_COMISSING_AGGREGATION
568
+ payload["comparison_aggregation_scheme"] = COMPARISON_COMISSING_AGGREGATION
569
+ payload["marginal_missing_rate_consistency"] = _mean_or_none(
570
+ [row.get("marginal_missing_rate_consistency") for row in rows if row.get("status") == "ok"]
571
+ )
572
+ payload["co_missingness_pattern_consistency"] = _mean_or_none(
573
+ [row.get("co_missingness_pattern_consistency") for row in rows if row.get("status") == "ok"]
574
+ )
575
+ payload["co_missing_strength_score"] = _mean_or_none(
576
+ [row.get("co_missing_strength_score") for row in rows if row.get("status") == "ok"]
577
+ )
578
+ payload["co_missing_composite_score"] = _mean_or_none(
579
+ [row.get("co_missing_composite_score") for row in rows if row.get("status") == "ok"]
580
+ )
581
+ payload["missingness_structure_score"] = _mean_or_none(
582
+ [row.get("missingness_structure_score") for row in rows if row.get("status") == "ok"]
583
+ )
584
+ payload["comparison_missingness_structure_score"] = _mean_or_none(
585
+ [row.get("comparison_missingness_structure_score") for row in rows if row.get("status") == "ok"]
586
+ )
587
+ payload["canonical_score"] = _mean_or_none([row.get("canonical_score") for row in rows if row.get("status") == "ok"])
588
+ payload["direct_mean_score"] = _mean_or_none([row.get("direct_mean_score") for row in rows if row.get("status") == "ok"])
589
+ payload["weighted_score"] = _mean_or_none([row.get("weighted_score") for row in rows if row.get("status") == "ok"])
590
+ payload["score_gap_weighted_minus_direct"] = _mean_or_none(
591
+ [row.get("score_gap_weighted_minus_direct") for row in rows if row.get("status") == "ok"]
592
+ )
593
+ for field in (
594
+ "marginal_missing_rate_consistency",
595
+ "co_missingness_pattern_consistency",
596
+ "co_missing_strength_score",
597
+ "co_missing_composite_score",
598
+ "missingness_structure_score",
599
+ "comparison_missingness_structure_score",
600
+ "canonical_score",
601
+ "direct_mean_score",
602
+ "weighted_score",
603
+ "score_gap_weighted_minus_direct",
604
+ ):
605
+ if payload[field] is not None:
606
+ payload[field] = round(float(payload[field]), 6)
607
+ summary_rows.append(payload)
608
+ return summary_rows
609
+
610
+
611
+ def evaluate_all_synthetic_assets(output_dir: Path, max_workers: int | None = None) -> dict[str, Path]:
612
+ output_dir.mkdir(parents=True, exist_ok=True)
613
+ dataset_ids = list_dataset_ids()
614
+ assets = discover_synthetic_assets(datasets=dataset_ids, latest_only=True)
615
+ dataset_asset_map: dict[str, list[SyntheticAsset]] = defaultdict(list)
616
+ for asset in assets:
617
+ dataset_asset_map[asset.dataset_id].append(asset)
618
+
619
+ dataset_context_rows: list[dict[str, Any]] = []
620
+ asset_rows: list[dict[str, Any]] = []
621
+ target_rows: list[dict[str, Any]] = []
622
+
623
+ worker_count = max_workers if max_workers is not None else min(8, max(1, (cpu_count() or 4) - 1))
624
+ futures = {}
625
+ with ThreadPoolExecutor(max_workers=max(1, worker_count)) as executor:
626
+ for dataset_id in dataset_ids:
627
+ futures[executor.submit(_evaluate_dataset_assets, dataset_id, dataset_asset_map.get(dataset_id, []))] = dataset_id
628
+ for index, future in enumerate(as_completed(futures), start=1):
629
+ dataset_id = futures[future]
630
+ context_row, dataset_asset_rows, dataset_target_rows = future.result()
631
+ dataset_context_rows.append(context_row)
632
+ asset_rows.extend(dataset_asset_rows)
633
+ target_rows.extend(dataset_target_rows)
634
+ print(
635
+ f"[co-missing] dataset={index}/{len(dataset_ids)}"
636
+ f" id={dataset_id}"
637
+ f" assets={len(dataset_asset_rows)}"
638
+ f" missing_targets={context_row.get('missing_target_count')}",
639
+ flush=True,
640
+ )
641
+
642
+ model_dataset_rows = _summarize_asset_rows(asset_rows, ("dataset_id", "model_id"))
643
+ model_overall_rows = _summarize_asset_rows(asset_rows, ("model_id",))
644
+
645
+ dataset_context_path = output_dir / "co_missing_dataset_context.csv"
646
+ asset_scores_path = output_dir / "co_missing_asset_scores.csv"
647
+ target_scores_path = output_dir / "co_missing_target_scores.csv"
648
+ model_dataset_path = output_dir / "co_missing_model_dataset_summary.csv"
649
+ model_overall_path = output_dir / "co_missing_model_overall_summary.csv"
650
+
651
+ write_csv(dataset_context_path, dataset_context_rows)
652
+ write_csv(asset_scores_path, asset_rows)
653
+ write_csv(target_scores_path, target_rows)
654
+ write_csv(model_dataset_path, model_dataset_rows)
655
+ write_csv(model_overall_path, model_overall_rows)
656
+
657
+ return {
658
+ "dataset_context": dataset_context_path,
659
+ "asset_scores": asset_scores_path,
660
+ "target_scores": target_scores_path,
661
+ "model_dataset_summary": model_dataset_path,
662
+ "model_overall_summary": model_overall_path,
663
+ }