staplot 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 (68) hide show
  1. staplot/__init__.py +1 -0
  2. staplot/api.py +441 -0
  3. staplot/main.py +21 -0
  4. staplot/models/__init__.py +1 -0
  5. staplot/models/project.py +461 -0
  6. staplot/plots/__init__.py +14 -0
  7. staplot/plots/bar.py +104 -0
  8. staplot/plots/before_after.py +110 -0
  9. staplot/plots/bland_altman.py +73 -0
  10. staplot/plots/box.py +95 -0
  11. staplot/plots/distribution_plot.py +188 -0
  12. staplot/plots/grouped_bar.py +112 -0
  13. staplot/plots/heatmap.py +73 -0
  14. staplot/plots/histogram.py +76 -0
  15. staplot/plots/qq.py +61 -0
  16. staplot/plots/residuals.py +72 -0
  17. staplot/plots/roc_plot.py +40 -0
  18. staplot/plots/scatter.py +61 -0
  19. staplot/plots/significance.py +94 -0
  20. staplot/plots/styles.py +154 -0
  21. staplot/plots/survival.py +78 -0
  22. staplot/plots/volcano.py +110 -0
  23. staplot/stats/__init__.py +15 -0
  24. staplot/stats/anova.py +124 -0
  25. staplot/stats/chi_square.py +85 -0
  26. staplot/stats/correlation.py +71 -0
  27. staplot/stats/curve_fit.py +85 -0
  28. staplot/stats/descriptive.py +52 -0
  29. staplot/stats/distribution.py +223 -0
  30. staplot/stats/multiple_comparisons.py +104 -0
  31. staplot/stats/normality.py +67 -0
  32. staplot/stats/outliers.py +62 -0
  33. staplot/stats/power.py +130 -0
  34. staplot/stats/regression.py +95 -0
  35. staplot/stats/repeated_measures.py +114 -0
  36. staplot/stats/roc.py +196 -0
  37. staplot/stats/tests.py +142 -0
  38. staplot/stats/two_way_anova.py +88 -0
  39. staplot/ui/__init__.py +0 -0
  40. staplot/ui/analysis_dialog.py +406 -0
  41. staplot/ui/axis_dialog.py +104 -0
  42. staplot/ui/computed_column_dialog.py +261 -0
  43. staplot/ui/contingency_table_widget.py +158 -0
  44. staplot/ui/data_table_widget.py +277 -0
  45. staplot/ui/distribution_inspector.py +431 -0
  46. staplot/ui/figure_layout_widget.py +236 -0
  47. staplot/ui/graph_gallery.py +117 -0
  48. staplot/ui/graph_options_dialog.py +325 -0
  49. staplot/ui/grouped_table_widget.py +190 -0
  50. staplot/ui/layout_dialog.py +218 -0
  51. staplot/ui/main_window.py +1126 -0
  52. staplot/ui/multiple_comparisons_dialog.py +168 -0
  53. staplot/ui/navigator.py +88 -0
  54. staplot/ui/plot_canvas.py +251 -0
  55. staplot/ui/power_dialog.py +108 -0
  56. staplot/ui/report_dialog.py +255 -0
  57. staplot/ui/reshape_dialog.py +286 -0
  58. staplot/ui/results_widget.py +19 -0
  59. staplot/ui/standard_curve_dialog.py +150 -0
  60. staplot/ui/test_wizard.py +252 -0
  61. staplot/ui/transform_dialog.py +137 -0
  62. staplot/ui/undo_commands.py +86 -0
  63. staplot-0.1.0.dist-info/METADATA +85 -0
  64. staplot-0.1.0.dist-info/RECORD +68 -0
  65. staplot-0.1.0.dist-info/WHEEL +5 -0
  66. staplot-0.1.0.dist-info/entry_points.txt +2 -0
  67. staplot-0.1.0.dist-info/licenses/LICENSE +24 -0
  68. staplot-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,104 @@
