from __future__ import annotations from pathlib import Path import matplotlib.pyplot as plt import numpy as np import pandas as pd ROOT = Path(__file__).resolve().parents[4] BASE = ROOT / "Evaluation" / "query_fivepart_breakdown" / "conditional_breakdown" OUT_DIR = BASE / "strength_focus" RUN_DIR = ( BASE / "locality_support_diagnostics" / "runs" / "20260502_064421_conditional_locality_support" / "data" ) MODEL_COLORS = { "RealTabFormer": "#332288", "TVAE": "#4477AA", "ForestDiffusion": "#228833", "TabDDPM": "#EE7733", "TabSyn": "#66CCEE", "TabDiff": "#AA3377", "CTGAN": "#EE6677", "ARF": "#777777", "BayesNet": "#CCBB44", "TabPFGen": "#009988", "TabbyFlow": "#882255", } SUPPORT_BUCKET_ORDER = ["dense", "medium", "sparse"] SUPPORT_BUCKET_LABELS = {"dense": "Dense", "medium": "Medium", "sparse": "Sparse"} SUPPORT_BUCKET_COLORS = {"dense": "#1b9e77", "medium": "#7570b3", "sparse": "#d95f02"} def _assign_primary_support_buckets(audit_df: pd.DataFrame) -> pd.DataFrame: case_df = audit_df[ [ "dataset_id", "query_id", "real_support_value", "support_main_eligible", "support_recovery_mode", "template_name", ] ].drop_duplicates() eligible = case_df[ (case_df["support_main_eligible"] == True) & (case_df["support_recovery_mode"].isin(["exact", "derived_exact"])) & (case_df["real_support_value"].notna()) ].copy() rows: list[pd.DataFrame] = [] for dataset_id, group in eligible.groupby("dataset_id", sort=False): values = pd.to_numeric(group["real_support_value"], errors="coerce") if group.shape[0] < 3 or values.dropna().nunique() < 3: continue ranked = values.rank(method="first") bins = pd.qcut(ranked, q=3, labels=["sparse", "medium", "dense"]) assigned = group[["dataset_id", "query_id"]].copy() assigned["support_bucket"] = bins.astype(str) rows.append(assigned) return pd.concat(rows, ignore_index=True) def _build_strength_tables() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]: model_summary = pd.read_csv(BASE / "final" / "model_summary__v2.csv") audit = pd.read_csv(RUN_DIR / "conditional_support_method_audit.csv") bucket_map = _assign_primary_support_buckets(audit) overall = model_summary[ [ "model_label", "dataset_count", "dependency_strength_similarity__mean", "dependency_strength_similarity__ci95_low", "dependency_strength_similarity__ci95_high", "dependency_strength_similarity__ci95_radius", ] ].rename( columns={ "dependency_strength_similarity__mean": "strength_mean", "dependency_strength_similarity__ci95_low": "strength_ci95_low", "dependency_strength_similarity__ci95_high": "strength_ci95_high", "dependency_strength_similarity__ci95_radius": "strength_ci95_radius", } ) overall = overall.sort_values("strength_mean", ascending=False).reset_index(drop=True) strength_rows = audit[audit["subitem_label"] == "Dependency strength similarity"].copy() strength_rows = strength_rows.merge(bucket_map, on=["dataset_id", "query_id"], how="inner") panel_strength = ( strength_rows.groupby( ["dataset_id", "dataset_prefix", "model_label", "support_bucket"], as_index=False, )["query_score"] .mean() .rename(columns={"query_score": "panel_strength"}) ) bucket_summary = ( panel_strength.groupby("support_bucket", as_index=False) .agg( strength_mean=("panel_strength", "mean"), strength_std=("panel_strength", "std"), panel_count=("panel_strength", "count"), ) .reset_index(drop=True) ) bucket_summary["strength_se"] = bucket_summary["strength_std"] / np.sqrt(bucket_summary["panel_count"]) bucket_summary["strength_ci95_radius"] = 1.96 * bucket_summary["strength_se"] bucket_summary["bucket_label"] = bucket_summary["support_bucket"].map(SUPPORT_BUCKET_LABELS) bucket_summary["support_bucket"] = pd.Categorical( bucket_summary["support_bucket"], SUPPORT_BUCKET_ORDER, ordered=True ) bucket_summary = bucket_summary.sort_values("support_bucket").reset_index(drop=True) model_bucket = ( panel_strength.groupby(["model_label", "support_bucket"], as_index=False)["panel_strength"] .mean() .rename(columns={"panel_strength": "strength_mean"}) ) model_bucket["bucket_label"] = model_bucket["support_bucket"].map(SUPPORT_BUCKET_LABELS) pivot = model_bucket.pivot(index="model_label", columns="support_bucket", values="strength_mean").reset_index() for bucket in SUPPORT_BUCKET_ORDER: if bucket not in pivot.columns: pivot[bucket] = np.nan pivot["range"] = pivot[SUPPORT_BUCKET_ORDER].max(axis=1) - pivot[SUPPORT_BUCKET_ORDER].min(axis=1) pivot = pivot.sort_values("dense", ascending=False).reset_index(drop=True) return overall, bucket_summary, model_bucket, pivot def _plot_overall_strength(overall: pd.DataFrame) -> None: fig, ax = plt.subplots(figsize=(11, 6)) x = np.arange(len(overall)) colors = [MODEL_COLORS.get(model, "#999999") for model in overall["model_label"]] ax.bar(x, overall["strength_mean"], color=colors, edgecolor="black", linewidth=0.5) ax.errorbar( x, overall["strength_mean"], yerr=overall["strength_ci95_radius"], fmt="none", ecolor="black", elinewidth=1, capsize=3, ) ax.set_xticks(x) ax.set_xticklabels(overall["model_label"], rotation=45, ha="right") ax.set_ylabel("Dependency strength similarity") ax.set_title("Overall conditional strength by model") ax.set_ylim(0, 0.8) ax.grid(axis="y", alpha=0.25) fig.tight_layout() fig.savefig(OUT_DIR / "fig_strength_overall_model_bars.png", dpi=220) fig.savefig(OUT_DIR / "fig_strength_overall_model_bars.pdf") plt.close(fig) def _plot_strength_bucket_summary(bucket_summary: pd.DataFrame) -> None: fig, ax = plt.subplots(figsize=(7, 5)) x = np.arange(len(bucket_summary)) colors = [SUPPORT_BUCKET_COLORS[b] for b in bucket_summary["support_bucket"].astype(str)] ax.bar(x, bucket_summary["strength_mean"], color=colors, edgecolor="black", linewidth=0.6) ax.errorbar( x, bucket_summary["strength_mean"], yerr=bucket_summary["strength_ci95_radius"], fmt="none", ecolor="black", elinewidth=1, capsize=4, ) ax.set_xticks(x) ax.set_xticklabels(bucket_summary["bucket_label"]) ax.set_ylabel("Dependency strength similarity") ax.set_title("Conditional strength by support bucket") ax.set_ylim(0, 0.45) ax.grid(axis="y", alpha=0.25) fig.tight_layout() fig.savefig(OUT_DIR / "fig_strength_support_bucket_summary.png", dpi=220) fig.savefig(OUT_DIR / "fig_strength_support_bucket_summary.pdf") plt.close(fig) def _plot_strength_by_model_bucket(model_bucket_pivot: pd.DataFrame) -> None: models = model_bucket_pivot["model_label"].tolist() x = np.arange(len(models)) width = 0.23 fig, ax = plt.subplots(figsize=(12, 6)) for idx, bucket in enumerate(SUPPORT_BUCKET_ORDER): offset = (idx - 1) * width ax.bar( x + offset, model_bucket_pivot[bucket], width=width, label=SUPPORT_BUCKET_LABELS[bucket], color=SUPPORT_BUCKET_COLORS[bucket], edgecolor="black", linewidth=0.4, ) ax.set_xticks(x) ax.set_xticklabels(models, rotation=45, ha="right") ax.set_ylabel("Dependency strength similarity") ax.set_title("Conditional strength by model and support bucket") ax.set_ylim(0, 0.45) ax.grid(axis="y", alpha=0.25) ax.legend(frameon=False, ncol=3, loc="upper center") fig.tight_layout() fig.savefig(OUT_DIR / "fig_strength_support_by_model.png", dpi=220) fig.savefig(OUT_DIR / "fig_strength_support_by_model.pdf") plt.close(fig) def _write_report( overall: pd.DataFrame, bucket_summary: pd.DataFrame, model_bucket_pivot: pd.DataFrame, ) -> None: top = overall.iloc[0] bottom = overall.iloc[-1] dense = bucket_summary.loc[bucket_summary["support_bucket"].astype(str) == "dense", "strength_mean"].iloc[0] medium = bucket_summary.loc[bucket_summary["support_bucket"].astype(str) == "medium", "strength_mean"].iloc[0] sparse = bucket_summary.loc[bucket_summary["support_bucket"].astype(str) == "sparse", "strength_mean"].iloc[0] flat = model_bucket_pivot.sort_values("range").head(3) volatile = model_bucket_pivot.sort_values("range", ascending=False).head(3) report = f"""# Strength-Only Conditional Analysis ## Scope - Focus metric: `dependency_strength_similarity` - Overall source: `final/model_summary__v2.csv` - Support-bucket source: `locality_support_diagnostics/runs/20260502_064421_conditional_locality_support` - Primary support variant: `scalar_filtered_local` ## What this isolates This bundle ignores `direction_consistency` and `slice_level_consistency` and asks only one question: > When the real data contains a conditional relationship, does the synthetic data preserve how *strong* that relationship is? In downstream terms, this matters for tasks such as: - deciding which conditional signals look strongest and therefore most actionable - ranking features, slices, or segments by how tightly they track an outcome - screening for candidate interactions before deeper local analysis If strength is distorted, a downstream analyst may still see the right columns and the right report shape, but mis-rank which relationships deserve attention. ## Main findings 1. Overall model spread is real but not huge: the top model is `{top['model_label']}` at `{top['strength_mean']:.3f}`, while the weakest is `{bottom['model_label']}` at `{bottom['strength_mean']:.3f}`. 2. In the primary scalar filtered-local subset, support buckets are close: dense=`{dense:.3f}`, medium=`{medium:.3f}`, sparse=`{sparse:.3f}`. 3. This means strength does **not** show a clean sparse-support penalty in the current main support diagnostic. 4. Several models are almost flat across support buckets, especially: - `{flat.iloc[0]['model_label']}` range=`{flat.iloc[0]['range']:.3f}` - `{flat.iloc[1]['model_label']}` range=`{flat.iloc[1]['range']:.3f}` - `{flat.iloc[2]['model_label']}` range=`{flat.iloc[2]['range']:.3f}` 5. The most bucket-sensitive models still do not follow one universal direction: - `{volatile.iloc[0]['model_label']}` range=`{volatile.iloc[0]['range']:.3f}` - `{volatile.iloc[1]['model_label']}` range=`{volatile.iloc[1]['range']:.3f}` - `{volatile.iloc[2]['model_label']}` range=`{volatile.iloc[2]['range']:.3f}` ## Downstream interpretation - Broad implication: many generators change conditional-strength estimates less across dense/medium/sparse local slices than one might expect. The support size of the slice is therefore not the main explanation for strength distortion. - Practical implication: if a downstream user relies on synthetic data to decide *which* conditional relationships are strongest, the bigger risk is model-specific calibration of strength, not simply sparse local support. - Reading by model family: - `RealTabFormer` is strong overall and also stable across buckets, which makes it the cleanest strength-preserving model in the current panel. - `BayesNet`, `ARF`, and `CTGAN` are comparatively flat across buckets, suggesting that for these models the strength story is more about their overall calibration level than about sensitivity to sparse slices. - `TVAE`, `TabbyFlow`, and `TabSyn` vary more by bucket, but even there the movement is not monotonic dense-to-sparse collapse. ## Applicability note The primary `Dense / Medium / Sparse` analysis is **not** a universal conditional-family split. It applies only to filtered-local templates whose support can be defined as a scalar real row count: - `Filtered Median Numeric Slice` - `Filtered Sum in Numeric Band` `Filtered Two-Dimensional Group Count` is excluded from the main bucket claim because its natural support object is a per-cell count distribution rather than one scalar filtered-row count. """ (OUT_DIR / "strength_focus_report.md").write_text(report, encoding="utf-8") readme = """# Strength Focus Strength-only conditional analysis artifacts. Files: - `overall_strength_by_model.csv` - `strength_support_bucket_summary.csv` - `strength_support_by_model.csv` - `fig_strength_overall_model_bars.png` - `fig_strength_support_bucket_summary.png` - `fig_strength_support_by_model.png` - `strength_focus_report.md` Generate / refresh: ```bash python Evaluation/query_fivepart_breakdown/conditional_breakdown/strength_focus/generate_strength_focus.py ``` """ (OUT_DIR / "README.md").write_text(readme, encoding="utf-8") def main() -> None: OUT_DIR.mkdir(parents=True, exist_ok=True) overall, bucket_summary, model_bucket, model_bucket_pivot = _build_strength_tables() overall.to_csv(OUT_DIR / "overall_strength_by_model.csv", index=False) bucket_summary.to_csv(OUT_DIR / "strength_support_bucket_summary.csv", index=False) model_bucket_pivot.to_csv(OUT_DIR / "strength_support_by_model.csv", index=False) model_bucket.to_csv(OUT_DIR / "strength_support_by_model_long.csv", index=False) _plot_overall_strength(overall) _plot_strength_bucket_summary(bucket_summary) _plot_strength_by_model_bucket(model_bucket_pivot) _write_report(overall, bucket_summary, model_bucket_pivot) if __name__ == "__main__": main()