terraproof 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/bin/terraproof.js +4 -0
  4. package/dist/router/apply.js +147 -0
  5. package/dist/router/classify.js +111 -0
  6. package/dist/router/explain.js +9 -0
  7. package/dist/router/index.js +272 -0
  8. package/dist/router/resolve.js +239 -0
  9. package/dist/router/score.js +60 -0
  10. package/dist/router/types.js +1 -0
  11. package/dist/router/validate.js +81 -0
  12. package/instructions/engineering.md +14 -0
  13. package/instructions/security.md +14 -0
  14. package/instructions/simplicity.md +13 -0
  15. package/package.json +65 -4
  16. package/routing/DOMAIN_ROUTING.md +161 -0
  17. package/routing/ROUTER_DESIGN.md +173 -0
  18. package/routing/SKILL_MANIFEST.md +86 -0
  19. package/routing/checks.json +121 -0
  20. package/routing/collections.json +47 -0
  21. package/routing/registry.json +2211 -0
  22. package/routing/rules.json +64 -0
  23. package/skills/accuracy-assessment/SKILL.md +213 -0
  24. package/skills/accuracy-assessment/UPSTREAM.md +7 -0
  25. package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
  26. package/skills/accuracy-assessment/skill.json +103 -0
  27. package/skills/brainstorming/SKILL.md +250 -0
  28. package/skills/brainstorming/UPSTREAM.md +29 -0
  29. package/skills/brainstorming/scripts/frame-template.html +213 -0
  30. package/skills/brainstorming/scripts/helper.js +167 -0
  31. package/skills/brainstorming/scripts/server.cjs +723 -0
  32. package/skills/brainstorming/scripts/start-server.sh +209 -0
  33. package/skills/brainstorming/scripts/stop-server.sh +120 -0
  34. package/skills/brainstorming/skill.json +73 -0
  35. package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  36. package/skills/brainstorming/visual-companion.md +299 -0
  37. package/skills/crs-and-units/SKILL.md +200 -0
  38. package/skills/crs-and-units/UPSTREAM.md +7 -0
  39. package/skills/crs-and-units/skill.json +74 -0
  40. package/skills/design-postgis-tables/SKILL.md +494 -0
  41. package/skills/design-postgis-tables/UPSTREAM.md +21 -0
  42. package/skills/design-postgis-tables/skill.json +90 -0
  43. package/skills/gdal/SKILL.md +125 -0
  44. package/skills/gdal/UPSTREAM.md +22 -0
  45. package/skills/gdal/references/gdal-recipes.md +103 -0
  46. package/skills/gdal/skill.json +66 -0
  47. package/skills/geomaster/README.md +105 -0
  48. package/skills/geomaster/SKILL.md +366 -0
  49. package/skills/geomaster/UPSTREAM.md +21 -0
  50. package/skills/geomaster/references/advanced-gis.md +376 -0
  51. package/skills/geomaster/references/big-data.md +363 -0
  52. package/skills/geomaster/references/code-examples.md +531 -0
  53. package/skills/geomaster/references/coordinate-systems.md +364 -0
  54. package/skills/geomaster/references/core-libraries.md +273 -0
  55. package/skills/geomaster/references/data-sources.md +330 -0
  56. package/skills/geomaster/references/gis-software.md +369 -0
  57. package/skills/geomaster/references/industry-applications.md +420 -0
  58. package/skills/geomaster/references/machine-learning.md +462 -0
  59. package/skills/geomaster/references/programming-languages.md +456 -0
  60. package/skills/geomaster/references/remote-sensing.md +370 -0
  61. package/skills/geomaster/references/scientific-domains.md +416 -0
  62. package/skills/geomaster/references/specialized-topics.md +428 -0
  63. package/skills/geomaster/references/troubleshooting.md +439 -0
  64. package/skills/geomaster/skill.json +157 -0
  65. package/skills/geopandas/SKILL.md +250 -0
  66. package/skills/geopandas/UPSTREAM.md +22 -0
  67. package/skills/geopandas/references/crs-management.md +231 -0
  68. package/skills/geopandas/references/data-io.md +323 -0
  69. package/skills/geopandas/references/data-structures.md +207 -0
  70. package/skills/geopandas/references/geometric-operations.md +262 -0
  71. package/skills/geopandas/references/spatial-analysis.md +294 -0
  72. package/skills/geopandas/references/visualization.md +230 -0
  73. package/skills/geopandas/scripts/_common.py +605 -0
  74. package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
  75. package/skills/geopandas/scripts/export_plan.py +305 -0
  76. package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
  77. package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
  78. package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
  79. package/skills/geopandas/scripts/vector_inventory.py +140 -0
  80. package/skills/geopandas/skill.json +116 -0
  81. package/skills/geoparquet-validation/SKILL.md +125 -0
  82. package/skills/geoparquet-validation/UPSTREAM.md +24 -0
  83. package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
  84. package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
  85. package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
  86. package/skills/geoparquet-validation/skill.json +71 -0
  87. package/skills/geospatial-data-discovery/SKILL.md +49 -0
  88. package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
  89. package/skills/geospatial-data-discovery/skill.json +51 -0
  90. package/skills/geospatial-frontend/SKILL.md +86 -0
  91. package/skills/geospatial-frontend/UPSTREAM.md +23 -0
  92. package/skills/geospatial-frontend/references/design-system.md +283 -0
  93. package/skills/geospatial-frontend/references/user-preferences.md +96 -0
  94. package/skills/geospatial-frontend/skill.json +87 -0
  95. package/skills/geozarr/SKILL.md +244 -0
  96. package/skills/geozarr/UPSTREAM.md +21 -0
  97. package/skills/geozarr/skill.json +97 -0
  98. package/skills/networkx/SKILL.md +440 -0
  99. package/skills/networkx/UPSTREAM.md +22 -0
  100. package/skills/networkx/references/algorithms.md +384 -0
  101. package/skills/networkx/references/generators.md +385 -0
  102. package/skills/networkx/references/graph-basics.md +284 -0
  103. package/skills/networkx/references/io.md +457 -0
  104. package/skills/networkx/references/visualization.md +531 -0
  105. package/skills/networkx/skill.json +93 -0
  106. package/skills/raster-processing/SKILL.md +222 -0
  107. package/skills/raster-processing/UPSTREAM.md +7 -0
  108. package/skills/raster-processing/skill.json +81 -0
  109. package/skills/sar-basics/SKILL.md +202 -0
  110. package/skills/sar-basics/UPSTREAM.md +7 -0
  111. package/skills/sar-basics/references/calibration-lut.md +98 -0
  112. package/skills/sar-basics/skill.json +97 -0
  113. package/skills/satellite-preprocessing/SKILL.md +241 -0
  114. package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
  115. package/skills/satellite-preprocessing/skill.json +84 -0
  116. package/skills/scientific-visualization/SKILL.md +285 -0
  117. package/skills/scientific-visualization/UPSTREAM.md +25 -0
  118. package/skills/scientific-visualization/assets/color_palettes.py +263 -0
  119. package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
  120. package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
  121. package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
  122. package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
  123. package/skills/scientific-visualization/references/color_palettes.md +227 -0
  124. package/skills/scientific-visualization/references/journal_requirements.md +169 -0
  125. package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
  126. package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
  127. package/skills/scientific-visualization/references/sources.md +76 -0
  128. package/skills/scientific-visualization/scripts/_common.py +136 -0
  129. package/skills/scientific-visualization/scripts/export_plan.py +493 -0
  130. package/skills/scientific-visualization/scripts/figure_export.py +642 -0
  131. package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
  132. package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
  133. package/skills/scientific-visualization/scripts/style_presets.py +501 -0
  134. package/skills/scientific-visualization/scripts/style_preview.py +232 -0
  135. package/skills/scientific-visualization/skill.json +95 -0
  136. package/skills/spectral-indices/SKILL.md +235 -0
  137. package/skills/spectral-indices/UPSTREAM.md +7 -0
  138. package/skills/spectral-indices/skill.json +88 -0
  139. package/skills/stac-and-cloud-access/SKILL.md +209 -0
  140. package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
  141. package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
  142. package/skills/stac-and-cloud-access/skill.json +98 -0
  143. package/skills/statistical-analysis/SKILL.md +446 -0
  144. package/skills/statistical-analysis/UPSTREAM.md +24 -0
  145. package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
  146. package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
  147. package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
  148. package/skills/statistical-analysis/references/reporting_standards.md +482 -0
  149. package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
  150. package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
  151. package/skills/statistical-analysis/skill.json +127 -0
  152. package/skills/systematic-debugging/SKILL.md +283 -0
  153. package/skills/systematic-debugging/UPSTREAM.md +28 -0
  154. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  155. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  156. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  157. package/skills/systematic-debugging/find-polluter.sh +72 -0
  158. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  159. package/skills/systematic-debugging/skill.json +88 -0
  160. package/skills/time-series-and-change/SKILL.md +217 -0
  161. package/skills/time-series-and-change/UPSTREAM.md +7 -0
  162. package/skills/time-series-and-change/references/change-methods.md +42 -0
  163. package/skills/time-series-and-change/skill.json +116 -0
  164. package/skills/vector-quality/SKILL.md +204 -0
  165. package/skills/vector-quality/UPSTREAM.md +7 -0
  166. package/skills/vector-quality/skill.json +82 -0
  167. package/skills/verification/SKILL.md +120 -0
  168. package/skills/verification/UPSTREAM.md +31 -0
  169. package/skills/verification/skill.json +67 -0
  170. package/skills/writing-plans/SKILL.md +171 -0
  171. package/skills/writing-plans/UPSTREAM.md +23 -0
  172. package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  173. package/skills/writing-plans/skill.json +80 -0
  174. package/sources/SOURCES.md +374 -0
  175. package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
  176. package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
  177. package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
  178. package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
  179. package/third_party/superpowers/LICENSE +21 -0
  180. package/third_party/superpowers/NOTICE.md +17 -0
  181. package/third_party/timescale-pg-aiguide/LICENSE +176 -0
  182. package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