1
+ """Multiple-comparison correction (Bonferroni, FDR, Holm, …)."""
2
+
3
+ import numpy as np
4
+ from statsmodels.stats.multitest import multipletests
5
+
6
+ from ..models.project import AnalysisResult
7
+ from .descriptive import format_p, significance_stars
8
+
9
+ _METHOD_LABELS = {
10
+ "bonferroni": "Bonferroni",
11
+ "fdr_bh": "Benjamini-Hochberg (FDR)",
12
+ "fdr_by": "Benjamini-Yekutieli (FDR)",
13
+ "holm": "Holm (Holm-Bonferroni)",
14
+ "holm-sidak": "Holm-Sidak",
15
+ "sidak": "Sidak",
16
+ }
17
+
18
+
19
+ def run_multiple_comparisons(
20
+ p_values: list[float],
21
+ names: list[str],
22
+ method: str = "fdr_bh",
23
+ alpha: float = 0.05,
24
+ ) -> AnalysisResult:
25
+ """
26
+ Apply a multiple-testing correction to a list of p-values.
27
+
28
+ Parameters
29
+ ----------
30
+ p_values : raw p-values (one per comparison)
31
+ names : labels for each comparison
32
+ method : statsmodels multipletests method string
33
+ alpha : family-wise significance threshold
34
+ """
35
+ if len(p_values) == 0:
36
+ raise ValueError("No p-values provided.")
37
+ if len(p_values) != len(names):
38
+ raise ValueError("p_values and names must have the same length.")
39
+
40
+ p_arr = np.array(p_values, dtype=float)
41
+ reject, p_corr, alpha_s, alpha_b = multipletests(p_arr, alpha=alpha, method=method)
42
+
43
+ method_label = _METHOD_LABELS.get(method, method)
44
+ n_sig = int(np.sum(reject))
45
+
46
+ col_w = max(30, max(len(n) for n in names) + 2)
47
+ hdr = f"{'Comparison':{col_w}s} {'Raw p':>10s} {'Adj. p':>12s} {'Sig':>6s}"
48
+ sep = "─" * len(hdr)
49
+ rows = []
50
+ for nm, pr, pa, rej in zip(names, p_values, p_corr, reject):
51
+ stars = significance_stars(float(pa)) if rej else ""
52
+ rows.append(
53
+ f"{nm:{col_w}s} {format_p(float(pr)):>10s}"
54
+ f" {format_p(float(pa)):>12s} {'YES' + stars:>6s}"
55
+ if rej else
56
+ f"{nm:{col_w}s} {format_p(float(pr)):>10s}"
57
+ f" {format_p(float(pa)):>12s} {'—':>6s}"
58
+ )
59
+
60
+ lines = [
61
+ f"=== Multiple Comparisons Correction ({method_label}) ===",
62
+ f"Comparisons : {len(p_values)}",
63
+ f"alpha : {alpha:.3f}",
64
+ "",
65
+ hdr,
66
+ sep,
67
+ *rows,
68
+ sep,
69
+ f"Significant after correction: {n_sig} / {len(p_values)}",
70
+ "",
71
+ "Note: 'Adj. p' is the corrected p-value (or Bonferroni-adjusted threshold).",
72
+ ]
73
+
74
+ return AnalysisResult(
75
+ name=f"Multiple comparisons ({method_label})",
76
+ method=f"mc-{method}",
77
+ source_table="",
78
+ summary_text="\n".join(lines),
79
+ details={
80
+ "method": method,
81
+ "alpha": alpha,
82
+ "names": names,
83
+ "p_raw": list(p_values),
84
+ "p_corrected": p_corr.tolist(),
85
+ "reject": reject.tolist(),
86
+ "n_sig": n_sig,
87
+ },
88
+ )
89
+
90
+
91
+ def extract_pairwise_p(analyses: list) -> tuple[list[str], list[float]]:
92
+ """
93
+ Scan a list of AnalysisResult objects and collect pairwise p-values
94
+ (those stored with 'group_a', 'group_b', 'p' keys in details).
95
+ Returns (names, p_values).
96
+ """
97
+ names, pvals = [], []
98
+ for a in analyses:
99
+ d = a.details
100
+ if "group_a" in d and "group_b" in d and "p" in d:
101
+ label = f"{d['group_a']} vs {d['group_b']}"
102
+ names.append(label)
103
+ pvals.append(float(d["p"]))
104
+ return names, pvals
@@ -0,0 +1,67 @@
1
+ """Normality tests: Shapiro-Wilk, D'Agostino-Pearson, KS-test."""
2
+
3
+ import numpy as np
4
+ from scipy import stats
5
+
6
+ from ..models.project import DataTable, AnalysisResult
7
+ from .descriptive import format_p, significance_stars
8
+
9
+
10
+ def run_normality(table: DataTable) -> AnalysisResult:
11
+ lines = ["=== Normality Tests ===", ""]
12
+ all_details: dict = {}
13
+
14
+ for col in table.columns:
15
+ arr = col.valid_values()
16
+ n = len(arr)
17
+ col_detail: dict = {"n": n}
18
+ lines.append(f"--- {col.name} (n={n}) ---")
19
+
20
+ if n < 3:
21
+ lines.append(" Insufficient data (need n ≥ 3).")
22
+ lines.append("")
23
+ continue
24
+
25
+ # Shapiro-Wilk (best for n ≤ 50; also valid for larger n)
26
+ w, p_sw = stats.shapiro(arr)
27
+ col_detail["shapiro_W"] = float(w)
28
+ col_detail["shapiro_p"] = float(p_sw)
29
+ lines.append(f" Shapiro-Wilk W = {w:.4f} {format_p(p_sw):15s} {significance_stars(p_sw)}")
30
+
31
+ # D'Agostino-Pearson (needs n ≥ 8)
32
+ if n >= 8:
33
+ k2, p_dp = stats.normaltest(arr)
34
+ col_detail["dagostino_K2"] = float(k2)
35
+ col_detail["dagostino_p"] = float(p_dp)
36
+ lines.append(f" D'Agostino-Pearson K² = {k2:.4f} {format_p(p_dp):15s} {significance_stars(p_dp)}")
37
+ else:
38
+ p_dp = np.nan
39
+ lines.append(f" D'Agostino-Pearson — requires n ≥ 8")
40
+
41
+ # Kolmogorov-Smirnov against a normal with same mean/sd
42
+ mu, sigma = np.mean(arr), np.std(arr, ddof=1)
43
+ if sigma > 0:
44
+ ks, p_ks = stats.kstest(arr, "norm", args=(mu, sigma))
45
+ col_detail["ks_stat"] = float(ks)
46
+ col_detail["ks_p"] = float(p_ks)
47
+ lines.append(f" KS test D = {ks:.4f} {format_p(p_ks):15s} {significance_stars(p_ks)}")
48
+
49
+ # Verdict: pass if Shapiro-Wilk p > 0.05
50
+ normal = p_sw > 0.05
51
+ verdict = (
52
+ "PASS — data appear normally distributed. Parametric tests are appropriate."
53
+ if normal
54
+ else "FAIL — data deviate from normality. Consider non-parametric alternatives."
55
+ )
56
+ lines.append(f" → {verdict}")
57
+ lines.append("")
58
+ col_detail["passed"] = normal
59
+ all_details[col.name] = col_detail
60
+
61
+ return AnalysisResult(
62
+ name=f"Normality tests: {table.name}",
63
+ method="normality",
64
+ source_table=table.name,
65
+ summary_text="\n".join(lines),
66
+ details=all_details,
67
+ )
@@ -0,0 +1,62 @@
1
+ """Grubbs outlier test (single outlier) applied column-wise."""
2
+
3
+ import numpy as np
4
+ from scipy import stats
5
+
6
+ from ..models.project import DataTable, AnalysisResult
7
+ from .descriptive import format_p
8
+
9
+
10
+ def _grubbs_critical(n: int, alpha: float = 0.05) -> float:
11
+ t_crit = stats.t.ppf(alpha / (2 * n), df=n - 2)
12
+ return ((n - 1) / np.sqrt(n)) * np.sqrt(t_crit ** 2 / (n - 2 + t_crit ** 2))
13
+
14
+
15
+ def grubbs_test_column(arr: np.ndarray, alpha: float = 0.05) -> dict:
16
+ clean = arr[~np.isnan(arr)]
17
+ n = len(clean)
18
+ if n < 3:
19
+ return {"n": n, "error": "Need n ≥ 3"}
20
+ mean, std = np.mean(clean), np.std(clean, ddof=1)
21
+ if std == 0:
22
+ return {"n": n, "G": 0.0, "G_crit": np.nan, "outlier": False}
23
+ G = np.max(np.abs(clean - mean)) / std
24
+ G_crit = _grubbs_critical(n, alpha)
25
+ idx = int(np.argmax(np.abs(clean - mean)))
26
+ return {
27
+ "n": n,
28
+ "G": float(G),
29
+ "G_crit": float(G_crit),
30
+ "outlier": bool(G > G_crit),
31
+ "suspect_value": float(clean[idx]),
32
+ "suspect_index": idx,
33
+ }
34
+
35
+
36
+ def run_grubbs(table: DataTable, alpha: float = 0.05) -> AnalysisResult:
37
+ lines = [f"=== Grubbs Outlier Test (alpha = {alpha}) ===", ""]
38
+ all_details: dict = {}
39
+
40
+ for col in table.columns:
41
+ arr = col.valid_values()
42
+ r = grubbs_test_column(arr, alpha)
43
+ lines.append(f"--- {col.name} ---")
44
+ if "error" in r:
45
+ lines.append(f" {r['error']}")
46
+ else:
47
+ lines.append(f" N = {r['n']}")
48
+ lines.append(f" G = {r['G']:.4f} (critical = {r['G_crit']:.4f})")
49
+ if r["outlier"]:
50
+ lines.append(f" → OUTLIER detected: value = {r['suspect_value']:.4f} (index {r['suspect_index']})")
51
+ else:
52
+ lines.append(" → No significant outlier detected.")
53
+ lines.append("")
54
+ all_details[col.name] = r
55
+
56
+ return AnalysisResult(
57
+ name=f"Grubbs test: {table.name}",
58
+ method="grubbs",
59
+ source_table=table.name,
60
+ summary_text="\n".join(lines),
61
+ details=all_details,
62
+ )
staplot/stats/power.py ADDED
@@ -0,0 +1,130 @@
1
+ """Power analysis and sample size calculation via statsmodels."""
2
+
3
+ import numpy as np
4
+ from statsmodels.stats.power import TTestIndPower, TTestPower, FTestAnovaPower
5
+
6
+ from ..models.project import AnalysisResult
7
+
8
+
9
+ def _effect_size_label(d: float) -> str:
10
+ if abs(d) < 0.2:
11
+ return "negligible"
12
+ if abs(d) < 0.5:
13
+ return "small"
14
+ if abs(d) < 0.8:
15
+ return "medium"
16
+ return "large"
17
+
18
+
19
+ def run_power_ttest(
20
+ effect_size: float = 0.5,
21
+ alpha: float = 0.05,
22
+ power: float = 0.80,
23
+ n: int | None = None,
24
+ paired: bool = False,
25
+ ) -> AnalysisResult:
26
+ analysis = TTestPower() if paired else TTestIndPower()
27
+ # TTestIndPower uses `nobs1`; TTestPower uses `nobs`
28
+ _nobs_kw = "nobs" if paired else "nobs1"
29
+
30
+ if n is None:
31
+ required_n = analysis.solve_power(effect_size=effect_size, alpha=alpha, power=power)
32
+ required_n = int(np.ceil(required_n))
33
+ actual_power = analysis.power(effect_size=effect_size, alpha=alpha,
34
+ **{_nobs_kw: required_n})
35
+ mode_label = "Sample size calculation"
36
+ lines = [
37
+ f"=== Power Analysis: {'Paired' if paired else 'Unpaired'} t-test ===",
38
+ f"Mode: {mode_label}",
39
+ "",
40
+ f"Effect size (Cohen's d) = {effect_size:.3f} ({_effect_size_label(effect_size)})",
41
+ f"alpha (significance) = {alpha:.3f}",
42
+ f"Target power = {power:.2f}",
43
+ "",
44
+ f"Required n per group = {required_n}",
45
+ f"Achieved power = {actual_power:.4f}",
46
+ ]
47
+ result_n = required_n
48
+ result_power = actual_power
49
+ else:
50
+ actual_power = analysis.power(effect_size=effect_size, alpha=alpha,
51
+ **{_nobs_kw: n})
52
+ mode_label = "Power calculation"
53
+ lines = [
54
+ f"=== Power Analysis: {'Paired' if paired else 'Unpaired'} t-test ===",
55
+ f"Mode: {mode_label}",
56
+ "",
57
+ f"Effect size (Cohen's d) = {effect_size:.3f} ({_effect_size_label(effect_size)})",
58
+ f"alpha (significance) = {alpha:.3f}",
59
+ f"n per group = {n}",
60
+ "",
61
+ f"Achieved power = {actual_power:.4f}",
62
+ f"{'-> ADEQUATE power (>= 0.80)' if actual_power >= 0.8 else '-> INSUFFICIENT power (< 0.80) -- consider increasing n'}",
63
+ ]
64
+ result_n = n
65
+ result_power = actual_power
66
+
67
+ # Effect size guide
68
+ lines += [
69
+ "",
70
+ "Cohen's d reference: small=0.2, medium=0.5, large=0.8",
71
+ "Note: effect size can be estimated from pilot data as |Δmean| / pooled_SD",
72
+ ]
73
+
74
+ return AnalysisResult(
75
+ name=f"Power analysis (t-test)",
76
+ method="power-ttest",
77
+ source_table="",
78
+ summary_text="\n".join(lines),
79
+ details={"effect_size": effect_size, "alpha": alpha, "power": float(result_power), "n": result_n},
80
+ )
81
+
82
+
83
+ def run_power_anova(
84
+ effect_size: float = 0.25,
85
+ alpha: float = 0.05,
86
+ power: float = 0.80,
87
+ k_groups: int = 3,
88
+ n: int | None = None,
89
+ ) -> AnalysisResult:
90
+ analysis = FTestAnovaPower()
91
+
92
+ if n is None:
93
+ required_n = analysis.solve_power(effect_size=effect_size, alpha=alpha, power=power, k_groups=k_groups)
94
+ required_n = int(np.ceil(required_n))
95
+ actual_power = analysis.power(effect_size=effect_size, nobs=required_n, alpha=alpha, k_groups=k_groups)
96
+ lines = [
97
+ "=== Power Analysis: One-Way ANOVA ===",
98
+ "",
99
+ f"Effect size (Cohen's f) = {effect_size:.3f}",
100
+ f"Groups (k) = {k_groups}",
101
+ f"alpha = {alpha:.3f}",
102
+ f"Target power = {power:.2f}",
103
+ "",
104
+ f"Required n per group = {required_n}",
105
+ f"Achieved power = {actual_power:.4f}",
106
+ "",
107
+ "Cohen's f reference: small=0.10, medium=0.25, large=0.40",
108
+ ]
109
+ result_n, result_power = required_n, actual_power
110
+ else:
111
+ actual_power = analysis.power(effect_size=effect_size, nobs=n, alpha=alpha, k_groups=k_groups)
112
+ lines = [
113
+ "=== Power Analysis: One-Way ANOVA ===",
114
+ "",
115
+ f"Effect size (Cohen's f) = {effect_size:.3f}",
116
+ f"Groups (k) = {k_groups}",
117
+ f"alpha = {alpha:.3f}",
118
+ f"n per group = {n}",
119
+ "",
120
+ f"Achieved power = {actual_power:.4f}",
121
+ ]
122
+ result_n, result_power = n, actual_power
123
+
124
+ return AnalysisResult(
125
+ name="Power analysis (ANOVA)",
126
+ method="power-anova",
127
+ source_table="",
128
+ summary_text="\n".join(lines),
129
+ details={"effect_size": effect_size, "alpha": alpha, "power": float(result_power), "n": result_n, "k": k_groups},
130
+ )
@@ -0,0 +1,95 @@
1
+ """Multiple linear regression via statsmodels OLS."""
2
+
3
+ import numpy as np
4
+ import statsmodels.api as sm
5
+ from statsmodels.stats.stattools import durbin_watson
6
+
7
+ from ..models.project import DataTable, AnalysisResult
8
+ from .descriptive import format_p, significance_stars
9
+
10
+
11
+ def run_multiple_regression(
12
+ table: DataTable,
13
+ y_col: str,
14
+ x_cols: list[str],
15
+ ) -> AnalysisResult:
16
+ """
17
+ OLS multiple linear regression.
18
+ Returns AnalysisResult with fitted values and residuals in details
19
+ so plot_residuals() can be called downstream.
20
+ """
21
+ if not x_cols:
22
+ raise ValueError("Select at least one predictor (X column).")
23
+
24
+ # excluded cells -> NaN (rows stay aligned), then complete rows only
25
+ df = table.analysis_dataframe()
26
+ for col in [y_col] + x_cols:
27
+ if col not in df.columns:
28
+ raise ValueError(f"Column '{col}' not found in table.")
29
+
30
+ sub = df[[y_col] + x_cols].dropna()
31
+ n = len(sub)
32
+ k = len(x_cols)
33
+
34
+ if n < k + 2:
35
+ raise ValueError(f"Too few complete rows ({n}); need at least {k + 2}.")
36
+
37
+ y = sub[y_col].values
38
+ X = sm.add_constant(sub[x_cols].values, has_constant="add")
39
+ col_names = ["(Intercept)"] + x_cols
40
+
41
+ res = sm.OLS(y, X).fit()
42
+ dw = float(durbin_watson(res.resid))
43
+
44
+ # ── Format output ──────────────────────────────────────────────────
45
+ hdr = f"{'Variable':22s} {'Coeff':>12s} {'Std Err':>12s} {'t':>9s} {'p':>11s}"
46
+ sep = "─" * len(hdr)
47
+ param_rows = []
48
+ for name, coef, se, t_val, pv in zip(
49
+ col_names, res.params, res.bse, res.tvalues, res.pvalues):
50
+ stars = significance_stars(float(pv))
51
+ param_rows.append(
52
+ f"{name:22s} {coef:>12.4f} {se:>12.4f} {t_val:>9.3f}"
53
+ f" {format_p(float(pv)):>11s} {stars}"
54
+ )
55
+
56
+ lines = [
57
+ "=== Multiple Linear Regression (OLS) ===",
58
+ f"Dependent : {y_col}",
59
+ f"Predictors : {', '.join(x_cols)}",
60
+ f"N = {n} | k = {k}",
61
+ "",
62
+ f"R² = {res.rsquared:.4f}",
63
+ f"Adj. R² = {res.rsquared_adj:.4f}",
64
+ f"F({k},{n-k-1}) = {res.fvalue:.4f} {format_p(float(res.f_pvalue))} "
65
+ f"{significance_stars(float(res.f_pvalue))}",
66
+ f"AIC = {res.aic:.2f} | BIC = {res.bic:.2f}",
67
+ f"Durbin-Watson = {dw:.3f}",
68
+ "",
69
+ hdr,
70
+ sep,
71
+ *param_rows,
72
+ "",
73
+ "Significance: *** p<0.001 ** p<0.01 * p<0.05",
74
+ ]
75
+
76
+ return AnalysisResult(
77
+ name=f"MLR: {y_col} ~ {' + '.join(x_cols)}",
78
+ method="multiple-regression",
79
+ source_table=table.name,
80
+ summary_text="\n".join(lines),
81
+ details={
82
+ "r2": float(res.rsquared),
83
+ "adj_r2": float(res.rsquared_adj),
84
+ "f": float(res.fvalue),
85
+ "p": float(res.f_pvalue),
86
+ "coefs": {n: float(c) for n, c in zip(col_names, res.params)},
87
+ "pvalues": {n: float(p) for n, p in zip(col_names, res.pvalues)},
88
+ "se": {n: float(s) for n, s in zip(col_names, res.bse)},
89
+ "fitted": res.fittedvalues.tolist(),
90
+ "residuals": res.resid.tolist(),
91
+ "y_col": y_col,
92
+ "x_cols": x_cols,
93
+ "n": n,
94
+ },
95
+ )
@@ -0,0 +1,114 @@
1
+ """Repeated-measures ANOVA (parametric) and Friedman test (non-parametric)."""
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ from scipy import stats
6
+ from statsmodels.stats.anova import AnovaRM
7
+ from statsmodels.stats.multitest import multipletests
8
+ import itertools
9
+
10
+ from ..models.project import DataTable, AnalysisResult
11
+ from .descriptive import format_p, significance_stars
12
+
13
+
14
+ def _complete_subjects(table: DataTable):
15
+ """(names, {name: array}) restricted to subjects (rows) measured under
16
+ EVERY treatment, so index i is the same subject in each array."""
17
+ names = [c.name for c in table.columns if len(c.valid_values()) > 0]
18
+ if len(names) < 2:
19
+ raise ValueError("Need at least 2 groups (columns).")
20
+ arrays = table.paired_arrays(*names)
21
+ return names, dict(zip(names, arrays))
22
+
23
+
24
+ def run_rm_anova(table: DataTable) -> AnalysisResult:
25
+ """One-way repeated-measures ANOVA. Columns = treatments, rows = subjects."""
26
+ names, groups = _complete_subjects(table)
27
+ min_n = len(groups[names[0]])
28
+ if min_n < 2:
29
+ raise ValueError("Need at least 2 subjects (rows) measured under every treatment.")
30
+
31
+ # Build long-format dataframe
32
+ rows = []
33
+ for subj_idx in range(min_n):
34
+ for grp_name, arr in groups.items():
35
+ rows.append({"subject": subj_idx, "treatment": grp_name, "value": arr[subj_idx]})
36
+ df = pd.DataFrame(rows)
37
+
38
+ model = AnovaRM(df, "value", "subject", within=["treatment"])
39
+ result = model.fit()
40
+ anova_tbl = result.anova_table
41
+
42
+ F = float(anova_tbl["F Value"].iloc[0])
43
+ p = float(anova_tbl["Pr > F"].iloc[0])
44
+ df_num = float(anova_tbl["Num DF"].iloc[0])
45
+ df_den = float(anova_tbl["Den DF"].iloc[0])
46
+
47
+ # Pairwise post-hoc (paired t-test + Bonferroni)
48
+ pairs = list(itertools.combinations(names, 2))
49
+ raw_p = []
50
+ for a, b in pairs:
51
+ _, pij = stats.ttest_rel(groups[a], groups[b])
52
+ raw_p.append(pij)
53
+ _, adj_p, _, _ = multipletests(raw_p, method="bonferroni")
54
+
55
+ ph_lines = ["", "Post-hoc (paired t-test, Bonferroni):"]
56
+ ph_lines.append(f"{'Comparison':35s} {'adj. p':>10s} {'sig':>5s}")
57
+ for (a, b), ap in zip(pairs, adj_p):
58
+ ph_lines.append(f"{a} vs {b:25s} {ap:>10.4f} {significance_stars(ap):>5s}")
59
+
60
+ lines = [
61
+ "=== One-Way Repeated-Measures ANOVA ===",
62
+ f"Subjects: {min_n} | Treatments: {len(names)}",
63
+ "",
64
+ f"F({df_num:.0f}, {df_den:.0f}) = {F:.4f}",
65
+ f"{format_p(p)} {significance_stars(p)}",
66
+ *ph_lines,
67
+ ]
68
+ return AnalysisResult(
69
+ name=f"RM ANOVA: {table.name}",
70
+ method="rm-anova",
71
+ source_table=table.name,
72
+ summary_text="\n".join(lines),
73
+ details={"F": F, "p": p, "groups": names},
74
+ )
75
+
76
+
77
+ def run_friedman(table: DataTable) -> AnalysisResult:
78
+ """Friedman test (non-parametric RM ANOVA). Columns = treatments, rows = blocks."""
79
+ names, groups = _complete_subjects(table)
80
+ min_n = len(groups[names[0]])
81
+ if min_n < 2:
82
+ raise ValueError("Need at least 2 subjects (rows) measured under every treatment.")
83
+ arrays = [groups[n] for n in names]
84
+
85
+ stat, p = stats.friedmanchisquare(*arrays)
86
+
87
+ # Pairwise Wilcoxon post-hoc + Bonferroni
88
+ pairs = list(itertools.combinations(range(len(names)), 2))
89
+ raw_p = []
90
+ for i, j in pairs:
91
+ _, pij = stats.wilcoxon(arrays[i], arrays[j])
92
+ raw_p.append(pij)
93
+ _, adj_p, _, _ = multipletests(raw_p, method="bonferroni")
94
+
95
+ ph_lines = ["", "Post-hoc (Wilcoxon, Bonferroni):"]
96
+ ph_lines.append(f"{'Comparison':35s} {'adj. p':>10s} {'sig':>5s}")
97
+ for (i, j), ap in zip(pairs, adj_p):
98
+ ph_lines.append(f"{names[i]} vs {names[j]:25s} {ap:>10.4f} {significance_stars(ap):>5s}")
99
+
100
+ lines = [
101
+ "=== Friedman Test ===",
102
+ f"Subjects: {min_n} | Treatments: {len(names)}",
103
+ "",
104
+ f"χ²({len(names)-1}) = {stat:.4f}",
105
+ f"{format_p(float(p))} {significance_stars(float(p))}",
106
+ *ph_lines,
107
+ ]
108
+ return AnalysisResult(
109
+ name=f"Friedman: {table.name}",
110
+ method="friedman",
111
+ source_table=table.name,
112
+ summary_text="\n".join(lines),
113
+ details={"chi2": float(stat), "p": float(p), "groups": names},
114
+ )