|
| 1 | +from .sensitivity_indices import sensitivity_indices |
| 2 | +import numpy as np |
| 3 | +import pandas as pd |
| 4 | +import matplotlib.pyplot as plt |
| 5 | + |
| 6 | +__all__ = ["heterogeneity_indices"] |
| 7 | + |
| 8 | + |
| 9 | +def heterogeneity_indices( |
| 10 | + output: pd.Series, |
| 11 | + inputs: pd.DataFrame, |
| 12 | + split_variable: str | pd.Series, |
| 13 | + n_subdivisions: int | None = None, |
| 14 | + plot: bool = False, |
| 15 | +) -> pd.DataFrame: |
| 16 | + """ |
| 17 | + Compute sensitivity-based heterogeneity across subdivisions of a variable. |
| 18 | +
|
| 19 | + Parameters |
| 20 | + ---------- |
| 21 | + output : pd.Series |
| 22 | + Model output vector. |
| 23 | + inputs : pd.DataFrame |
| 24 | + Input/feature matrix. |
| 25 | + split_variable : str or pd.Series |
| 26 | + Variable to split on. If string, must be a column in 'inputs'. |
| 27 | + n_subdivisions : int, optional |
| 28 | + Number of regions for continuous variables. Defaults to 4. |
| 29 | + plot : bool, default False |
| 30 | + If True, displays a stacked bar chart of regional sensitivities. |
| 31 | +
|
| 32 | + Returns |
| 33 | + ---------- |
| 34 | + summary : pd.Dataframe |
| 35 | + A summary of calculated heterogeneity indices. |
| 36 | + """ |
| 37 | + y = pd.Series(output).reset_index(drop=True) |
| 38 | + X = pd.DataFrame(inputs).reset_index(drop=True) |
| 39 | + |
| 40 | + if isinstance(split_variable, str): |
| 41 | + if split_variable not in X.columns: |
| 42 | + raise ValueError(f"'{split_variable}' not found in inputs.") |
| 43 | + z = X[split_variable].reset_index(drop=True) |
| 44 | + split_name = split_variable |
| 45 | + else: |
| 46 | + z = pd.Series(split_variable).reset_index(drop=True) |
| 47 | + split_name = getattr(split_variable, "name", "split_variable") |
| 48 | + |
| 49 | + unique_vals = z.dropna().unique() |
| 50 | + n_unique = len(unique_vals) |
| 51 | + |
| 52 | + # Determine if variable is categorical/binary |
| 53 | + is_categorical = ( |
| 54 | + pd.api.types.is_categorical_dtype(z) |
| 55 | + or pd.api.types.is_object_dtype(z) |
| 56 | + or pd.api.types.is_bool_dtype(z) |
| 57 | + or n_unique <= 2 |
| 58 | + ) |
| 59 | + |
| 60 | + if is_categorical: |
| 61 | + regions = z.astype("category") |
| 62 | + else: |
| 63 | + q = n_subdivisions if n_subdivisions is not None else 4 |
| 64 | + try: |
| 65 | + regions = pd.qcut(z, q=q, duplicates="drop") |
| 66 | + except ValueError as e: |
| 67 | + raise ValueError( |
| 68 | + f"Failed to bin '{split_name}' into {q} quantiles: {e}" |
| 69 | + ) from e |
| 70 | + |
| 71 | + regional_profiles = [] |
| 72 | + skipped = [] |
| 73 | + |
| 74 | + for region in regions.cat.categories: |
| 75 | + mask = regions == region |
| 76 | + n_in_region = mask.sum() |
| 77 | + |
| 78 | + if n_in_region < 10: |
| 79 | + # Need enough samples for meaningful sensitivity indices |
| 80 | + skipped.append((region, n_in_region, "too few samples (< 10)")) |
| 81 | + continue |
| 82 | + |
| 83 | + X_sub = X.loc[mask] |
| 84 | + y_sub = y.loc[mask] |
| 85 | + |
| 86 | + # Skip if output has zero or near-zero variance in this region |
| 87 | + if y_sub.var() < 1e-12: |
| 88 | + skipped.append((region, n_in_region, "output variance ≈ 0")) |
| 89 | + continue |
| 90 | + |
| 91 | + try: |
| 92 | + res = sensitivity_indices(inputs=X_sub, output=y_sub) |
| 93 | + si_vals = np.asarray(res.si).ravel() |
| 94 | + |
| 95 | + # Guard against NaN/Inf from degenerate sensitivity computation |
| 96 | + if not np.all(np.isfinite(si_vals)): |
| 97 | + skipped.append((region, n_in_region, "non-finite SI values")) |
| 98 | + continue |
| 99 | + |
| 100 | + si_region = pd.Series(si_vals, index=X.columns, name=region) |
| 101 | + regional_profiles.append(si_region) |
| 102 | + |
| 103 | + except Exception as e: |
| 104 | + skipped.append((region, n_in_region, f"exception: {e}")) |
| 105 | + continue |
| 106 | + |
| 107 | + if skipped: |
| 108 | + print( |
| 109 | + f"[heterogeneity_indices] Skipped {len(skipped)} region(s) of '{split_name}':" |
| 110 | + ) |
| 111 | + for reg, n, reason in skipped: |
| 112 | + print(f" - region={reg!r}, n={n}, reason={reason}") |
| 113 | + |
| 114 | + if len(regional_profiles) < 2: |
| 115 | + total_regions = len(regions.cat.categories) |
| 116 | + valid = len(regional_profiles) |
| 117 | + raise ValueError( |
| 118 | + f"Not enough valid subdivisions to compute heterogeneity: " |
| 119 | + f"{valid}/{total_regions} regions passed all checks for '{split_name}'.\n" |
| 120 | + f"Skipped regions:\n" |
| 121 | + + "\n".join(f" {r!r}: n={n}, {reason}" for r, n, reason in skipped) |
| 122 | + + "\n\nTry: (1) reducing n_subdivisions, " |
| 123 | + "(2) using a different split_variable, or " |
| 124 | + "(3) ensuring more samples per region." |
| 125 | + ) |
| 126 | + |
| 127 | + regional_si = pd.concat(regional_profiles, axis=1) |
| 128 | + |
| 129 | + res_global = sensitivity_indices(inputs=X, output=y) |
| 130 | + overall_si = pd.Series( |
| 131 | + np.asarray(res_global.si).ravel(), |
| 132 | + index=X.columns, |
| 133 | + name="Overall_SI", |
| 134 | + ) |
| 135 | + |
| 136 | + # Heterogeneity = 2 × population std dev across regions |
| 137 | + hetero_scores = 2 * regional_si.std(axis=1, ddof=0) |
| 138 | + total_hetero = hetero_scores.mean() |
| 139 | + |
| 140 | + hetero_col_name = f"Heterogeneity (across {split_name})" |
| 141 | + summary = pd.DataFrame( |
| 142 | + {"Overall_SI": overall_si, hetero_col_name: hetero_scores} |
| 143 | + ).sort_values(by=hetero_col_name, ascending=False) |
| 144 | + summary.loc["SUM / TOTAL"] = [overall_si.sum(), total_hetero] |
| 145 | + |
| 146 | + if plot: |
| 147 | + plot_order = summary.index[:-1] |
| 148 | + data_to_plot = regional_si.loc[plot_order].T |
| 149 | + |
| 150 | + cmap = plt.get_cmap("terrain") |
| 151 | + colors = [cmap(i) for i in np.linspace(0.05, 0.95, len(plot_order))] |
| 152 | + |
| 153 | + _ = data_to_plot.plot( |
| 154 | + kind="bar", |
| 155 | + stacked=True, |
| 156 | + figsize=(10, 6), |
| 157 | + color=colors, |
| 158 | + edgecolor="white", |
| 159 | + width=0.8, |
| 160 | + ) |
| 161 | + |
| 162 | + plt.title(f"Sensitivity Profiles across {split_name}", fontsize=14) |
| 163 | + plt.ylabel("Variance Contribution", fontsize=12) |
| 164 | + plt.xlabel(f"Regions of {split_name}", fontsize=12) |
| 165 | + plt.legend(title="Input Variables", bbox_to_anchor=(1.05, 1), loc="upper left") |
| 166 | + plt.xticks(rotation=45) |
| 167 | + plt.grid(axis="y", linestyle="--", alpha=0.7) |
| 168 | + plt.tight_layout() |
| 169 | + plt.show() |
| 170 | + |
| 171 | + return summary |
0 commit comments