statstudio 0.1.0__py3-none-any.whl

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 (110) hide show
  1. statstudio/__init__.py +9 -0
  2. statstudio/__main__.py +3 -0
  3. statstudio/app.py +83 -0
  4. statstudio/cli.py +116 -0
  5. statstudio/core/__init__.py +3 -0
  6. statstudio/core/archive.py +27 -0
  7. statstudio/core/commands.py +67 -0
  8. statstudio/core/formula_catalog.py +74 -0
  9. statstudio/core/formulas.py +605 -0
  10. statstudio/core/joins.py +123 -0
  11. statstudio/core/project.py +358 -0
  12. statstudio/core/runtime.py +321 -0
  13. statstudio/core/scripting.py +594 -0
  14. statstudio/core/table.py +796 -0
  15. statstudio/core/transform.py +450 -0
  16. statstudio/feature_help.py +595 -0
  17. statstudio/io/__init__.py +3 -0
  18. statstudio/io/docx.py +201 -0
  19. statstudio/io/export.py +99 -0
  20. statstudio/io/file_import.py +199 -0
  21. statstudio/io/odbc.py +334 -0
  22. statstudio/io/sample_data.py +164 -0
  23. statstudio/io/table_io.py +118 -0
  24. statstudio/plots/__init__.py +19 -0
  25. statstudio/plots/advanced.py +651 -0
  26. statstudio/plots/basic.py +957 -0
  27. statstudio/plots/bayesian_plots.py +94 -0
  28. statstudio/plots/common.py +334 -0
  29. statstudio/plots/diagnostics.py +214 -0
  30. statstudio/plots/doe_plots.py +235 -0
  31. statstudio/plots/plotly_builders.py +719 -0
  32. statstudio/plots/predictive_plots.py +72 -0
  33. statstudio/plots/registry.py +251 -0
  34. statstudio/plugins.py +111 -0
  35. statstudio/resources/help_topics.json +13195 -0
  36. statstudio/resources/logo.ico +0 -0
  37. statstudio/resources/logo.png +0 -0
  38. statstudio/resources/statstudio.svg +8 -0
  39. statstudio/stats/__init__.py +42 -0
  40. statstudio/stats/bayesian.py +1094 -0
  41. statstudio/stats/bayesian_optimization.py +590 -0
  42. statstudio/stats/common.py +140 -0
  43. statstudio/stats/correlation.py +135 -0
  44. statstudio/stats/custom_doe.py +1714 -0
  45. statstudio/stats/descriptive.py +200 -0
  46. statstudio/stats/desirability.py +132 -0
  47. statstudio/stats/distributions.py +331 -0
  48. statstudio/stats/doe.py +1070 -0
  49. statstudio/stats/hypothesis.py +1305 -0
  50. statstudio/stats/multivariate.py +307 -0
  51. statstudio/stats/optimal_doe.py +264 -0
  52. statstudio/stats/power.py +194 -0
  53. statstudio/stats/predictive.py +605 -0
  54. statstudio/stats/profiler.py +379 -0
  55. statstudio/stats/quality.py +1218 -0
  56. statstudio/stats/regression.py +1600 -0
  57. statstudio/stats/results.py +235 -0
  58. statstudio/stats/simulator.py +95 -0
  59. statstudio/stats/survival.py +637 -0
  60. statstudio/stats/timeseries.py +643 -0
  61. statstudio/stats/tolerance.py +154 -0
  62. statstudio/ui/__init__.py +0 -0
  63. statstudio/ui/analysis_hub.py +271 -0
  64. statstudio/ui/command_catalog.py +460 -0
  65. statstudio/ui/command_palette.py +55 -0
  66. statstudio/ui/console.py +239 -0
  67. statstudio/ui/dialogs/__init__.py +0 -0
  68. statstudio/ui/dialogs/advanced_dialogs.py +392 -0
  69. statstudio/ui/dialogs/base.py +537 -0
  70. statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
  71. statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
  72. statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
  73. statstudio/ui/dialogs/doe_dialogs.py +220 -0
  74. statstudio/ui/dialogs/extended_dialogs.py +665 -0
  75. statstudio/ui/dialogs/graph_builder.py +139 -0
  76. statstudio/ui/dialogs/help_dialog.py +207 -0
  77. statstudio/ui/dialogs/help_topics.py +280 -0
  78. statstudio/ui/dialogs/lazy.py +184 -0
  79. statstudio/ui/dialogs/odbc_dialog.py +311 -0
  80. statstudio/ui/dialogs/plot_dialog.py +1385 -0
  81. statstudio/ui/dialogs/report_composer.py +218 -0
  82. statstudio/ui/dialogs/script_dialogs.py +267 -0
  83. statstudio/ui/dialogs/stats_dialogs.py +1688 -0
  84. statstudio/ui/dialogs/table_dialogs.py +997 -0
  85. statstudio/ui/dialogs/window.py +58 -0
  86. statstudio/ui/docks/__init__.py +0 -0
  87. statstudio/ui/formula_editor.py +121 -0
  88. statstudio/ui/icons.py +257 -0
  89. statstudio/ui/jobs.py +179 -0
  90. statstudio/ui/main_window.py +3934 -0
  91. statstudio/ui/plot_interaction.py +178 -0
  92. statstudio/ui/profiler_widget.py +437 -0
  93. statstudio/ui/recent.py +82 -0
  94. statstudio/ui/reports/__init__.py +0 -0
  95. statstudio/ui/reports/report_view.py +1632 -0
  96. statstudio/ui/script_jobs.py +35 -0
  97. statstudio/ui/scripts_panel.py +271 -0
  98. statstudio/ui/table_document.py +233 -0
  99. statstudio/ui/table_model.py +285 -0
  100. statstudio/ui/table_view.py +285 -0
  101. statstudio/ui/theme.py +645 -0
  102. statstudio/ui/welcome.py +453 -0
  103. statstudio/ui/window_controls.py +53 -0
  104. statstudio/ui/workers.py +53 -0
  105. statstudio-0.1.0.dist-info/METADATA +261 -0
  106. statstudio-0.1.0.dist-info/RECORD +110 -0
  107. statstudio-0.1.0.dist-info/WHEEL +5 -0
  108. statstudio-0.1.0.dist-info/entry_points.txt +5 -0
  109. statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
  110. statstudio-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1305 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Any, Sequence
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ import statsmodels.api as sm
9
+ import statsmodels.formula.api as smf
10
+ from scipy import stats
11
+ from statsmodels.stats.proportion import proportions_ztest
12
+
13
+ from statstudio.stats.common import display_formula, p_stars
14
+ from statstudio.stats.results import AnalysisResult
15
+
16
+
17
+ def _q(name: str) -> str:
18
+ return f'Q("{name}")'
19
+
20
+
21
+ def _clean_two_groups(df: pd.DataFrame, value: str, group: str) -> tuple[pd.DataFrame, list[Any]]:
22
+ if value not in df.columns or group not in df.columns:
23
+ raise KeyError("Value or group column not found.")
24
+ frame = df[[value, group]].copy()
25
+ frame[value] = pd.to_numeric(frame[value], errors="coerce")
26
+ frame = frame.dropna()
27
+ levels = list(pd.unique(frame[group]))
28
+ if len(levels) < 2:
29
+ raise ValueError("The group column must contain at least two levels.")
30
+ if len(levels) > 2:
31
+ raise ValueError(f"Exactly two group levels are required; found {len(levels)}.")
32
+ return frame, levels
33
+
34
+
35
+ def one_sample_t_test(df: pd.DataFrame, column: str, mu: float = 0.0, alternative: str = "two-sided") -> AnalysisResult:
36
+ values = pd.to_numeric(df[column], errors="coerce").dropna()
37
+ if len(values) < 2:
38
+ raise ValueError("At least two observations are required.")
39
+ statistic, pvalue = stats.ttest_1samp(values, mu, alternative=alternative)
40
+ n = len(values)
41
+ mean = float(values.mean())
42
+ std = float(values.std(ddof=1))
43
+ se = std / math.sqrt(n)
44
+ diff = mean - mu
45
+ result = AnalysisResult(
46
+ title=f"One-Sample t Test: {column}",
47
+ analysis_type="t_test_one",
48
+ params={"column": column, "mu": mu, "alternative": alternative},
49
+ )
50
+ result.add_table(
51
+ "Test",
52
+ pd.DataFrame(
53
+ [
54
+ {
55
+ "Hypothesized Mean": mu,
56
+ "Sample Mean": mean,
57
+ "N": n,
58
+ "Std Dev": std,
59
+ "Std Error": se,
60
+ "Difference": diff,
61
+ "t": statistic,
62
+ "df": n - 1,
63
+ "p-value": pvalue,
64
+ "Significance": p_stars(pvalue),
65
+ }
66
+ ]
67
+ ),
68
+ )
69
+ result.add_table(
70
+ "Descriptive",
71
+ pd.DataFrame(
72
+ [
73
+ {
74
+ "N": n,
75
+ "Mean": mean,
76
+ "Std Dev": std,
77
+ "Min": float(values.min()),
78
+ "Median": float(values.median()),
79
+ "Max": float(values.max()),
80
+ }
81
+ ]
82
+ ),
83
+ )
84
+ result.add_plot("histogram", {"column": column}, title=f"Distribution of {column}", data=df)
85
+ result.summary = (
86
+ f"Mean {mean:.4g} versus hypothesized {mu:.4g}; difference {diff:.4g}, "
87
+ f"p = {pvalue:.4g}. {_interpret_p(pvalue)}"
88
+ )
89
+ return result
90
+
91
+
92
+ def two_sample_t_test(
93
+ df: pd.DataFrame,
94
+ value: str,
95
+ group: str,
96
+ equal_var: bool = False,
97
+ alternative: str = "two-sided",
98
+ ) -> AnalysisResult:
99
+ frame, levels = _clean_two_groups(df, value, group)
100
+ first = frame.loc[frame[group] == levels[0], value]
101
+ second = frame.loc[frame[group] == levels[1], value]
102
+ if len(first) < 2 or len(second) < 2:
103
+ raise ValueError("Each group requires at least two observations.")
104
+ statistic, pvalue = stats.ttest_ind(first, second, equal_var=equal_var, alternative=alternative)
105
+ mean1, mean2 = float(first.mean()), float(second.mean())
106
+ var1, var2 = float(first.var(ddof=1)), float(second.var(ddof=1))
107
+ n1, n2 = len(first), len(second)
108
+ if equal_var:
109
+ pooled = ((n1 - 1) * var1 + (n2 - 1) * var2) / (n1 + n2 - 2)
110
+ se = math.sqrt(pooled * (1 / n1 + 1 / n2))
111
+ else:
112
+ se = math.sqrt(var1 / n1 + var2 / n2)
113
+ diff = mean1 - mean2
114
+ df_value = n1 + n2 - 2 if equal_var else (var1 / n1 + var2 / n2) ** 2 / (
115
+ (var1 / n1) ** 2 / (n1 - 1) + (var2 / n2) ** 2 / (n2 - 1)
116
+ )
117
+ pooled_std = math.sqrt(((n1 - 1) * var1 + (n2 - 1) * var2) / max(1, n1 + n2 - 2))
118
+ cohen_d = diff / pooled_std if pooled_std else np.nan
119
+ table = pd.DataFrame(
120
+ [
121
+ {
122
+ "Group 1": str(levels[0]),
123
+ "N 1": n1,
124
+ "Mean 1": mean1,
125
+ "Std Dev 1": math.sqrt(var1),
126
+ "Group 2": str(levels[1]),
127
+ "N 2": n2,
128
+ "Mean 2": mean2,
129
+ "Std Dev 2": math.sqrt(var2),
130
+ "Difference": diff,
131
+ "Std Error": se,
132
+ "t": statistic,
133
+ "df": df_value,
134
+ "p-value": pvalue,
135
+ "Cohen's d": cohen_d,
136
+ "Significance": p_stars(pvalue),
137
+ }
138
+ ]
139
+ )
140
+ result = AnalysisResult(
141
+ title=f"Two-Sample t Test: {value} by {group}",
142
+ analysis_type="t_test_two",
143
+ params={"value": value, "group": group, "equal_var": equal_var, "alternative": alternative},
144
+ )
145
+ result.add_table("Test", table)
146
+ group_summary = (
147
+ frame.groupby(group)[value]
148
+ .agg(["count", "mean", "std", "min", "median", "max"])
149
+ .reset_index()
150
+ )
151
+ group_summary.columns = [group, "N", "Mean", "Std Dev", "Min", "Median", "Max"]
152
+ result.add_table("Group Summary", group_summary)
153
+ result.add_plot("box", {"column": value, "group": group}, title=f"{value} by {group}", data=df)
154
+ result.summary = (
155
+ f"{levels[0]} mean {mean1:.4g}, {levels[1]} mean {mean2:.4g}; "
156
+ f"difference {diff:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
157
+ )
158
+ return result
159
+
160
+
161
+ def paired_t_test(df: pd.DataFrame, column1: str, column2: str, alternative: str = "two-sided") -> AnalysisResult:
162
+ frame = df[[column1, column2]].apply(pd.to_numeric, errors="coerce").dropna()
163
+ if len(frame) < 2:
164
+ raise ValueError("At least two complete pairs are required.")
165
+ statistic, pvalue = stats.ttest_rel(frame[column1], frame[column2], alternative=alternative)
166
+ n_pairs = len(frame)
167
+ diff = frame[column1] - frame[column2]
168
+ result = AnalysisResult(
169
+ title=f"Paired t Test: {column1} vs {column2}",
170
+ analysis_type="t_test_paired",
171
+ params={"column1": column1, "column2": column2, "alternative": alternative},
172
+ )
173
+ result.add_table(
174
+ "Test",
175
+ pd.DataFrame(
176
+ [
177
+ {
178
+ "N Pairs": n_pairs,
179
+ "Mean Difference": float(diff.mean()),
180
+ "Std Dev Difference": float(diff.std(ddof=1)),
181
+ "Std Error": float(diff.std(ddof=1) / math.sqrt(len(diff))),
182
+ "t": statistic,
183
+ "df": len(frame) - 1,
184
+ "p-value": pvalue,
185
+ "Significance": p_stars(pvalue),
186
+ }
187
+ ]
188
+ ),
189
+ )
190
+ result.add_plot(
191
+ "scatter",
192
+ {"x": column1, "y": column2, "identity": True},
193
+ title=f"{column1} vs {column2}",
194
+ data=df,
195
+ )
196
+ result.summary = f"Mean paired difference {diff.mean():.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
197
+ return result
198
+
199
+
200
+ def anova_oneway(
201
+ df: pd.DataFrame,
202
+ response: str,
203
+ factor: str,
204
+ *,
205
+ tukey_letters: bool = True,
206
+ alpha: float = 0.05,
207
+ ) -> AnalysisResult:
208
+ frame = df[[response, factor]].copy()
209
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
210
+ frame = frame.dropna()
211
+ if frame[factor].nunique() < 2:
212
+ raise ValueError("The factor must contain at least two levels.")
213
+ groups = [chunk[response].to_numpy() for _, chunk in frame.groupby(factor)]
214
+ statistic, pvalue = stats.f_oneway(*groups)
215
+ model = smf.ols(f"{_q(response)} ~ C({_q(factor)})", data=frame).fit()
216
+ anova = sm.stats.anova_lm(model, typ=2).reset_index().rename(columns={"index": "Source"})
217
+ anova["Source"] = anova["Source"].map(display_formula)
218
+ means = (
219
+ frame.groupby(factor)[response]
220
+ .agg(["count", "mean", "std", "min", "median", "max"])
221
+ .reset_index()
222
+ )
223
+ means.columns = [factor, "N", "Mean", "Std Dev", "Min", "Median", "Max"]
224
+ result = AnalysisResult(
225
+ title=f"One-Way ANOVA: {response} by {factor}",
226
+ analysis_type="anova",
227
+ params={
228
+ "response": response,
229
+ "factor": factor,
230
+ "tukey_letters": bool(tukey_letters),
231
+ "alpha": alpha,
232
+ },
233
+ )
234
+ result.add_table(
235
+ "ANOVA",
236
+ pd.DataFrame(
237
+ [
238
+ {
239
+ "F": statistic,
240
+ "p-value": pvalue,
241
+ "df Between": len(groups) - 1,
242
+ "df Within": len(frame) - len(groups),
243
+ "Significance": p_stars(pvalue),
244
+ }
245
+ ]
246
+ ),
247
+ )
248
+ result.add_table("ANOVA Table", anova)
249
+ result.add_plot("box", {"column": response, "group": factor}, title=f"{response} by {factor}", data=df)
250
+ result.summary = f"F = {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
251
+ if tukey_letters:
252
+ try:
253
+ rows = _tukey_rows(frame, response, factor, alpha)
254
+ letters = _compact_letters(
255
+ list(means[factor]),
256
+ dict(zip(means[factor], means["Mean"], strict=True)),
257
+ rows,
258
+ alpha,
259
+ )
260
+ means["Tukey Grouping"] = means[factor].map(letters)
261
+ result.add_table(
262
+ "Group Means",
263
+ means,
264
+ notes=f"Groups sharing a Tukey HSD letter are not significantly different at alpha {alpha:.3g}.",
265
+ )
266
+ result.add_table("Tukey HSD", pd.DataFrame(rows))
267
+ result.summary += (
268
+ " Tukey HSD letters are shown in Group Means; "
269
+ "groups sharing a letter are not significantly different."
270
+ )
271
+ except Exception as exc:
272
+ result.add_table("Group Means", means)
273
+ result.notes = f"Tukey HSD grouping letters could not be computed: {exc}"
274
+ else:
275
+ result.add_table("Group Means", means)
276
+ return result
277
+
278
+
279
+ def _tukey_rows(
280
+ frame: pd.DataFrame,
281
+ response: str,
282
+ factor: str,
283
+ alpha: float,
284
+ ) -> list[dict[str, object]]:
285
+ from statsmodels.stats.multicomp import pairwise_tukeyhsd
286
+
287
+ outcome = pairwise_tukeyhsd(frame[response], frame[factor], alpha=alpha)
288
+ rows: list[dict[str, object]] = []
289
+ for item in outcome.summary().data[1:]:
290
+ rows.append(
291
+ {
292
+ "Group 1": item[0],
293
+ "Group 2": item[1],
294
+ "Mean Difference": float(item[2]),
295
+ "CI Low": float(item[4]),
296
+ "CI High": float(item[5]),
297
+ "p-value": float(item[3]),
298
+ "Adjusted p": float(item[3]),
299
+ "Significant": bool(item[6]),
300
+ }
301
+ )
302
+ return rows
303
+
304
+
305
+ def _letter_label(index: int) -> str:
306
+ label = ""
307
+ value = index + 1
308
+ while value:
309
+ value, remainder = divmod(value - 1, 26)
310
+ label = chr(65 + remainder) + label
311
+ return label
312
+
313
+
314
+ def _compact_letters(
315
+ levels: list[Any],
316
+ means: dict[Any, float],
317
+ rows: list[dict[str, object]],
318
+ alpha: float,
319
+ ) -> dict[Any, str]:
320
+ def mean_key(level: Any) -> tuple[int, float, str]:
321
+ value = float(means.get(level, np.nan))
322
+ if not math.isfinite(value):
323
+ return (1, 0.0, str(level))
324
+ return (0, -value, str(level))
325
+
326
+ ordered = sorted(levels, key=mean_key)
327
+ rank = {level: index for index, level in enumerate(ordered)}
328
+ label_to_level = {str(level): level for level in levels}
329
+ adjacency: dict[Any, set[Any]] = {level: set() for level in levels}
330
+ for row in rows:
331
+ first = label_to_level.get(str(row.get("Group 1")))
332
+ second = label_to_level.get(str(row.get("Group 2")))
333
+ if first is None or second is None or first == second:
334
+ continue
335
+ raw_p = row.get("Adjusted p", row.get("p-value", 1.0))
336
+ try:
337
+ pvalue = float(raw_p)
338
+ except (TypeError, ValueError) as exc:
339
+ raise ValueError("Tukey adjusted p-values must be numeric.") from exc
340
+ if not math.isfinite(pvalue):
341
+ raise ValueError("Tukey adjusted p-values contain non-finite values.")
342
+ if pvalue >= alpha:
343
+ adjacency[first].add(second)
344
+ adjacency[second].add(first)
345
+
346
+ cliques: list[tuple[Any, ...]] = []
347
+
348
+ def visit(selected: set[Any], candidates: set[Any], excluded: set[Any]) -> None:
349
+ if not candidates and not excluded:
350
+ cliques.append(tuple(sorted(selected, key=lambda level: rank[level])))
351
+ return
352
+ pivot = max(candidates | excluded, key=lambda level: len(candidates & adjacency[level]), default=None)
353
+ options = candidates - adjacency[pivot] if pivot is not None else set(candidates)
354
+ for level in list(options):
355
+ visit(selected | {level}, candidates & adjacency[level], excluded & adjacency[level])
356
+ candidates.remove(level)
357
+ excluded.add(level)
358
+
359
+ visit(set(), set(levels), set())
360
+ cliques.sort(key=lambda clique: tuple(rank[level] for level in clique))
361
+ assigned: dict[Any, list[str]] = {level: [] for level in levels}
362
+ for index, clique in enumerate(cliques):
363
+ letter = _letter_label(index)
364
+ for level in clique:
365
+ assigned[level].append(letter)
366
+ return {level: "".join(labels) for level, labels in assigned.items()}
367
+
368
+
369
+ def kruskal_test(df: pd.DataFrame, response: str, factor: str) -> AnalysisResult:
370
+ frame = df[[response, factor]].copy()
371
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
372
+ frame = frame.dropna()
373
+ groups = [chunk[response].to_numpy() for _, chunk in frame.groupby(factor)]
374
+ if len(groups) < 2:
375
+ raise ValueError("The factor must contain at least two levels.")
376
+ statistic, pvalue = stats.kruskal(*groups)
377
+ result = AnalysisResult(
378
+ title=f"Kruskal-Wallis Test: {response} by {factor}",
379
+ analysis_type="kruskal",
380
+ params={"response": response, "factor": factor},
381
+ )
382
+ result.add_table(
383
+ "Test",
384
+ pd.DataFrame(
385
+ [
386
+ {
387
+ "H": statistic,
388
+ "df": len(groups) - 1,
389
+ "p-value": pvalue,
390
+ "Significance": p_stars(pvalue),
391
+ }
392
+ ]
393
+ ),
394
+ )
395
+ result.add_plot("box", {"column": response, "group": factor}, title=f"{response} by {factor}", data=df)
396
+ result.summary = f"Kruskal-Wallis H = {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
397
+ return result
398
+
399
+
400
+ def mann_whitney_test(df: pd.DataFrame, value: str, group: str, alternative: str = "two-sided") -> AnalysisResult:
401
+ frame, levels = _clean_two_groups(df, value, group)
402
+ first = frame.loc[frame[group] == levels[0], value]
403
+ second = frame.loc[frame[group] == levels[1], value]
404
+ statistic, pvalue = stats.mannwhitneyu(first, second, alternative=alternative)
405
+ result = AnalysisResult(
406
+ title=f"Mann-Whitney U Test: {value} by {group}",
407
+ analysis_type="mann_whitney",
408
+ params={"value": value, "group": group, "alternative": alternative},
409
+ )
410
+ result.add_table(
411
+ "Test",
412
+ pd.DataFrame(
413
+ [
414
+ {
415
+ "Group 1": str(levels[0]),
416
+ "N 1": len(first),
417
+ "Median 1": float(first.median()),
418
+ "Group 2": str(levels[1]),
419
+ "N 2": len(second),
420
+ "Median 2": float(second.median()),
421
+ "U": statistic,
422
+ "p-value": pvalue,
423
+ "Significance": p_stars(pvalue),
424
+ }
425
+ ]
426
+ ),
427
+ )
428
+ result.add_plot("box", {"column": value, "group": group}, title=f"{value} by {group}", data=df)
429
+ result.summary = f"U = {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
430
+ return result
431
+
432
+
433
+ def wilcoxon_test(df: pd.DataFrame, column1: str, column2: str, alternative: str = "two-sided") -> AnalysisResult:
434
+ frame = df[[column1, column2]].apply(pd.to_numeric, errors="coerce").dropna()
435
+ if len(frame) < 2:
436
+ raise ValueError("At least two complete pairs are required.")
437
+ statistic, pvalue = stats.wilcoxon(frame[column1], frame[column2], alternative=alternative)
438
+ n_pairs = int((frame[column1] != frame[column2]).sum())
439
+ result = AnalysisResult(
440
+ title=f"Wilcoxon Signed-Rank Test: {column1} vs {column2}",
441
+ analysis_type="wilcoxon",
442
+ params={"column1": column1, "column2": column2, "alternative": alternative},
443
+ )
444
+ result.add_table(
445
+ "Test",
446
+ pd.DataFrame(
447
+ [
448
+ {
449
+ "N Pairs": n_pairs,
450
+ "Statistic": statistic,
451
+ "p-value": pvalue,
452
+ "Significance": p_stars(pvalue),
453
+ }
454
+ ]
455
+ ),
456
+ )
457
+ result.summary = f"Wilcoxon statistic {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
458
+ return result
459
+
460
+
461
+ def chi_square_test(df: pd.DataFrame, row: str, column: str) -> AnalysisResult:
462
+ frame = df[[row, column]].dropna()
463
+ table = pd.crosstab(frame[row], frame[column])
464
+ if table.shape[0] < 2 or table.shape[1] < 2:
465
+ raise ValueError("The two columns must each contain at least two levels.")
466
+ chi2, pvalue, dof, expected = stats.chi2_contingency(table, correction=False)
467
+ result = AnalysisResult(
468
+ title=f"Chi-Square Test: {row} by {column}",
469
+ analysis_type="chi_square",
470
+ params={"row": row, "column": column},
471
+ )
472
+ result.add_table("Contingency Table", table.reset_index())
473
+ expected_frame = pd.DataFrame(expected, index=table.index, columns=table.columns).reset_index()
474
+ result.add_table("Expected Counts", expected_frame)
475
+ result.add_table(
476
+ "Test",
477
+ pd.DataFrame(
478
+ [
479
+ {
480
+ "Chi-Square": chi2,
481
+ "df": dof,
482
+ "p-value": pvalue,
483
+ "Min Expected Count": float(expected.min()),
484
+ "Significance": p_stars(pvalue),
485
+ }
486
+ ]
487
+ ),
488
+ )
489
+ if table.shape == (2, 2):
490
+ yates, yates_p, _, _ = stats.chi2_contingency(table, correction=True)
491
+ _, fisher_p = stats.fisher_exact(table)
492
+ result.add_table(
493
+ "Small-Sample Alternatives",
494
+ pd.DataFrame(
495
+ [
496
+ {"Test": "Yates-corrected Pearson", "Statistic": yates, "p-value": yates_p, "Significance": p_stars(yates_p)},
497
+ {"Test": "Fisher Exact", "Statistic": np.nan, "p-value": fisher_p, "Significance": p_stars(fisher_p)},
498
+ ]
499
+ ),
500
+ )
501
+ result.add_plot("mosaic", {"row": row, "column": column}, title=f"{row} by {column}", data=df)
502
+ result.summary = f"Pearson chi-square = {chi2:.4g}, df = {dof}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
503
+ if expected.min() < 5:
504
+ result.notes = "Some expected counts are below 5; interpret the chi-square approximation cautiously."
505
+ return result
506
+
507
+
508
+ def proportion_test(
509
+ df: pd.DataFrame,
510
+ column: str,
511
+ success: Any,
512
+ null_proportion: float = 0.5,
513
+ group: str | None = None,
514
+ ) -> AnalysisResult:
515
+ frame = df[[column] + ([group] if group else [])].dropna()
516
+ mask = frame[column].astype(str) == str(success)
517
+ count = int(mask.sum())
518
+ nobs = len(frame)
519
+ if nobs == 0:
520
+ raise ValueError("No complete observations.")
521
+ result = AnalysisResult(
522
+ title=f"Proportion Test: {column} = {success}",
523
+ analysis_type="proportion",
524
+ params={"column": column, "success": success, "null_proportion": null_proportion, "group": group},
525
+ )
526
+ if group and group in frame.columns:
527
+ levels = list(pd.unique(frame[group]))
528
+ if len(levels) != 2:
529
+ raise ValueError("The group column must have exactly two levels for a two-sample proportion test.")
530
+ first = frame[group] == levels[0]
531
+ second = frame[group] == levels[1]
532
+ counts = np.array([mask[first].sum(), mask[second].sum()])
533
+ totals = np.array([first.sum(), second.sum()])
534
+ statistic, pvalue = proportions_ztest(counts, totals)
535
+ table = pd.DataFrame(
536
+ [
537
+ {
538
+ "Group 1": str(levels[0]),
539
+ "Successes 1": int(counts[0]),
540
+ "N 1": int(totals[0]),
541
+ "Proportion 1": counts[0] / totals[0],
542
+ "Group 2": str(levels[1]),
543
+ "Successes 2": int(counts[1]),
544
+ "N 2": int(totals[1]),
545
+ "Proportion 2": counts[1] / totals[1],
546
+ "z": statistic,
547
+ "p-value": pvalue,
548
+ "Significance": p_stars(pvalue),
549
+ }
550
+ ]
551
+ )
552
+ result.add_table("Two-Sample Proportion Test", table)
553
+ result.summary = f"Two-sample z = {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
554
+ else:
555
+ pvalue = stats.binomtest(count, nobs, null_proportion).pvalue
556
+ result.add_table(
557
+ "One-Sample Proportion Test",
558
+ pd.DataFrame(
559
+ [
560
+ {
561
+ "Successes": count,
562
+ "N": nobs,
563
+ "Proportion": count / nobs,
564
+ "Null Proportion": null_proportion,
565
+ "p-value": pvalue,
566
+ "Significance": p_stars(pvalue),
567
+ }
568
+ ]
569
+ ),
570
+ )
571
+ result.summary = f"Observed proportion {count / nobs:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
572
+ result.add_plot("bar", {"x": column, "y": "Count"}, title=f"Counts of {column}", data=frame[column].astype(str).value_counts().rename_axis(column).reset_index(name="Count"))
573
+ return result
574
+
575
+
576
+ def normality_test(df: pd.DataFrame, column: str) -> AnalysisResult:
577
+ values = pd.to_numeric(df[column], errors="coerce").dropna().to_numpy(dtype=float)
578
+ if len(values) < 3:
579
+ raise ValueError("At least three observations are required.")
580
+ rows = []
581
+ if len(values) <= 5000:
582
+ statistic, pvalue = stats.shapiro(values)
583
+ rows.append({"Test": "Shapiro-Wilk", "Statistic": statistic, "p-value": pvalue})
584
+ if len(values) >= 8:
585
+ ad = stats.anderson(values, dist="norm")
586
+ rows.append({"Test": "Anderson-Darling", "Statistic": float(ad.statistic), "p-value": np.nan})
587
+ ordered = np.sort(values)
588
+ n = len(values)
589
+ scores = stats.norm.ppf((np.arange(1, n + 1) - 0.375) / (n + 0.25))
590
+ rows.append({"Test": "Ryan-Joiner", "Statistic": float(np.corrcoef(ordered, scores)[0, 1]), "p-value": np.nan})
591
+ mean = float(np.mean(values))
592
+ std = float(np.std(values, ddof=1))
593
+ try:
594
+ from statsmodels.stats.diagnostic import lilliefors
595
+
596
+ ks_statistic, ks_pvalue = lilliefors(values, dist="norm")
597
+ ks_label = "Kolmogorov-Smirnov (Lilliefors)"
598
+ except Exception:
599
+ ks_statistic, ks_pvalue = stats.kstest(values, "norm", args=(mean, std))
600
+ ks_label = "Kolmogorov-Smirnov"
601
+ rows.append({"Test": ks_label, "Statistic": float(ks_statistic), "p-value": float(ks_pvalue)})
602
+ table = pd.DataFrame(rows)
603
+ table["Significance"] = table["p-value"].map(p_stars)
604
+ result = AnalysisResult(
605
+ title=f"Normality Test: {column}",
606
+ analysis_type="normality",
607
+ params={"column": column},
608
+ )
609
+ result.add_table("Tests", table)
610
+ result.notes = "Anderson-Darling and Ryan-Joiner are reported as statistics; interpret them against distribution-specific critical values rather than a p-value."
611
+ result.add_table(
612
+ "Summary",
613
+ pd.DataFrame([{"N": len(values), "Mean": mean, "Std Dev": std, "Min": float(np.min(values)), "Max": float(np.max(values))}]),
614
+ )
615
+ result.add_plot("histogram", {"column": column, "normal_overlay": True}, title=f"Distribution of {column}", data=df)
616
+ result.add_plot("qq", {"column": column}, title=f"Normal Q-Q Plot: {column}", data=df)
617
+ pvalue = float(table.loc[table["Test"] == "Shapiro-Wilk", "p-value"].iloc[0]) if "Shapiro-Wilk" in set(table["Test"]) else float(ks_pvalue)
618
+ result.summary = f"Normality tests for {column}; primary p = {pvalue:.4g}. " + (
619
+ "Evidence against normality." if pvalue < 0.05 else "No strong evidence against normality."
620
+ )
621
+ result.notes = "Anderson-Darling and Ryan-Joiner p-values require simulation or tables; statistics are reported for comparison."
622
+ return result
623
+
624
+
625
+ def _interpret_p(pvalue: float) -> str:
626
+ if pvalue < 0.001:
627
+ return "Highly significant (p < 0.001)."
628
+ if pvalue < 0.01:
629
+ return "Significant at the 1% level."
630
+ if pvalue < 0.05:
631
+ return "Significant at the 5% level."
632
+ return "Not significant at the 5% level."
633
+
634
+
635
+ # ---------------------------------------------------------------------------
636
+ # Additional analyses (Fit Y by X, mean comparisons, contingency, post-hoc)
637
+ # ---------------------------------------------------------------------------
638
+
639
+ def levene_test(df: pd.DataFrame, response: str, factor: str) -> AnalysisResult:
640
+ frame = df[[response, factor]].copy()
641
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
642
+ frame = frame.dropna()
643
+ groups = [chunk[response].to_numpy() for _, chunk in frame.groupby(factor)]
644
+ if len(groups) < 2:
645
+ raise ValueError("The factor must contain at least two levels.")
646
+ statistic, pvalue = stats.levene(*groups, center="median")
647
+ result = AnalysisResult(
648
+ title=f"Levene (Brown-Forsythe) Test: {response} by {factor}",
649
+ analysis_type="levene",
650
+ params={"response": response, "factor": factor},
651
+ )
652
+ result.add_table(
653
+ "Homogeneity of Variance",
654
+ pd.DataFrame(
655
+ [
656
+ {
657
+ "Test": "Brown-Forsythe (median-centered Levene)",
658
+ "Statistic": statistic,
659
+ "df1": len(groups) - 1,
660
+ "df2": len(frame) - len(groups),
661
+ "p-value": pvalue,
662
+ "Significance": p_stars(pvalue),
663
+ }
664
+ ]
665
+ ),
666
+ )
667
+ result.summary = (
668
+ f"Equal-variance assumption {'rejected' if pvalue < 0.05 else 'not rejected'} "
669
+ f"(p = {pvalue:.4g})."
670
+ )
671
+ return result
672
+
673
+
674
+ def fit_y_by_x(df: pd.DataFrame, response: str, factor: str, robust: bool = False) -> AnalysisResult:
675
+ """Fit Y by X: regression for continuous X, ANOVA for categorical X."""
676
+ if response not in df.columns or factor not in df.columns:
677
+ raise KeyError("Response or X column missing.")
678
+ numeric_x = pd.api.types.is_numeric_dtype(df[factor]) and not pd.api.types.is_bool_dtype(df[factor])
679
+ if numeric_x and df[factor].nunique(dropna=True) > 10:
680
+ from statstudio.stats import regression
681
+
682
+ result = regression.linear_regression(df, response, [factor], interactions=False, robust=robust)
683
+ result.title = f"Fit Y by X: {response} vs {factor} (Simple Regression)"
684
+ result.analysis_type = "fit_y_by_x"
685
+ result.params = {"response": response, "factor": factor, "robust": robust}
686
+ result.add_plot(
687
+ "scatter",
688
+ {"x": factor, "y": response, "smooth": True},
689
+ title=f"{response} vs {factor}",
690
+ data=df,
691
+ )
692
+ if len(result.plots) > 1:
693
+ result.plots.insert(0, result.plots.pop())
694
+ return result
695
+ result = anova_oneway(df, response, factor)
696
+ result.title = f"Fit Y by X: {response} by {factor} (One-Way ANOVA)"
697
+ result.analysis_type = "fit_y_by_x"
698
+ try:
699
+ result.tables.extend(levene_test(df, response, factor).tables)
700
+ except Exception:
701
+ pass
702
+ return result
703
+
704
+
705
+ def two_way_anova(
706
+ df: pd.DataFrame,
707
+ response: str,
708
+ factor1: str,
709
+ factor2: str,
710
+ interaction: bool = True,
711
+ ss_type: int = 2,
712
+ ) -> AnalysisResult:
713
+ frame = df[[response, factor1, factor2]].copy()
714
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
715
+ frame = frame.dropna()
716
+ if frame[factor1].nunique() < 2 or frame[factor2].nunique() < 2:
717
+ raise ValueError("Each factor must contain at least two levels.")
718
+ terms = [f"C({_q(factor1)})", f"C({_q(factor2)})"]
719
+ if interaction:
720
+ terms.append(f"C({_q(factor1)}):C({_q(factor2)})")
721
+ formula = f"{_q(response)} ~ " + " + ".join(terms)
722
+ model = smf.ols(formula, data=frame).fit()
723
+ anova = sm.stats.anova_lm(model, typ=min(3, max(1, int(ss_type)))).reset_index().rename(columns={"index": "Source"})
724
+ anova["Source"] = anova["Source"].map(display_formula)
725
+ residual_mask = anova["Source"].astype(str).str.contains("Residual", case=False, na=False)
726
+ residual_ss = float(anova.loc[residual_mask, "sum_sq"].sum())
727
+ anova["Partial Eta Squared"] = (anova["sum_sq"] / (anova["sum_sq"] + residual_ss)).where(~residual_mask)
728
+ anova["Significance"] = anova["PR(>F)"].map(p_stars) if "PR(>F)" in anova else ""
729
+ means = (
730
+ frame.groupby([factor1, factor2], dropna=False)[response]
731
+ .agg(["count", "mean", "std"])
732
+ .reset_index()
733
+ )
734
+ means.columns = [factor1, factor2, "N", "Mean", "Std Dev"]
735
+ result = AnalysisResult(
736
+ title=f"Two-Way ANOVA: {response}",
737
+ analysis_type="two_way_anova",
738
+ params={
739
+ "response": response,
740
+ "factor1": factor1,
741
+ "factor2": factor2,
742
+ "interaction": interaction,
743
+ "formula": formula,
744
+ "ss_type": ss_type,
745
+ },
746
+ )
747
+ result.add_table("ANOVA", anova)
748
+ result.add_table("Cell Means", means)
749
+ result.add_table(
750
+ "Model Metrics",
751
+ pd.DataFrame(
752
+ [
753
+ ("N", len(frame)),
754
+ ("R-squared", model.rsquared),
755
+ ("Adjusted R-squared", model.rsquared_adj),
756
+ ("F statistic", model.fvalue),
757
+ ("Model p-value", model.f_pvalue),
758
+ ("RMSE", float(np.sqrt(model.mse_resid))),
759
+ ],
760
+ columns=["Metric", "Value"],
761
+ ),
762
+ )
763
+ result.add_plot(
764
+ "interaction_grouped",
765
+ {"x": factor1, "y": response, "group": factor2},
766
+ title=f"{response} by {factor1} and {factor2}",
767
+ data=frame,
768
+ )
769
+ result.summary = f"Two-way ANOVA for {response}; R² = {model.rsquared:.4f}, model p = {model.f_pvalue:.4g}, N = {len(frame)}."
770
+ return result
771
+
772
+
773
+ def repeated_measures_anova(
774
+ df: pd.DataFrame,
775
+ response: str,
776
+ subject: str,
777
+ within: list[str],
778
+ ) -> AnalysisResult:
779
+ try:
780
+ from statsmodels.stats.anova import AnovaRM
781
+ except Exception as exc:
782
+ raise ValueError(f"Repeated-measures ANOVA is unavailable: {exc}") from exc
783
+ if not within:
784
+ raise ValueError("Choose at least one within-subject factor.")
785
+ frame = df[[response, subject] + within].dropna()
786
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
787
+ frame = frame.dropna()
788
+ try:
789
+ model = AnovaRM(frame, response, subject, within=within).fit()
790
+ except Exception as exc:
791
+ raise ValueError(f"Repeated-measures ANOVA failed: {exc}") from exc
792
+ table = model.anova_table.reset_index().rename(columns={"index": "Effect"})
793
+ if "Pr > F" in table.columns:
794
+ table["Significance"] = table["Pr > F"].map(p_stars)
795
+ result = AnalysisResult(
796
+ title=f"Repeated-Measures ANOVA: {response}",
797
+ analysis_type="repeated_measures_anova",
798
+ params={"response": response, "subject": subject, "within": list(within)},
799
+ )
800
+ result.add_table("Within-Subject Effects", table)
801
+ result.add_table(
802
+ "Design",
803
+ pd.DataFrame(
804
+ [
805
+ ("Subjects", frame[subject].nunique()),
806
+ ("Observations", len(frame)),
807
+ ("Within factors", ", ".join(within)),
808
+ ],
809
+ columns=["Metric", "Value"],
810
+ ),
811
+ )
812
+ result.summary = f"Repeated-measures ANOVA for {response} with {frame[subject].nunique()} subjects."
813
+ return result
814
+
815
+
816
+ def contingency_table(df: pd.DataFrame, row: str, column: str) -> AnalysisResult:
817
+ frame = df[[row, column]].dropna()
818
+ table = pd.crosstab(frame[row], frame[column])
819
+ if table.shape[0] < 2 or table.shape[1] < 2:
820
+ raise ValueError("Both columns must contain at least two levels.")
821
+ chi2, pvalue, dof, expected = stats.chi2_contingency(table, correction=False)
822
+ total = table.to_numpy().sum()
823
+ expected_frame = pd.DataFrame(expected, index=table.index, columns=table.columns)
824
+ std_resid = (table.to_numpy() - expected) / np.sqrt(expected)
825
+ row_pct = table.div(table.sum(axis=1), axis=0) * 100
826
+ col_pct = table.div(table.sum(axis=0), axis=1) * 100
827
+ obs = table.to_numpy().astype(float)
828
+ exp = np.asarray(expected, dtype=float)
829
+ with np.errstate(divide="ignore", invalid="ignore"):
830
+ terms = np.where(obs > 0, obs * np.log(obs / exp), 0.0)
831
+ g = 2 * float(np.sum(terms))
832
+ min_dim = min(table.shape) - 1
833
+ cramers_v = float(np.sqrt(chi2 / (total * min_dim))) if total and min_dim else np.nan
834
+ rows = []
835
+ for row_value in table.index:
836
+ for column_value in table.columns:
837
+ rows.append(
838
+ {
839
+ row: row_value,
840
+ column: column_value,
841
+ "Count": int(table.loc[row_value, column_value]),
842
+ "Expected": float(expected_frame.loc[row_value, column_value]),
843
+ "Row %": float(row_pct.loc[row_value, column_value]),
844
+ "Column %": float(col_pct.loc[row_value, column_value]),
845
+ "Std Residual": float(std_resid[list(table.index).index(row_value), list(table.columns).index(column_value)]),
846
+ }
847
+ )
848
+ detail = pd.DataFrame(rows)
849
+ tests = pd.DataFrame(
850
+ [
851
+ {"Test": "Pearson Chi-Square", "Statistic": chi2, "df": dof, "p-value": pvalue},
852
+ {"Test": "Likelihood-Ratio G", "Statistic": g, "df": dof, "p-value": float(stats.chi2.sf(g, dof)) if g == g else np.nan},
853
+ ]
854
+ )
855
+ tests["Significance"] = tests["p-value"].map(p_stars)
856
+ result = AnalysisResult(
857
+ title=f"Contingency Analysis: {row} by {column}",
858
+ analysis_type="contingency",
859
+ params={"row": row, "column": column},
860
+ )
861
+ result.add_table("Contingency Table", table.reset_index())
862
+ result.add_table("Cell Details", detail)
863
+ result.add_table("Tests", tests)
864
+ result.add_table(
865
+ "Association",
866
+ pd.DataFrame([{"Cramer's V": cramers_v, "N": int(total), "Min Expected": float(expected.min())}]),
867
+ )
868
+ if table.shape == (2, 2):
869
+ _, fisher_p = stats.fisher_exact(table)
870
+ result.add_table("Fisher Exact", pd.DataFrame([{"p-value": fisher_p, "Significance": p_stars(fisher_p)}]))
871
+ result.add_plot("mosaic", {"row": row, "column": column}, title=f"{row} by {column}", data=df)
872
+ result.summary = f"Chi-square = {chi2:.4g}, df = {dof}, p = {pvalue:.4g}, Cramer's V = {cramers_v:.3f}. {_interpret_p(pvalue)}"
873
+ return result
874
+
875
+
876
+ def posthoc_test(
877
+ df: pd.DataFrame,
878
+ response: str,
879
+ factor: str,
880
+ method: str = "tukey",
881
+ control: Any | None = None,
882
+ alpha: float = 0.05,
883
+ equal_var: bool = False,
884
+ ) -> AnalysisResult:
885
+ from itertools import combinations
886
+ from statsmodels.stats.multitest import multipletests
887
+
888
+ frame = df[[response, factor]].copy()
889
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
890
+ frame = frame.dropna()
891
+ levels = list(pd.unique(frame[factor]))
892
+ if len(levels) < 2:
893
+ raise ValueError("The factor must contain at least two levels.")
894
+ method = method.lower().replace("_", "-")
895
+ groups = {level: frame.loc[frame[factor] == level, response].to_numpy(dtype=float) for level in levels}
896
+ rows: list[dict[str, object]] = []
897
+ label = ""
898
+ if method in {"tukey", "hsd"}:
899
+ rows = _tukey_rows(frame, response, factor, alpha)
900
+ label = "Tukey HSD"
901
+ elif method in {"dunnett", "control"}:
902
+ baseline = control if control is not None else levels[0]
903
+ others = [level for level in levels if level != baseline]
904
+ control_values = groups[baseline]
905
+ adjusted = False
906
+ try:
907
+ outcome = stats.dunnett(*[groups[level] for level in others], control=control_values)
908
+ pvalues = np.asarray(outcome.pvalue)
909
+ statistics = np.asarray(outcome.statistic)
910
+ adjusted = True
911
+ except Exception:
912
+ pvalues = np.array([stats.ttest_ind(control_values, groups[level], equal_var=equal_var).pvalue for level in others])
913
+ statistics = np.array([stats.ttest_ind(control_values, groups[level], equal_var=equal_var).statistic for level in others])
914
+ m = len(others)
915
+ adjusted_p = pvalues if adjusted else 1 - (1 - pvalues) ** m
916
+ for index, level in enumerate(others):
917
+ mean_diff = float(groups[level].mean() - control_values.mean())
918
+ rows.append({
919
+ "Control": str(baseline),
920
+ "Group": str(level),
921
+ "Mean Difference": mean_diff,
922
+ "Statistic": float(statistics[index]),
923
+ "p-value": float(pvalues[index]),
924
+ "Adjusted p": float(adjusted_p[index]),
925
+ "Significant": bool(adjusted_p[index] < alpha),
926
+ })
927
+ label = f"Dunnett comparisons versus {baseline}"
928
+ elif method in {"hsu", "mcb"}:
929
+ best = max(levels, key=lambda level: float(groups[level].mean()))
930
+ for level in levels:
931
+ if level == best:
932
+ continue
933
+ first, second = groups[level], groups[best]
934
+ statistic, pvalue = stats.ttest_ind(first, second, equal_var=equal_var)
935
+ rows.append({
936
+ "Best Group": str(best),
937
+ "Group": str(level),
938
+ "Mean Difference": float(first.mean() - second.mean()),
939
+ "Statistic": float(statistic),
940
+ "p-value": float(pvalue),
941
+ "Adjusted p": float(min(1.0, pvalue * max(1, len(levels) - 1))),
942
+ "Significant": bool(pvalue * max(1, len(levels) - 1) < alpha),
943
+ })
944
+ label = f"Hsu MCB versus best group {best}"
945
+ elif method in {"games-howell", "tamhane", "fisher-lsd", "bonferroni", "bonf"}:
946
+ pairs = list(combinations(levels, 2))
947
+ raw_p: list[float] = []
948
+ metadata: list[dict[str, object]] = []
949
+ for first_level, second_level in pairs:
950
+ first, second = groups[first_level], groups[second_level]
951
+ statistic, pvalue = stats.ttest_ind(first, second, equal_var=equal_var)
952
+ n1, n2 = len(first), len(second)
953
+ diff = float(first.mean() - second.mean())
954
+ row = {
955
+ "Group 1": str(first_level),
956
+ "Group 2": str(second_level),
957
+ "Mean Difference": diff,
958
+ "Statistic": float(statistic),
959
+ "p-value": float(pvalue),
960
+ }
961
+ if method in {"games-howell", "tamhane"}:
962
+ var1, var2 = float(first.var(ddof=1)), float(second.var(ddof=1))
963
+ se = math.sqrt(var1 / n1 + var2 / n2)
964
+ df_value = (var1 / n1 + var2 / n2) ** 2 / (
965
+ (var1 / n1) ** 2 / max(1, n1 - 1) + (var2 / n2) ** 2 / max(1, n2 - 1)
966
+ ) if se else 1
967
+ if method == "games-howell":
968
+ q_value = abs(diff) / se * math.sqrt(2) if se else np.nan
969
+ p_adjusted = float(stats.studentized_range.sf(q_value, len(levels), df_value)) if np.isfinite(q_value) else np.nan
970
+ else:
971
+ raw = float(2 * stats.t.sf(abs(statistic), df_value)) if np.isfinite(df_value) else np.nan
972
+ p_adjusted = float(1 - (1 - raw) ** max(1, len(levels) - 1)) if np.isfinite(raw) else np.nan
973
+ row["df"] = df_value
974
+ row["Adjusted p"] = p_adjusted
975
+ row["Significant"] = bool(p_adjusted < alpha)
976
+ raw_p.append(p_adjusted)
977
+ else:
978
+ raw_p.append(float(pvalue))
979
+ metadata.append(row)
980
+ if method in {"bonferroni", "bonf"}:
981
+ adjusted = multipletests(raw_p, alpha=alpha, method="bonferroni")[1]
982
+ else:
983
+ adjusted = raw_p
984
+ for row, pvalue in zip(metadata, adjusted):
985
+ row["Adjusted p"] = float(pvalue)
986
+ row["Significant"] = bool(pvalue < alpha)
987
+ rows = metadata
988
+ label = {
989
+ "games-howell": "Games-Howell",
990
+ "tamhane": "Tamhane T2 (Welch + Sidak)",
991
+ "fisher-lsd": "Fisher LSD (unadjusted)",
992
+ "bonferroni": "Bonferroni-adjusted pairwise t tests",
993
+ "bonf": "Bonferroni-adjusted pairwise t tests",
994
+ }[method]
995
+ elif method == "newman-keuls":
996
+ rows, label = _newman_keuls(levels, groups, alpha)
997
+ elif method == "dunn":
998
+ rows, label = _dunn_test(levels, groups, alpha)
999
+ elif method == "steel-dwass":
1000
+ rows, label = _steel_dwass_test(levels, groups, alpha)
1001
+ else:
1002
+ raise ValueError(f"Unknown post-hoc method: {method}")
1003
+ result = AnalysisResult(
1004
+ title=f"Post-Hoc Comparisons: {response} by {factor}",
1005
+ analysis_type="posthoc",
1006
+ params={"response": response, "factor": factor, "method": method, "control": control, "alpha": alpha, "equal_var": equal_var},
1007
+ )
1008
+ result.add_table(label, pd.DataFrame(rows))
1009
+ result.summary = f"{label} across {len(levels)} levels of {factor} at alpha {alpha}."
1010
+ if method in {"tukey", "hsd"}:
1011
+ try:
1012
+ means = (
1013
+ frame.groupby(factor)[response]
1014
+ .agg(["count", "mean"])
1015
+ .reset_index()
1016
+ )
1017
+ means.columns = [factor, "N", "Mean"]
1018
+ letters = _compact_letters(
1019
+ list(means[factor]),
1020
+ dict(zip(means[factor], means["Mean"], strict=True)),
1021
+ rows,
1022
+ alpha,
1023
+ )
1024
+ means["Tukey Grouping"] = means[factor].map(letters)
1025
+ means = means.sort_values("Mean", ascending=False, kind="stable").reset_index(drop=True)
1026
+ result.add_table(
1027
+ "Tukey Grouping",
1028
+ means,
1029
+ notes=f"Groups sharing a Tukey HSD letter are not significantly different at alpha {alpha:.3g}.",
1030
+ )
1031
+ result.summary += " Groups sharing a letter are not significantly different."
1032
+ except Exception as exc:
1033
+ result.notes = f"Tukey HSD grouping letters could not be computed: {exc}"
1034
+ result.add_plot("box", {"column": response, "group": factor}, title=f"{response} by {factor}", data=df)
1035
+ return result
1036
+
1037
+
1038
+ def _newman_keuls(levels: list[Any], groups: dict[Any, np.ndarray], alpha: float) -> tuple[list[dict[str, object]], str]:
1039
+ from itertools import combinations
1040
+
1041
+ k = len(levels)
1042
+ all_values = np.concatenate([groups[level] for level in levels])
1043
+ n_total = len(all_values)
1044
+ df_error = n_total - k
1045
+ if df_error <= 0:
1046
+ raise ValueError("Not enough observations for Newman-Keuls.")
1047
+ grand = float(all_values.mean())
1048
+ ss_between = sum(len(groups[level]) * (float(groups[level].mean()) - grand) ** 2 for level in levels)
1049
+ ss_within = sum(float(((groups[level] - groups[level].mean()) ** 2).sum()) for level in levels)
1050
+ mse = ss_within / df_error
1051
+ del ss_between
1052
+ if not np.isfinite(mse) or mse <= 0:
1053
+ raise ValueError("Within-group variance is zero; Newman-Keuls cannot be computed.")
1054
+ ordered = sorted(levels, key=lambda level: float(groups[level].mean()))
1055
+ rank_of = {level: index for index, level in enumerate(ordered)}
1056
+ pairs = list(combinations(levels, 2))
1057
+ info: dict[tuple[Any, Any], dict[str, object]] = {}
1058
+ for first_level, second_level in pairs:
1059
+ first, second = groups[first_level], groups[second_level]
1060
+ n1, n2 = len(first), len(second)
1061
+ diff = float(first.mean() - second.mean())
1062
+ span = abs(rank_of[first_level] - rank_of[second_level]) + 1
1063
+ se = math.sqrt(mse / 2.0 * (1.0 / n1 + 1.0 / n2))
1064
+ q_value = abs(diff) / se if se else np.nan
1065
+ pvalue = float(stats.studentized_range.sf(q_value, span, df_error)) if np.isfinite(q_value) else np.nan
1066
+ key = (first_level, second_level)
1067
+ info[key] = {
1068
+ "Group 1": str(first_level),
1069
+ "Group 2": str(second_level),
1070
+ "Mean Difference": diff,
1071
+ "Range": int(span),
1072
+ "q": float(q_value) if np.isfinite(q_value) else np.nan,
1073
+ "p-value": pvalue,
1074
+ "Adjusted p": pvalue,
1075
+ "_span": span,
1076
+ }
1077
+ significant: dict[tuple[Any, Any], bool] = {}
1078
+ for span in range(k, 1, -1):
1079
+ for start in range(0, k - span + 1):
1080
+ end = start + span - 1
1081
+ left, right = ordered[start], ordered[end]
1082
+ key = (left, right) if (left, right) in info else (right, left)
1083
+ entry = info[key]
1084
+ decision = bool(entry["p-value"] < alpha)
1085
+ if decision:
1086
+ for wider in range(span + 1, k + 1):
1087
+ for outer in range(0, k - wider + 1):
1088
+ inner_end = outer + wider - 1
1089
+ if outer <= start and end <= inner_end:
1090
+ enclosing = (ordered[outer], ordered[inner_end])
1091
+ enclosing = enclosing if enclosing in significant else (enclosing[1], enclosing[0])
1092
+ if not significant.get(enclosing, True):
1093
+ decision = False
1094
+ break
1095
+ if not decision:
1096
+ break
1097
+ significant[key] = decision
1098
+ rows: list[dict[str, object]] = []
1099
+ for first_level, second_level in pairs:
1100
+ entry = dict(info[(first_level, second_level)])
1101
+ entry.pop("_span", None)
1102
+ entry["Significant"] = bool(significant.get((first_level, second_level), False))
1103
+ rows.append(entry)
1104
+ return rows, "Newman-Keuls (studentized range, step-down)"
1105
+
1106
+
1107
+ def _dunn_test(levels: list[Any], groups: dict[Any, np.ndarray], alpha: float) -> tuple[list[dict[str, object]], str]:
1108
+ from itertools import combinations
1109
+ from statsmodels.stats.multitest import multipletests
1110
+
1111
+ combined = np.concatenate([groups[level] for level in levels])
1112
+ n = len(combined)
1113
+ if n < 3:
1114
+ raise ValueError("At least three observations are required for Dunn's test.")
1115
+ ranks = stats.rankdata(combined, method="average")
1116
+ position = 0
1117
+ rank_sums: dict[Any, float] = {}
1118
+ for level in levels:
1119
+ size = len(groups[level])
1120
+ rank_sums[level] = float(ranks[position:position + size].sum())
1121
+ position += size
1122
+ counts = {level: len(groups[level]) for level in levels}
1123
+ mean_ranks = {level: rank_sums[level] / counts[level] for level in levels}
1124
+ tie_counts = np.unique(ranks, return_counts=True)[1]
1125
+ tie_sum = float(np.sum(tie_counts ** 3 - tie_counts)) / (12.0 * (n - 1.0))
1126
+ variance_term = n * (n + 1.0) / 12.0 - tie_sum
1127
+ pairs = list(combinations(levels, 2))
1128
+ raw_p: list[float] = []
1129
+ rows: list[dict[str, object]] = []
1130
+ for first_level, second_level in pairs:
1131
+ diff = mean_ranks[first_level] - mean_ranks[second_level]
1132
+ scale = math.sqrt(variance_term * (1.0 / counts[first_level] + 1.0 / counts[second_level]))
1133
+ z_value = diff / scale if scale else np.nan
1134
+ pvalue = float(2.0 * stats.norm.sf(abs(z_value))) if np.isfinite(z_value) else np.nan
1135
+ raw_p.append(pvalue)
1136
+ rows.append({
1137
+ "Group 1": str(first_level),
1138
+ "Group 2": str(second_level),
1139
+ "Mean Rank Difference": float(diff),
1140
+ "z": float(z_value) if np.isfinite(z_value) else np.nan,
1141
+ "p-value": pvalue,
1142
+ })
1143
+ adjusted = multipletests(raw_p, alpha=alpha, method="bonferroni")[1]
1144
+ for row, pvalue in zip(rows, adjusted):
1145
+ row["Adjusted p"] = float(pvalue)
1146
+ row["Significant"] = bool(pvalue < alpha)
1147
+ return rows, "Dunn (rank-sum, Bonferroni)"
1148
+
1149
+
1150
+ def _steel_dwass_test(levels: list[Any], groups: dict[Any, np.ndarray], alpha: float) -> tuple[list[dict[str, object]], str]:
1151
+ from itertools import combinations
1152
+
1153
+ k = len(levels)
1154
+ pairs = list(combinations(levels, 2))
1155
+ rows: list[dict[str, object]] = []
1156
+ for first_level, second_level in pairs:
1157
+ first, second = groups[first_level], groups[second_level]
1158
+ n_first, n_second = len(first), len(second)
1159
+ combined = np.concatenate([first, second])
1160
+ ranks = stats.rankdata(combined, method="average")
1161
+ rank_sum_first = float(ranks[:n_first].sum())
1162
+ rank_sum_second = float(ranks[n_first:].sum())
1163
+ u_first = n_first * n_second + n_first * (n_first + 1) / 2.0 - rank_sum_first
1164
+ u_second = n_first * n_second + n_second * (n_second + 1) / 2.0 - rank_sum_second
1165
+ u_min = min(u_first, u_second)
1166
+ total = n_first + n_second
1167
+ tie_counts = np.unique(ranks, return_counts=True)[1]
1168
+ ties = float(np.sum(tie_counts ** 3 - tie_counts)) / 12.0
1169
+ variance = (n_first * n_second / (total * (total - 1.0))) * ((total ** 3 - total) / 12.0 - ties)
1170
+ statistic = math.sqrt(2.0) * (u_min - n_first * n_second / 2.0) / math.sqrt(variance) if variance > 0 else np.nan
1171
+ pvalue = float(stats.studentized_range.sf(abs(statistic), k, np.inf)) if np.isfinite(statistic) else np.nan
1172
+ rows.append({
1173
+ "Group 1": str(first_level),
1174
+ "Group 2": str(second_level),
1175
+ "Median Difference": float(np.median(first) - np.median(second)),
1176
+ "U": float(u_min),
1177
+ "Statistic": float(statistic) if np.isfinite(statistic) else np.nan,
1178
+ "p-value": pvalue,
1179
+ "Adjusted p": pvalue,
1180
+ "Significant": bool(pvalue < alpha),
1181
+ })
1182
+ return rows, "Steel-Dwass (DSCF, studentized range)"
1183
+
1184
+
1185
+ def sign_test(df: pd.DataFrame, column: str, hypothesized_median: float = 0.0, alternative: str = "two-sided") -> AnalysisResult:
1186
+ values = pd.to_numeric(df[column], errors="coerce").dropna().to_numpy(dtype=float)
1187
+ above = int(np.sum(values > hypothesized_median))
1188
+ below = int(np.sum(values < hypothesized_median))
1189
+ n = above + below
1190
+ if n == 0:
1191
+ raise ValueError("All observations equal the hypothesized median.")
1192
+ if alternative == "greater":
1193
+ pvalue = float(stats.binom.sf(above - 1, n, 0.5))
1194
+ elif alternative == "less":
1195
+ pvalue = float(stats.binom.cdf(above, n, 0.5))
1196
+ else:
1197
+ pvalue = float(min(1.0, 2 * min(stats.binom.cdf(min(above, below), n, 0.5), stats.binom.sf(max(above, below) - 1, n, 0.5))))
1198
+ result = AnalysisResult(title=f"Sign Test: {column}", analysis_type="sign_test", params={"column": column, "hypothesized_median": hypothesized_median, "alternative": alternative})
1199
+ result.add_table("Test", pd.DataFrame([{"Above": above, "Below": below, "N": n, "p-value": pvalue, "Significance": p_stars(pvalue)}]))
1200
+ result.summary = f"Sign test p = {pvalue:.4g}. {_interpret_p(pvalue)}"
1201
+ return result
1202
+
1203
+
1204
+ def one_sample_wilcoxon(df: pd.DataFrame, column: str, hypothesized_median: float = 0.0, alternative: str = "two-sided") -> AnalysisResult:
1205
+ values = pd.to_numeric(df[column], errors="coerce").dropna().to_numpy(dtype=float)
1206
+ statistic, pvalue = stats.wilcoxon(values - hypothesized_median, alternative=alternative)
1207
+ result = AnalysisResult(title=f"One-Sample Wilcoxon: {column}", analysis_type="one_sample_wilcoxon", params={"column": column, "hypothesized_median": hypothesized_median, "alternative": alternative})
1208
+ result.add_table("Test", pd.DataFrame([{"N": len(values), "Statistic": statistic, "p-value": pvalue, "Significance": p_stars(pvalue)}]))
1209
+ result.summary = f"Wilcoxon statistic {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
1210
+ return result
1211
+
1212
+
1213
+ def mood_median_test(df: pd.DataFrame, response: str, factor: str) -> AnalysisResult:
1214
+ frame = df[[response, factor]].copy()
1215
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
1216
+ frame = frame.dropna()
1217
+ groups = [chunk[response].to_numpy(dtype=float) for _, chunk in frame.groupby(factor)]
1218
+ if len(groups) < 2:
1219
+ raise ValueError("The factor must contain at least two levels.")
1220
+ combined = np.concatenate(groups)
1221
+ grand_median = float(np.median(combined))
1222
+ above = np.array([np.sum(group > grand_median) for group in groups])
1223
+ below = np.array([np.sum(group < grand_median) for group in groups])
1224
+ table = pd.DataFrame({"Above": above, "Below": below})
1225
+ statistic, pvalue, dof, _ = stats.chi2_contingency(table.to_numpy())
1226
+ result = AnalysisResult(title=f"Mood's Median Test: {response} by {factor}", analysis_type="mood_median", params={"response": response, "factor": factor})
1227
+ result.add_table("Counts", table.reset_index().rename(columns={"index": factor}))
1228
+ result.add_table("Test", pd.DataFrame([{"Grand Median": grand_median, "Chi-Square": statistic, "df": dof, "p-value": pvalue, "Significance": p_stars(pvalue)}]))
1229
+ result.summary = f"Mood's median chi-square = {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
1230
+ return result
1231
+
1232
+
1233
+ def friedman_test(df: pd.DataFrame, columns: Sequence[str]) -> AnalysisResult:
1234
+ columns = [c for c in columns if c in df.columns]
1235
+ if len(columns) < 3:
1236
+ raise ValueError("Friedman test requires at least three related columns.")
1237
+ frame = df.loc[:, columns].apply(pd.to_numeric, errors="coerce").dropna()
1238
+ statistic, pvalue = stats.friedmanchisquare(*[frame[c].to_numpy(dtype=float) for c in columns])
1239
+ result = AnalysisResult(title="Friedman Test", analysis_type="friedman", params={"columns": list(columns)})
1240
+ result.add_table("Test", pd.DataFrame([{"N Blocks": len(frame), "Statistic": statistic, "df": len(columns) - 1, "p-value": pvalue, "Significance": p_stars(pvalue)}]))
1241
+ result.summary = f"Friedman chi-square = {statistic:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
1242
+ return result
1243
+
1244
+
1245
+ def runs_test(df: pd.DataFrame, column: str) -> AnalysisResult:
1246
+ values = pd.to_numeric(df[column], errors="coerce").dropna().to_numpy(dtype=float)
1247
+ if len(values) < 3:
1248
+ raise ValueError("At least three observations are required.")
1249
+ median = float(np.median(values))
1250
+ signs = values > median
1251
+ signs = signs[values != median]
1252
+ if len(signs) < 3:
1253
+ raise ValueError("Too many values equal the median.")
1254
+ runs = 1 + int(np.sum(signs[1:] != signs[:-1]))
1255
+ n1 = int(np.sum(signs))
1256
+ n2 = int(len(signs) - n1)
1257
+ mean = 2 * n1 * n2 / (n1 + n2) + 1
1258
+ variance = 2 * n1 * n2 * (2 * n1 * n2 - n1 - n2) / ((n1 + n2) ** 2 * (n1 + n2 - 1))
1259
+ z_value = (runs - mean) / math.sqrt(variance) if variance > 0 else np.nan
1260
+ pvalue = float(2 * stats.norm.sf(abs(z_value))) if np.isfinite(z_value) else np.nan
1261
+ result = AnalysisResult(title=f"Runs Test: {column}", analysis_type="runs_test", params={"column": column})
1262
+ result.add_table("Test", pd.DataFrame([{"Runs": runs, "Above Median": n1, "Below Median": n2, "Z": z_value, "p-value": pvalue, "Significance": p_stars(pvalue)}]))
1263
+ result.summary = f"Runs = {runs}, Z = {z_value:.4g}, p = {pvalue:.4g}. {_interpret_p(pvalue)}"
1264
+ return result
1265
+
1266
+
1267
+ def equivalence_test(
1268
+ df: pd.DataFrame,
1269
+ value: str,
1270
+ group: str,
1271
+ margin: float,
1272
+ alpha: float = 0.05,
1273
+ ) -> AnalysisResult:
1274
+ if margin <= 0:
1275
+ raise ValueError("Equivalence margin must be positive.")
1276
+ frame, levels = _clean_two_groups(df, value, group)
1277
+ first = frame.loc[frame[group] == levels[0], value].to_numpy(dtype=float)
1278
+ second = frame.loc[frame[group] == levels[1], value].to_numpy(dtype=float)
1279
+ first = first[np.isfinite(first)]
1280
+ second = second[np.isfinite(second)]
1281
+ diff = float(np.mean(first) - np.mean(second))
1282
+ se = math.sqrt(np.var(first, ddof=1) / len(first) + np.var(second, ddof=1) / len(second))
1283
+ df_value = (np.var(first, ddof=1) / len(first) + np.var(second, ddof=1) / len(second)) ** 2 / (
1284
+ (np.var(first, ddof=1) / len(first)) ** 2 / max(1, len(first) - 1)
1285
+ + (np.var(second, ddof=1) / len(second)) ** 2 / max(1, len(second) - 1)
1286
+ )
1287
+ critical = float(stats.t.ppf(1 - alpha, df_value))
1288
+ lower = diff - critical * se
1289
+ upper = diff + critical * se
1290
+ p_lower = float(stats.t.sf((diff + margin) / se, df_value)) if se else np.nan
1291
+ p_upper = float(stats.t.cdf((diff - margin) / se, df_value)) if se else np.nan
1292
+ pvalue = max(p_lower, p_upper) if np.isfinite(p_lower) and np.isfinite(p_upper) else np.nan
1293
+ result = AnalysisResult(title=f"Equivalence Test: {value} by {group}", analysis_type="equivalence", params={"value": value, "group": group, "margin": margin, "alpha": alpha})
1294
+ result.add_table("TOST", pd.DataFrame([{
1295
+ "Group 1": str(levels[0]),
1296
+ "Group 2": str(levels[1]),
1297
+ "Difference": diff,
1298
+ "Margin": margin,
1299
+ "Lower CI": lower,
1300
+ "Upper CI": upper,
1301
+ "p-value": pvalue,
1302
+ "Equivalent": bool(np.isfinite(pvalue) and pvalue < alpha and lower > -margin and upper < margin),
1303
+ }]))
1304
+ result.summary = f"TOST difference {diff:.4g}; 90% CI [{lower:.4g}, {upper:.4g}], p = {pvalue:.4g}."
1305
+ return result