@@ -0,0 +1,652 @@
1
+ """
2
+ Comprehensive statistical assumption checking utilities.
3
+
4
+ This module provides functions to check common statistical assumptions:
5
+ - Normality
6
+ - Homogeneity of variance
7
+ - Independence
8
+ - Linearity
9
+ - Outliers
10
+ """
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ from scipy import stats
15
+ import matplotlib.pyplot as plt
16
+ import seaborn as sns
17
+ from typing import Dict, List, Tuple, Optional, Union
18
+
19
+
20
+ def check_normality(
21
+ data: Union[np.ndarray, pd.Series, List],
22
+ name: str = "data",
23
+ alpha: float = 0.05,
24
+ plot: bool = True
25
+ ) -> Dict:
26
+ """
27
+ Check normality assumption using Shapiro-Wilk test and visualizations.
28
+
29
+ Parameters
30
+ ----------
31
+ data : array-like
32
+ Data to check for normality
33
+ name : str
34
+ Name of the variable (for labeling)
35
+ alpha : float
36
+ Significance level for Shapiro-Wilk test
37
+ plot : bool
38
+ Whether to create Q-Q plot and histogram
39
+
40
+ Returns
41
+ -------
42
+ dict
43
+ Results including test statistic, p-value, and interpretation
44
+ """
45
+ data = np.asarray(data)
46
+ data_clean = data[~np.isnan(data)]
47
+
48
+ # Shapiro-Wilk test
49
+ statistic, p_value = stats.shapiro(data_clean)
50
+
51
+ # Interpretation
52
+ is_normal = p_value > alpha
53
+ interpretation = (
54
+ f"Data {'appear' if is_normal else 'do not appear'} normally distributed "
55
+ f"(W = {statistic:.3f}, p = {p_value:.3f})"
56
+ )
57
+
58
+ # Visual checks
59
+ if plot:
60
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
61
+
62
+ # Q-Q plot
63
+ stats.probplot(data_clean, dist="norm", plot=ax1)
64
+ ax1.set_title(f"Q-Q Plot: {name}")
65
+ ax1.grid(alpha=0.3)
66
+
67
+ # Histogram with normal curve
68
+ ax2.hist(data_clean, bins='auto', density=True, alpha=0.7, color='steelblue', edgecolor='black')
69
+ mu, sigma = data_clean.mean(), data_clean.std()
70
+ x = np.linspace(data_clean.min(), data_clean.max(), 100)
71
+ ax2.plot(x, stats.norm.pdf(x, mu, sigma), 'r-', linewidth=2, label='Normal curve')
72
+ ax2.set_xlabel('Value')
73
+ ax2.set_ylabel('Density')
74
+ ax2.set_title(f'Histogram: {name}')
75
+ ax2.legend()
76
+ ax2.grid(alpha=0.3)
77
+
78
+ plt.tight_layout()
79
+ plt.show()
80
+
81
+ return {
82
+ 'test': 'Shapiro-Wilk',
83
+ 'statistic': statistic,
84
+ 'p_value': p_value,
85
+ 'is_normal': is_normal,
86
+ 'interpretation': interpretation,
87
+ 'n': len(data_clean),
88
+ 'recommendation': (
89
+ "Proceed with parametric test" if is_normal
90
+ else "Consider non-parametric alternative or transformation"
91
+ )
92
+ }
93
+
94
+
95
+ def check_normality_per_group(
96
+ data: pd.DataFrame,
97
+ value_col: str,
98
+ group_col: str,
99
+ alpha: float = 0.05,
100
+ plot: bool = True
101
+ ) -> pd.DataFrame:
102
+ """
103
+ Check normality assumption for each group separately.
104
+
105
+ Parameters
106
+ ----------
107
+ data : pd.DataFrame
108
+ Data containing values and group labels
109
+ value_col : str
110
+ Column name for values to check
111
+ group_col : str
112
+ Column name for group labels
113
+ alpha : float
114
+ Significance level
115
+ plot : bool
116
+ Whether to create Q-Q plots for each group
117
+
118
+ Returns
119
+ -------
120
+ pd.DataFrame
121
+ Results for each group
122
+ """
123
+ groups = data[group_col].unique()
124
+ results = []
125
+
126
+ if plot:
127
+ n_groups = len(groups)
128
+ fig, axes = plt.subplots(1, n_groups, figsize=(5 * n_groups, 4))
129
+ if n_groups == 1:
130
+ axes = [axes]
131
+
132
+ for idx, group in enumerate(groups):
133
+ group_data = data[data[group_col] == group][value_col].dropna()
134
+ stat, p = stats.shapiro(group_data)
135
+
136
+ results.append({
137
+ 'Group': group,
138
+ 'N': len(group_data),
139
+ 'W': stat,
140
+ 'p-value': p,
141
+ 'Normal': 'Yes' if p > alpha else 'No'
142
+ })
143
+
144
+ if plot:
145
+ stats.probplot(group_data, dist="norm", plot=axes[idx])
146
+ axes[idx].set_title(f"Q-Q Plot: {group}")
147
+ axes[idx].grid(alpha=0.3)
148
+
149
+ if plot:
150
+ plt.tight_layout()
151
+ plt.show()
152
+
153
+ return pd.DataFrame(results)
154
+
155
+
156
+ def check_homogeneity_of_variance(
157
+ data: pd.DataFrame,
158
+ value_col: str,
159
+ group_col: str,
160
+ alpha: float = 0.05,
161
+ plot: bool = True
162
+ ) -> Dict:
163
+ """
164
+ Check homogeneity of variance using Levene's test.
165
+
166
+ Parameters
167
+ ----------
168
+ data : pd.DataFrame
169
+ Data containing values and group labels
170
+ value_col : str
171
+ Column name for values
172
+ group_col : str
173
+ Column name for group labels
174
+ alpha : float
175
+ Significance level
176
+ plot : bool
177
+ Whether to create box plots
178
+
179
+ Returns
180
+ -------
181
+ dict
182
+ Results including test statistic, p-value, and interpretation
183
+ """
184
+ groups = [group[value_col].values for name, group in data.groupby(group_col)]
185
+
186
+ # Levene's test (robust to non-normality)
187
+ statistic, p_value = stats.levene(*groups)
188
+
189
+ # Variance ratio (max/min)
190
+ variances = [np.var(g, ddof=1) for g in groups]
191
+ var_ratio = max(variances) / min(variances)
192
+
193
+ is_homogeneous = p_value > alpha
194
+ interpretation = (
195
+ f"Variances {'appear' if is_homogeneous else 'do not appear'} homogeneous "
196
+ f"(F = {statistic:.3f}, p = {p_value:.3f}, variance ratio = {var_ratio:.2f})"
197
+ )
198
+
199
+ if plot:
200
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
201
+
202
+ # Box plot
203
+ data.boxplot(column=value_col, by=group_col, ax=ax1)
204
+ ax1.set_title('Box Plots by Group')
205
+ ax1.set_xlabel(group_col)
206
+ ax1.set_ylabel(value_col)
207
+ plt.sca(ax1)
208
+ plt.xticks(rotation=45)
209
+
210
+ # Variance plot
211
+ group_names = data[group_col].unique()
212
+ ax2.bar(range(len(variances)), variances, color='steelblue', edgecolor='black')
213
+ ax2.set_xticks(range(len(variances)))
214
+ ax2.set_xticklabels(group_names, rotation=45)
215
+ ax2.set_ylabel('Variance')
216
+ ax2.set_title('Variance by Group')
217
+ ax2.grid(alpha=0.3, axis='y')
218
+
219
+ plt.tight_layout()
220
+ plt.show()
221
+
222
+ return {
223
+ 'test': 'Levene',
224
+ 'statistic': statistic,
225
+ 'p_value': p_value,
226
+ 'is_homogeneous': is_homogeneous,
227
+ 'variance_ratio': var_ratio,
228
+ 'interpretation': interpretation,
229
+ 'recommendation': (
230
+ "Proceed with standard test" if is_homogeneous
231
+ else "Consider Welch's correction or transformation"
232
+ )
233
+ }
234
+
235
+
236
+ def check_linearity(
237
+ x: Union[np.ndarray, pd.Series],
238
+ y: Union[np.ndarray, pd.Series],
239
+ x_name: str = "X",
240
+ y_name: str = "Y"
241
+ ) -> Dict:
242
+ """
243
+ Check linearity assumption for regression.
244
+
245
+ Parameters
246
+ ----------
247
+ x : array-like
248
+ Predictor variable
249
+ y : array-like
250
+ Outcome variable
251
+ x_name : str
252
+ Name of predictor
253
+ y_name : str
254
+ Name of outcome
255
+
256
+ Returns
257
+ -------
258
+ dict
259
+ Visualization and recommendations
260
+ """
261
+ x = np.asarray(x)
262
+ y = np.asarray(y)
263
+
264
+ # Fit linear regression
265
+ slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
266
+ y_pred = intercept + slope * x
267
+
268
+ # Calculate residuals
269
+ residuals = y - y_pred
270
+
271
+ # Visualization
272
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
273
+
274
+ # Scatter plot with regression line
275
+ ax1.scatter(x, y, alpha=0.6, s=50, edgecolors='black', linewidths=0.5)
276
+ ax1.plot(x, y_pred, 'r-', linewidth=2, label=f'y = {intercept:.2f} + {slope:.2f}x')
277
+ ax1.set_xlabel(x_name)
278
+ ax1.set_ylabel(y_name)
279
+ ax1.set_title('Scatter Plot with Regression Line')
280
+ ax1.legend()
281
+ ax1.grid(alpha=0.3)
282
+
283
+ # Residuals vs fitted
284
+ ax2.scatter(y_pred, residuals, alpha=0.6, s=50, edgecolors='black', linewidths=0.5)
285
+ ax2.axhline(y=0, color='r', linestyle='--', linewidth=2)
286
+ ax2.set_xlabel('Fitted values')
287
+ ax2.set_ylabel('Residuals')
288
+ ax2.set_title('Residuals vs Fitted Values')
289
+ ax2.grid(alpha=0.3)
290
+
291
+ plt.tight_layout()
292
+ plt.show()
293
+
294
+ return {
295
+ 'r': r_value,
296
+ 'r_squared': r_value ** 2,
297
+ 'interpretation': (
298
+ "Examine residual plot. Points should be randomly scattered around zero. "
299
+ "Patterns (curves, funnels) suggest non-linearity or heteroscedasticity."
300
+ ),
301
+ 'recommendation': (
302
+ "If non-linear pattern detected: Consider polynomial terms, "
303
+ "transformations, or non-linear models"
304
+ )
305
+ }
306
+
307
+
308
+ def detect_outliers(
309
+ data: Union[np.ndarray, pd.Series, List],
310
+ name: str = "data",
311
+ method: str = "iqr",
312
+ threshold: float = 1.5,
313
+ plot: bool = True
314
+ ) -> Dict:
315
+ """
316
+ Detect outliers using IQR method or z-score method.
317
+
318
+ Parameters
319
+ ----------
320
+ data : array-like
321
+ Data to check for outliers
322
+ name : str
323
+ Name of variable
324
+ method : str
325
+ Method to use: 'iqr' or 'zscore'
326
+ threshold : float
327
+ Threshold for outlier detection
328
+ For IQR: typically 1.5 (mild) or 3 (extreme)
329
+ For z-score: typically 3
330
+ plot : bool
331
+ Whether to create visualizations
332
+
333
+ Returns
334
+ -------
335
+ dict
336
+ Outlier indices, values, and visualizations
337
+ """
338
+ data = np.asarray(data)
339
+ data_clean = data[~np.isnan(data)]
340
+
341
+ if method == "iqr":
342
+ q1 = np.percentile(data_clean, 25)
343
+ q3 = np.percentile(data_clean, 75)
344
+ iqr = q3 - q1
345
+ lower_bound = q1 - threshold * iqr
346
+ upper_bound = q3 + threshold * iqr
347
+ outlier_mask = (data_clean < lower_bound) | (data_clean > upper_bound)
348
+
349
+ elif method == "zscore":
350
+ z_scores = np.abs(stats.zscore(data_clean))
351
+ outlier_mask = z_scores > threshold
352
+ lower_bound = data_clean.mean() - threshold * data_clean.std()
353
+ upper_bound = data_clean.mean() + threshold * data_clean.std()
354
+
355
+ else:
356
+ raise ValueError("method must be 'iqr' or 'zscore'")
357
+
358
+ outlier_indices = np.where(outlier_mask)[0]
359
+ outlier_values = data_clean[outlier_mask]
360
+ n_outliers = len(outlier_indices)
361
+ pct_outliers = (n_outliers / len(data_clean)) * 100
362
+
363
+ if plot:
364
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
365
+
366
+ # Box plot
367
+ bp = ax1.boxplot(data_clean, vert=True, patch_artist=True)
368
+ bp['boxes'][0].set_facecolor('steelblue')
369
+ ax1.set_ylabel('Value')
370
+ ax1.set_title(f'Box Plot: {name}')
371
+ ax1.grid(alpha=0.3, axis='y')
372
+
373
+ # Scatter plot highlighting outliers
374
+ x_coords = np.arange(len(data_clean))
375
+ ax2.scatter(x_coords[~outlier_mask], data_clean[~outlier_mask],
376
+ alpha=0.6, s=50, color='steelblue', label='Normal', edgecolors='black', linewidths=0.5)
377
+ if n_outliers > 0:
378
+ ax2.scatter(x_coords[outlier_mask], data_clean[outlier_mask],
379
+ alpha=0.8, s=100, color='red', label='Outliers', marker='D', edgecolors='black', linewidths=0.5)
380
+ ax2.axhline(y=lower_bound, color='orange', linestyle='--', linewidth=1.5, label='Bounds')
381
+ ax2.axhline(y=upper_bound, color='orange', linestyle='--', linewidth=1.5)
382
+ ax2.set_xlabel('Index')
383
+ ax2.set_ylabel('Value')
384
+ ax2.set_title(f'Outlier Detection: {name}')
385
+ ax2.legend()
386
+ ax2.grid(alpha=0.3)
387
+
388
+ plt.tight_layout()
389
+ plt.show()
390
+
391
+ return {
392
+ 'method': method,
393
+ 'threshold': threshold,
394
+ 'n_outliers': n_outliers,
395
+ 'pct_outliers': pct_outliers,
396
+ 'outlier_indices': outlier_indices,
397
+ 'outlier_values': outlier_values,
398
+ 'lower_bound': lower_bound,
399
+ 'upper_bound': upper_bound,
400
+ 'interpretation': f"Found {n_outliers} outliers ({pct_outliers:.1f}% of data)",
401
+ 'recommendation': (
402
+ "Investigate outliers for data entry errors. "
403
+ "Consider: (1) removing if errors, (2) winsorizing, "
404
+ "(3) keeping if legitimate, (4) using robust methods"
405
+ )
406
+ }
407
+
408
+
409
+ def check_regression_diagnostics(
410
+ model,
411
+ alpha: float = 0.05,
412
+ plot: bool = True
413
+ ) -> Dict:
414
+ """
415
+ Run standard diagnostics on a fitted statsmodels OLS model.
416
+
417
+ Produces the classic 4-panel diagnostic plot (residuals vs fitted,
418
+ Q-Q, scale-location, residual histogram) plus formal tests:
419
+ normality of residuals (Shapiro-Wilk), heteroscedasticity
420
+ (Breusch-Pagan), autocorrelation (Durbin-Watson), and
421
+ multicollinearity (VIF per predictor).
422
+
423
+ Parameters
424
+ ----------
425
+ model : statsmodels regression results
426
+ A fitted model from ``sm.OLS(y, X).fit()`` where X includes
427
+ a constant (``sm.add_constant``).
428
+ alpha : float
429
+ Significance level for the formal tests.
430
+ plot : bool
431
+ Whether to create the 4-panel diagnostic figure.
432
+
433
+ Returns
434
+ -------
435
+ dict
436
+ Test results, VIF table, and per-assumption interpretations.
437
+ """
438
+ from statsmodels.stats.diagnostic import het_breuschpagan
439
+ from statsmodels.stats.stattools import durbin_watson
440
+ from statsmodels.stats.outliers_influence import variance_inflation_factor
441
+
442
+ residuals = np.asarray(model.resid)
443
+ fitted = np.asarray(model.fittedvalues)
444
+ exog = model.model.exog
445
+ exog_names = list(model.model.exog_names)
446
+
447
+ # Normality of residuals
448
+ sw_stat, sw_p = stats.shapiro(residuals)
449
+
450
+ # Heteroscedasticity (Breusch-Pagan)
451
+ bp_lm, bp_p, _, _ = het_breuschpagan(residuals, exog)
452
+
453
+ # Autocorrelation (Durbin-Watson: ~2 = none, <1.5 or >2.5 = concern)
454
+ dw = durbin_watson(residuals)
455
+
456
+ # Multicollinearity (VIF, skipping the constant)
457
+ vif_rows = []
458
+ for i, name in enumerate(exog_names):
459
+ if name.lower() in ("const", "intercept"):
460
+ continue
461
+ vif_rows.append({'Variable': name,
462
+ 'VIF': variance_inflation_factor(exog, i)})
463
+ vif_table = pd.DataFrame(vif_rows)
464
+ max_vif = vif_table['VIF'].max() if not vif_table.empty else np.nan
465
+
466
+ if plot:
467
+ fig, axes = plt.subplots(2, 2, figsize=(12, 10))
468
+
469
+ axes[0, 0].scatter(fitted, residuals, alpha=0.6, edgecolors='black', linewidths=0.5)
470
+ axes[0, 0].axhline(y=0, color='r', linestyle='--')
471
+ axes[0, 0].set_xlabel('Fitted values')
472
+ axes[0, 0].set_ylabel('Residuals')
473
+ axes[0, 0].set_title('Residuals vs Fitted')
474
+ axes[0, 0].grid(alpha=0.3)
475
+
476
+ stats.probplot(residuals, dist="norm", plot=axes[0, 1])
477
+ axes[0, 1].set_title('Normal Q-Q')
478
+ axes[0, 1].grid(alpha=0.3)
479
+
480
+ std_resid = residuals / residuals.std()
481
+ axes[1, 0].scatter(fitted, np.sqrt(np.abs(std_resid)), alpha=0.6,
482
+ edgecolors='black', linewidths=0.5)
483
+ axes[1, 0].set_xlabel('Fitted values')
484
+ axes[1, 0].set_ylabel('√|Standardized residuals|')
485
+ axes[1, 0].set_title('Scale-Location')
486
+ axes[1, 0].grid(alpha=0.3)
487
+
488
+ axes[1, 1].hist(residuals, bins='auto', edgecolor='black', alpha=0.7)
489
+ axes[1, 1].set_xlabel('Residuals')
490
+ axes[1, 1].set_ylabel('Frequency')
491
+ axes[1, 1].set_title('Histogram of Residuals')
492
+ axes[1, 1].grid(alpha=0.3, axis='y')
493
+
494
+ plt.tight_layout()
495
+ plt.show()
496
+
497
+ issues = []
498
+ if sw_p <= alpha:
499
+ issues.append("non-normal residuals (consider transformation or robust/bootstrap inference)")
500
+ if bp_p <= alpha:
501
+ issues.append("heteroscedasticity (consider robust SEs, e.g. model.get_robustcov_results('HC3'), or WLS)")
502
+ if dw < 1.5 or dw > 2.5:
503
+ issues.append("possible autocorrelation (if data are ordered/temporal, use time-series methods or cluster-robust SEs)")
504
+ if not np.isnan(max_vif) and max_vif > 5:
505
+ issues.append("multicollinearity (VIF > 5; consider dropping/combining predictors)")
506
+
507
+ return {
508
+ 'residual_normality': {'test': 'Shapiro-Wilk', 'statistic': sw_stat,
509
+ 'p_value': sw_p, 'ok': sw_p > alpha},
510
+ 'heteroscedasticity': {'test': 'Breusch-Pagan', 'statistic': bp_lm,
511
+ 'p_value': bp_p, 'ok': bp_p > alpha},
512
+ 'autocorrelation': {'test': 'Durbin-Watson', 'statistic': dw,
513
+ 'ok': 1.5 <= dw <= 2.5},
514
+ 'vif': vif_table,
515
+ 'max_vif': max_vif,
516
+ 'issues': issues,
517
+ 'interpretation': ("No assumption concerns detected." if not issues
518
+ else "Concerns: " + "; ".join(issues))
519
+ }
520
+
521
+
522
+ def comprehensive_assumption_check(
523
+ data: pd.DataFrame,
524
+ value_col: str,
525
+ group_col: Optional[str] = None,
526
+ alpha: float = 0.05
527
+ ) -> Dict:
528
+ """
529
+ Perform comprehensive assumption checking for common statistical tests.
530
+
531
+ Parameters
532
+ ----------
533
+ data : pd.DataFrame
534
+ Data to check
535
+ value_col : str
536
+ Column name for dependent variable
537
+ group_col : str, optional
538
+ Column name for grouping variable (if applicable)
539
+ alpha : float
540
+ Significance level
541
+
542
+ Returns
543
+ -------
544
+ dict
545
+ Summary of all assumption checks
546
+ """
547
+ print("=" * 70)
548
+ print("COMPREHENSIVE ASSUMPTION CHECK")
549
+ print("=" * 70)
550
+
551
+ results = {}
552
+
553
+ # Outlier detection
554
+ print("\n1. OUTLIER DETECTION")
555
+ print("-" * 70)
556
+ outlier_results = detect_outliers(
557
+ data[value_col].dropna(),
558
+ name=value_col,
559
+ method='iqr',
560
+ plot=True
561
+ )
562
+ results['outliers'] = outlier_results
563
+ print(f" {outlier_results['interpretation']}")
564
+ print(f" {outlier_results['recommendation']}")
565
+
566
+ # Check if grouped data
567
+ if group_col is not None:
568
+ # Normality per group
569
+ print(f"\n2. NORMALITY CHECK (by {group_col})")
570
+ print("-" * 70)
571
+ normality_results = check_normality_per_group(
572
+ data, value_col, group_col, alpha=alpha, plot=True
573
+ )
574
+ results['normality_per_group'] = normality_results
575
+ print(normality_results.to_string(index=False))
576
+
577
+ all_normal = normality_results['Normal'].eq('Yes').all()
578
+ print(f"\n All groups normal: {'Yes' if all_normal else 'No'}")
579
+ if not all_normal:
580
+ print(" → Consider non-parametric alternative (Mann-Whitney, Kruskal-Wallis)")
581
+
582
+ # Homogeneity of variance
583
+ print(f"\n3. HOMOGENEITY OF VARIANCE")
584
+ print("-" * 70)
585
+ homogeneity_results = check_homogeneity_of_variance(
586
+ data, value_col, group_col, alpha=alpha, plot=True
587
+ )
588
+ results['homogeneity'] = homogeneity_results
589
+ print(f" {homogeneity_results['interpretation']}")
590
+ print(f" {homogeneity_results['recommendation']}")
591
+
592
+ else:
593
+ # Overall normality
594
+ print(f"\n2. NORMALITY CHECK")
595
+ print("-" * 70)
596
+ normality_results = check_normality(
597
+ data[value_col].dropna(),
598
+ name=value_col,
599
+ alpha=alpha,
600
+ plot=True
601
+ )
602
+ results['normality'] = normality_results
603
+ print(f" {normality_results['interpretation']}")
604
+ print(f" {normality_results['recommendation']}")
605
+
606
+ # Summary
607
+ print("\n" + "=" * 70)
608
+ print("SUMMARY")
609
+ print("=" * 70)
610
+
611
+ if group_col is not None:
612
+ all_normal = results.get('normality_per_group', pd.DataFrame()).get('Normal', pd.Series()).eq('Yes').all()
613
+ is_homogeneous = results.get('homogeneity', {}).get('is_homogeneous', False)
614
+
615
+ if all_normal and is_homogeneous:
616
+ print("✓ All assumptions met. Proceed with parametric test (t-test, ANOVA).")
617
+ elif not all_normal:
618
+ print("✗ Normality violated. Use non-parametric alternative.")
619
+ elif not is_homogeneous:
620
+ print("✗ Homogeneity violated. Use Welch's correction or transformation.")
621
+ else:
622
+ is_normal = results.get('normality', {}).get('is_normal', False)
623
+ if is_normal:
624
+ print("✓ Normality assumption met.")
625
+ else:
626
+ print("✗ Normality violated. Consider transformation or non-parametric method.")
627
+
628
+ print("=" * 70)
629
+
630
+ return results
631
+
632
+
633
+ if __name__ == "__main__":
634
+ # Example usage
635
+ np.random.seed(42)
636
+
637
+ # Simulate data
638
+ group_a = np.random.normal(75, 8, 50)
639
+ group_b = np.random.normal(68, 10, 50)
640
+
641
+ df = pd.DataFrame({
642
+ 'score': np.concatenate([group_a, group_b]),
643
+ 'group': ['A'] * 50 + ['B'] * 50
644
+ })
645
+
646
+ # Run comprehensive check
647
+ results = comprehensive_assumption_check(
648
+ df,
649
+ value_col='score',
650
+ group_col='group',
651
+ alpha=0.05
652
+ )