File size: 13,892 Bytes
42dd317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
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()