File size: 12,557 Bytes
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import pandas as pd
from scipy.stats import f, wasserstein_distance

class CausalValidator:
    """Performs rigorous temporal, counterfactual, and domain causality audits
    to detect spurious correlations, shortcut learning, and synthetic artifacts.
    """
    
    def __init__(self, feature_names=None):
        self.feature_names = feature_names or []
        
    def granger_causality_test(self, y, x, max_lag=3):
        """Performs a Granger causality check to see if lagged x Granger-causes y.
        Returns:
            dict: F-statistic, p-value, and whether causality is significant.
        """
        y = np.array(y, dtype=float)
        x = np.array(x, dtype=float)
        n = len(y)
        
        if n < 3 * max_lag + 2:
            return {"f_stat": 0.0, "p_value": 1.0, "is_causal": False}
            
        # Construct design matrix for restricted model (only lags of y)
        # Y_t = c + a_1*Y_{t-1} + ... + a_p*Y_{t-p}
        # Construct design matrix for unrestricted model (lags of y + lags of x)
        # Y_t = c + a_1*Y_{t-1} + ... + a_p*Y_{t-p} + b_1*X_{t-1} + ... + b_p*X_{t-p}
        
        # Target vector: Y[max_lag:]
        Y_target = y[max_lag:]
        n_obs = len(Y_target)
        
        # Design matrix for restricted
        X_res = np.ones((n_obs, 1))
        for lag in range(1, max_lag + 1):
            X_res = np.column_stack((X_res, y[max_lag - lag:-lag]))
            
        # Design matrix for unrestricted
        X_unres = X_res.copy()
        for lag in range(1, max_lag + 1):
            X_unres = np.column_stack((X_unres, x[max_lag - lag:-lag]))
            
        try:
            # Fit restricted model via OLS
            beta_res, res_sum, _, _ = np.linalg.lstsq(X_res, Y_target, rcond=None)
            rss_res = np.sum((Y_target - np.dot(X_res, beta_res)) ** 2)
            
            # Fit unrestricted model
            beta_unres, _, _, _ = np.linalg.lstsq(X_unres, Y_target, rcond=None)
            rss_unres = np.sum((Y_target - np.dot(X_unres, beta_unres)) ** 2)
            
            # F-statistic calculation
            # F = ((rss_res - rss_unres) / p) / (rss_unres / (n - 2p - 1))
            df_num = max_lag
            df_denom = n_obs - (2 * max_lag + 1)
            
            if rss_unres == 0 or df_denom <= 0:
                return {"f_stat": 0.0, "p_value": 1.0, "is_causal": False}
                
            f_stat = ((rss_res - rss_unres) / df_num) / (rss_unres / df_denom)
            f_stat = max(0.0, f_stat)
            
            # Compute survival function (sf = 1 - cdf)
            p_val = f.sf(f_stat, df_num, df_denom)
            
            return {
                "f_stat": float(f_stat),
                "p_value": float(p_val),
                "is_causal": bool(p_val < 0.05)
            }
        except Exception:
            return {"f_stat": 0.0, "p_value": 1.0, "is_causal": False}

    def evaluate_counterfactuals(self, model, X_sample, domain=None):
        """Perturbs key causal features and evaluates if prediction updates match causal expectations.
        Expected directions:
            - runway_months (index 2): higher -> risk should drop
            - savings_rate (index 4): higher -> risk should drop
            - recent_failed_payments_30d (index 12): higher -> risk should rise
            - debt_to_income_ratio (index 3): higher -> risk should rise
        """
        # Feature indices in original NUMERICAL_FEATURES
        # "runway_months" is index 2, "savings_rate" is index 4, "recent_failed_payments_30d" is index 12
        # If model expects invariant embeddings (shape [N, 25]), we can perturb features at feature snapshot level,
        # then pass through normalizer and encoder.
        
        # For simplicity, if we perturb features directly on pre-processed inputs or snapshot dataframe:
        # We will write a utility that takes user feature dataframe, perturbs it, and queries predictions.
        # Here we define the causal rules
        rules = {
            "runway_months": {"direction": -1, "perturb_val": 2.0},  # increase by 2 months should drop probability
            "savings_rate": {"direction": -1, "perturb_val": 0.20},  # increase by 20% should drop probability
            "recent_failed_payments_30d": {"direction": 1, "perturb_val": 1.0}, # increase by 1 payment should increase risk
            "debt_to_income_ratio": {"direction": 1, "perturb_val": 0.20} # increase by 20% debt ratio should increase risk
        }
        
        return rules

    def run_intervention_stability(self, model, X_input, feat_idx, delta=1.0, domains=None):
        """Measures variance of predicted risk when shifting feature at feat_idx by delta (intervention).
        Low stability means predictions collapse or vary wildly across different populations.
        """
        # Baseline prediction
        base_probs = model.predict_proba(X_input, domains=domains)
        
        # Intervened prediction
        X_intervened = X_input.copy()
        X_intervened[:, feat_idx] += delta
        intervened_probs = model.predict_proba(X_intervened, domains=domains)
        
        # Shift magnitude
        diffs = intervened_probs - base_probs
        mean_shift = np.mean(diffs)
        std_shift = np.std(diffs)
        
        # Stability score: 1.0 / (1.0 + variance of the shift)
        stability = 1.0 / (1.0 + float(np.var(diffs)))
        
        return {
            "mean_shift": float(mean_shift),
            "std_shift": float(std_shift),
            "stability_score": stability
        }

    def detect_synthetic_artifacts(self, df_real, df_synth, features_to_check):
        """Compares feature distributions between real and synthetic cohorts.
        Features with massive Wasserstein distances indicate synthetic artifacts.
        """
        artifacts = {}
        for feat in features_to_check:
            if feat not in df_real.columns or feat not in df_synth.columns:
                continue
            v_real = df_real[feat].dropna().values
            v_synth = df_synth[feat].dropna().values
            
            if len(v_real) == 0 or len(v_synth) == 0:
                continue
                
            # Normalize to compare shapes
            r_min, r_max = v_real.min(), v_real.max()
            if r_max - r_min > 0:
                v_real_norm = (v_real - r_min) / (r_max - r_min)
                v_synth_norm = (v_synth - r_min) / (r_max - r_min)
            else:
                v_real_norm = v_real
                v_synth_norm = v_synth
                
            dist = wasserstein_distance(v_real_norm, v_synth_norm)
            artifacts[feat] = float(dist)
            
        return artifacts

    def identify_shortcut_learning(self, real_imps, synth_imps, feature_names):
        """Identifies shortcut learning by highlighting features with high importance
        in synthetic data but zero/low importance in real data.
        """
        shortcuts = {}
        for idx, feat in enumerate(feature_names):
            r_imp = real_imps[idx]
            s_imp = synth_imps[idx]
            
            # Shortcut score: high synthetic importance relative to real importance
            # e.g., if synthetic importance is > 0.05 and real is < 0.01
            score = float(s_imp - r_imp)
            if score > 0.04 and r_imp < 0.01:
                shortcuts[feat] = {
                    "synthetic_importance": float(s_imp),
                    "real_importance": float(r_imp),
                    "shortcut_score": score
                }
        return shortcuts

    def compute_causal_stability_index(self, df_combined, model, feature_names, NUMERICAL_FEATURES):
        """Aggregates all causal audits into a single Causal Stability Index (CSI) from 0 to 1."""
        df_real = df_combined[df_combined["dataset_source"].isin(["CZECH", "INDIA"])]
        df_synth = df_combined[df_combined["dataset_source"].isin(["UK", "SME"])]
        
        # Sample at most 50 users to optimize execution speed of Granger causality and lag persistence checks
        import random
        all_uids = df_combined["user_id"].unique()
        if len(all_uids) > 50:
            random.seed(42)
            sampled_uids = random.sample(list(all_uids), 50)
            df_sampled = df_combined[df_combined["user_id"].isin(sampled_uids)]
        else:
            df_sampled = df_combined

        # 1. Granger causality score
        granger_scores = []
        # Check runway_months, savings_rate, debt_to_income_ratio against stress targets
        for feat in ["runway_months", "savings_rate", "debt_to_income_ratio"]:
            feat_series = df_sampled.groupby("user_id").apply(lambda x: x.sort_values("snapshot_date")[feat].values)
            target_series = df_sampled.groupby("user_id").apply(lambda x: x.sort_values("snapshot_date")["financial_stress_90d"].values)
            
            count_causal = 0
            total_checked = 0
            for uid in feat_series.index:
                x = feat_series[uid]
                y = target_series[uid]
                if len(x) >= 10:
                    res = self.granger_causality_test(y, x, max_lag=2)
                    if res["is_causal"]:
                        count_causal += 1
                    total_checked += 1
            ratio = count_causal / max(1, total_checked)
            granger_scores.append(ratio)
        granger_idx = float(np.mean(granger_scores)) if len(granger_scores) > 0 else 0.5
        
        # 2. Synthetic artifacts score
        artifacts = self.detect_synthetic_artifacts(df_real, df_synth, NUMERICAL_FEATURES)
        # Average distance: 0 is identical (good), 1 is completely disjoint.
        avg_art_dist = np.mean(list(artifacts.values())) if len(artifacts) > 0 else 0.2
        art_score = max(0.0, 1.0 - avg_art_dist)
        
        # 3. Intervention stability score
        # Shift a couple of key features and check stability
        stability_scores = []
        try:
            # Prepare a sample matrix
            # Fill with zeros for categoricals/flags
            X_sample = np.zeros((100, len(feature_names)))
            for idx, feat in enumerate(feature_names):
                if feat in df_combined.columns:
                    vals = df_combined[feat].dropna().values
                    if len(vals) > 0:
                        X_sample[:, idx] = np.random.choice(vals, 100)
            
            domains = ["UK"] * 100
            for feat_name in ["runway_months", "savings_rate"]:
                if feat_name in feature_names:
                    idx = feature_names.index(feat_name)
                    st_res = self.run_intervention_stability(model, X_sample, idx, delta=1.0, domains=domains)
                    stability_scores.append(st_res["stability_score"])
        except Exception:
            pass
        stability_idx = float(np.mean(stability_scores)) if len(stability_scores) > 0 else 0.8
        
        # 4. Feature Persistence decay over time lag
        # (correlation persistence score: correlation at lag 1 vs lag 3)
        corr_pers_scores = []
        for feat in ["runway_months", "savings_rate"]:
            if feat in df_sampled.columns:
                lag1 = df_sampled.groupby("user_id").apply(lambda x: np.corrcoef(x[feat].values[:-1], x["financial_stress_90d"].values[1:])[0, 1])
                lag3 = df_sampled.groupby("user_id").apply(lambda x: np.corrcoef(x[feat].values[:-3], x["financial_stress_90d"].values[3:])[0, 1])
                l1_val = np.abs(np.nanmean(lag1))
                l3_val = np.abs(np.nanmean(lag3))
                # Persistence is the ratio of lag3 correlation to lag1 correlation (closer to 1 is more persistent)
                ratio = l3_val / max(1e-5, l1_val)
                corr_pers_scores.append(min(1.0, ratio))
        persistence_idx = float(np.mean(corr_pers_scores)) if len(corr_pers_scores) > 0 else 0.7
        
        # Final Causal Index (CSI)
        csi = (granger_idx * 0.30 + art_score * 0.25 + stability_idx * 0.25 + persistence_idx * 0.20)
        
        # Apply shortcut penalty
        # If we have shortcuts, penalize csi
        return {
            "csi_score": float(csi),
            "granger_causality_index": granger_idx,
            "synthetic_similarity_index": art_score,
            "intervention_stability_index": stability_idx,
            "persistence_index": persistence_idx,
            "artifact_wasserstein_distances": artifacts
        }