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.
- staplot/__init__.py +1 -0
- staplot/api.py +441 -0
- staplot/main.py +21 -0
- staplot/models/__init__.py +1 -0
- staplot/models/project.py +461 -0
- staplot/plots/__init__.py +14 -0
- staplot/plots/bar.py +104 -0
- staplot/plots/before_after.py +110 -0
- staplot/plots/bland_altman.py +73 -0
- staplot/plots/box.py +95 -0
- staplot/plots/distribution_plot.py +188 -0
- staplot/plots/grouped_bar.py +112 -0
- staplot/plots/heatmap.py +73 -0
- staplot/plots/histogram.py +76 -0
- staplot/plots/qq.py +61 -0
- staplot/plots/residuals.py +72 -0
- staplot/plots/roc_plot.py +40 -0
- staplot/plots/scatter.py +61 -0
- staplot/plots/significance.py +94 -0
- staplot/plots/styles.py +154 -0
- staplot/plots/survival.py +78 -0
- staplot/plots/volcano.py +110 -0
- staplot/stats/__init__.py +15 -0
- staplot/stats/anova.py +124 -0
- staplot/stats/chi_square.py +85 -0
- staplot/stats/correlation.py +71 -0
- staplot/stats/curve_fit.py +85 -0
- staplot/stats/descriptive.py +52 -0
- staplot/stats/distribution.py +223 -0
- staplot/stats/multiple_comparisons.py +104 -0
- staplot/stats/normality.py +67 -0
- staplot/stats/outliers.py +62 -0
- staplot/stats/power.py +130 -0
- staplot/stats/regression.py +95 -0
- staplot/stats/repeated_measures.py +114 -0
- staplot/stats/roc.py +196 -0
- staplot/stats/tests.py +142 -0
- staplot/stats/two_way_anova.py +88 -0
- staplot/ui/__init__.py +0 -0
- staplot/ui/analysis_dialog.py +406 -0
- staplot/ui/axis_dialog.py +104 -0
- staplot/ui/computed_column_dialog.py +261 -0
- staplot/ui/contingency_table_widget.py +158 -0
- staplot/ui/data_table_widget.py +277 -0
- staplot/ui/distribution_inspector.py +431 -0
- staplot/ui/figure_layout_widget.py +236 -0
- staplot/ui/graph_gallery.py +117 -0
- staplot/ui/graph_options_dialog.py +325 -0
- staplot/ui/grouped_table_widget.py +190 -0
- staplot/ui/layout_dialog.py +218 -0
- staplot/ui/main_window.py +1126 -0
- staplot/ui/multiple_comparisons_dialog.py +168 -0
- staplot/ui/navigator.py +88 -0
- staplot/ui/plot_canvas.py +251 -0
- staplot/ui/power_dialog.py +108 -0
- staplot/ui/report_dialog.py +255 -0
- staplot/ui/reshape_dialog.py +286 -0
- staplot/ui/results_widget.py +19 -0
- staplot/ui/standard_curve_dialog.py +150 -0
- staplot/ui/test_wizard.py +252 -0
- staplot/ui/transform_dialog.py +137 -0
- staplot/ui/undo_commands.py +86 -0
- staplot-0.1.0.dist-info/METADATA +85 -0
- staplot-0.1.0.dist-info/RECORD +68 -0
- staplot-0.1.0.dist-info/WHEEL +5 -0
- staplot-0.1.0.dist-info/entry_points.txt +2 -0
- staplot-0.1.0.dist-info/licenses/LICENSE +24 -0
- staplot-0.1.0.dist-info/top_level.txt +1 -0
staplot/stats/roc.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""ROC curve computation and AUC (no sklearn dependency), and the log-rank 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 validate_binary(values, name: str = "label") -> np.ndarray:
|
|
11
|
+
"""Exact 0/1 values as ints; rejects fractions, other numbers and NaN
|
|
12
|
+
BEFORE any cast (0.5 must not silently become 0)."""
|
|
13
|
+
arr = np.asarray(values, dtype=float)
|
|
14
|
+
if not np.all(np.isfinite(arr)):
|
|
15
|
+
raise ValueError(f"{name} values must be finite 0/1.")
|
|
16
|
+
bad = sorted(set(arr[(arr != 0) & (arr != 1)].tolist()))
|
|
17
|
+
if bad:
|
|
18
|
+
raise ValueError(f"{name} values must be exactly 0 or 1 (found {bad[:5]}).")
|
|
19
|
+
return arr.astype(int)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def roc_curve(labels: np.ndarray, scores: np.ndarray):
|
|
23
|
+
"""(fpr, tpr, thresholds, auc) with ONE curve point per distinct score, so
|
|
24
|
+
tied scores move the curve diagonally (half credit) whatever their order.
|
|
25
|
+
thresholds[i] is the cut (score >= threshold → positive) of point i; the
|
|
26
|
+
first point is (0, 0) at threshold +inf."""
|
|
27
|
+
labels = validate_binary(labels)
|
|
28
|
+
scores = np.asarray(scores, dtype=float)
|
|
29
|
+
if labels.shape != scores.shape:
|
|
30
|
+
raise ValueError("labels and scores must have the same length.")
|
|
31
|
+
if not np.all(np.isfinite(scores)):
|
|
32
|
+
raise ValueError("scores must be finite.")
|
|
33
|
+
n_pos = int(np.sum(labels == 1))
|
|
34
|
+
n_neg = int(np.sum(labels == 0))
|
|
35
|
+
if n_pos == 0 or n_neg == 0:
|
|
36
|
+
raise ValueError("ROC needs both classes (at least one 0 and one 1).")
|
|
37
|
+
thr = np.unique(scores)[::-1]
|
|
38
|
+
tp = np.array([np.sum((scores >= t) & (labels == 1)) for t in thr], dtype=float)
|
|
39
|
+
fp = np.array([np.sum((scores >= t) & (labels == 0)) for t in thr], dtype=float)
|
|
40
|
+
tpr = np.concatenate([[0.0], tp / n_pos])
|
|
41
|
+
fpr = np.concatenate([[0.0], fp / n_neg])
|
|
42
|
+
thresholds = np.concatenate([[np.inf], thr])
|
|
43
|
+
_trapz = getattr(np, "trapezoid", None) or np.trapz
|
|
44
|
+
auc = float(_trapz(tpr, fpr))
|
|
45
|
+
return fpr, tpr, thresholds, auc
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def compute_roc(labels: np.ndarray, scores: np.ndarray) -> tuple[np.ndarray, np.ndarray, float]:
|
|
49
|
+
"""
|
|
50
|
+
Returns (fpr, tpr, auc).
|
|
51
|
+
labels: 0/1 array scores: continuous predictor (higher = more positive)
|
|
52
|
+
"""
|
|
53
|
+
fpr, tpr, _, auc = roc_curve(labels, scores)
|
|
54
|
+
return fpr, tpr, auc
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _delong_variance(labels: np.ndarray, scores: np.ndarray) -> float:
|
|
58
|
+
"""SE of the AUC (DeLong placement values, ties = half credit). NaN when a
|
|
59
|
+
class has fewer than 2 observations (its variance is undefined)."""
|
|
60
|
+
pos = scores[labels == 1]
|
|
61
|
+
neg = scores[labels == 0]
|
|
62
|
+
n1, n2 = len(pos), len(neg)
|
|
63
|
+
if n1 < 2 or n2 < 2:
|
|
64
|
+
return float("nan")
|
|
65
|
+
psi = (pos[:, None] > neg[None, :]).astype(float) + 0.5 * (pos[:, None] == neg[None, :])
|
|
66
|
+
V10 = psi.mean(axis=1)
|
|
67
|
+
V01 = psi.mean(axis=0)
|
|
68
|
+
s10 = np.var(V10, ddof=1) / n1
|
|
69
|
+
s01 = np.var(V01, ddof=1) / n2
|
|
70
|
+
return float(np.sqrt(s10 + s01))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def run_roc(
|
|
74
|
+
table: DataTable,
|
|
75
|
+
label_col: str,
|
|
76
|
+
score_col: str,
|
|
77
|
+
) -> AnalysisResult:
|
|
78
|
+
# label and score of a subject come from the same row
|
|
79
|
+
labels, scores = table.paired_arrays(label_col, score_col)
|
|
80
|
+
labels = validate_binary(labels, f"Label column '{label_col}'")
|
|
81
|
+
|
|
82
|
+
fpr, tpr, thresholds, auc = roc_curve(labels, scores)
|
|
83
|
+
se = _delong_variance(labels, scores)
|
|
84
|
+
if np.isfinite(se) and se > 0:
|
|
85
|
+
z = (auc - 0.5) / se
|
|
86
|
+
p = float(2 * stats.norm.sf(abs(z)))
|
|
87
|
+
ci_lo = max(0.0, auc - 1.96 * se)
|
|
88
|
+
ci_hi = min(1.0, auc + 1.96 * se)
|
|
89
|
+
else:
|
|
90
|
+
z = p = ci_lo = ci_hi = float("nan")
|
|
91
|
+
|
|
92
|
+
# Optimal threshold (Youden index), read at the same curve point
|
|
93
|
+
youden = tpr - fpr
|
|
94
|
+
opt_idx = int(np.argmax(youden))
|
|
95
|
+
opt_thresh = float(thresholds[opt_idx])
|
|
96
|
+
|
|
97
|
+
n_pos, n_neg = int(np.sum(labels == 1)), int(np.sum(labels == 0))
|
|
98
|
+
lines = [
|
|
99
|
+
"=== ROC Curve Analysis ===",
|
|
100
|
+
f"Label column: {label_col} (0=negative, 1=positive)",
|
|
101
|
+
f"Score column: {score_col}",
|
|
102
|
+
f"N = {len(labels)} (positive={n_pos}, negative={n_neg})",
|
|
103
|
+
"",
|
|
104
|
+
f"AUC = {auc:.4f}",
|
|
105
|
+
]
|
|
106
|
+
if np.isfinite(se):
|
|
107
|
+
lines += [
|
|
108
|
+
f"95% CI = [{ci_lo:.4f}, {ci_hi:.4f}]",
|
|
109
|
+
f"SE = {se:.4f}",
|
|
110
|
+
f"z = {z:.4f}",
|
|
111
|
+
f"{format_p(p)} {significance_stars(p)}",
|
|
112
|
+
]
|
|
113
|
+
else:
|
|
114
|
+
lines.append("SE / CI / p: not computed (a class has fewer than 2 observations)")
|
|
115
|
+
lines += [
|
|
116
|
+
"",
|
|
117
|
+
f"Optimal threshold (Youden index) ≈ {opt_thresh:.4f}",
|
|
118
|
+
" (score ≥ threshold → positive; maximises sensitivity + specificity − 1)",
|
|
119
|
+
]
|
|
120
|
+
return AnalysisResult(
|
|
121
|
+
name=f"ROC: {score_col} predicting {label_col}",
|
|
122
|
+
method="roc",
|
|
123
|
+
source_table=table.name,
|
|
124
|
+
summary_text="\n".join(lines),
|
|
125
|
+
details={
|
|
126
|
+
"auc": auc, "p": p, "ci_lo": ci_lo, "ci_hi": ci_hi, "se": se,
|
|
127
|
+
"label_col": label_col, "score_col": score_col,
|
|
128
|
+
"threshold": opt_thresh,
|
|
129
|
+
"fpr": fpr.tolist(), "tpr": tpr.tolist(),
|
|
130
|
+
"thresholds": [None if not np.isfinite(t) else float(t) for t in thresholds],
|
|
131
|
+
},
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def log_rank(t1, e1, t2, e2) -> tuple[float, float, dict]:
|
|
136
|
+
"""Two-group log-rank test (Mantel-Cox) with the hypergeometric risk-set
|
|
137
|
+
variance V = Σ n1·n2·d·(n−d) / (n²·(n−1)). Returns (chi2, p, counts)."""
|
|
138
|
+
t1, t2 = np.asarray(t1, float), np.asarray(t2, float)
|
|
139
|
+
e1, e2 = validate_binary(e1, "event"), validate_binary(e2, "event")
|
|
140
|
+
if not (np.all(np.isfinite(t1)) and np.all(np.isfinite(t2))):
|
|
141
|
+
raise ValueError("times must be finite.")
|
|
142
|
+
event_times = np.unique(np.concatenate([t1[e1 == 1], t2[e2 == 1]]))
|
|
143
|
+
O1 = E1 = V = 0.0
|
|
144
|
+
for t in event_times:
|
|
145
|
+
n1 = float(np.sum(t1 >= t))
|
|
146
|
+
n2 = float(np.sum(t2 >= t))
|
|
147
|
+
d1 = float(np.sum((t1 == t) & (e1 == 1)))
|
|
148
|
+
d2 = float(np.sum((t2 == t) & (e2 == 1)))
|
|
149
|
+
n, d = n1 + n2, d1 + d2
|
|
150
|
+
O1 += d1
|
|
151
|
+
E1 += n1 * d / n
|
|
152
|
+
if n > 1:
|
|
153
|
+
V += n1 * n2 * d * (n - d) / (n * n * (n - 1))
|
|
154
|
+
if V > 0:
|
|
155
|
+
chi2 = (O1 - E1) ** 2 / V
|
|
156
|
+
p = float(stats.chi2.sf(chi2, df=1))
|
|
157
|
+
else:
|
|
158
|
+
chi2, p = float("nan"), float("nan")
|
|
159
|
+
return float(chi2), p, {"O1": O1, "E1": E1, "V": V,
|
|
160
|
+
"O2": float(np.sum(e2 == 1)),
|
|
161
|
+
"E2": float(np.sum(e1 == 1) + np.sum(e2 == 1)) - E1}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def run_log_rank(
|
|
165
|
+
table: DataTable,
|
|
166
|
+
time_col_a: str,
|
|
167
|
+
event_col_a: str,
|
|
168
|
+
time_col_b: str,
|
|
169
|
+
event_col_b: str,
|
|
170
|
+
label_a: str = "Group A",
|
|
171
|
+
label_b: str = "Group B",
|
|
172
|
+
) -> AnalysisResult:
|
|
173
|
+
"""Log-rank test to compare two survival curves."""
|
|
174
|
+
# a subject's time and event flag come from the same row
|
|
175
|
+
t1, e1 = table.paired_arrays(time_col_a, event_col_a)
|
|
176
|
+
t2, e2 = table.paired_arrays(time_col_b, event_col_b)
|
|
177
|
+
chi2, p, cnt = log_rank(t1, e1, t2, e2)
|
|
178
|
+
e1, e2 = validate_binary(e1, "event"), validate_binary(e2, "event")
|
|
179
|
+
|
|
180
|
+
lines = [
|
|
181
|
+
"=== Log-Rank Test ===",
|
|
182
|
+
f"Group A: {label_a} (n={len(t1)}, events={int(np.sum(e1 == 1))})",
|
|
183
|
+
f"Group B: {label_b} (n={len(t2)}, events={int(np.sum(e2 == 1))})",
|
|
184
|
+
"",
|
|
185
|
+
]
|
|
186
|
+
if np.isfinite(chi2):
|
|
187
|
+
lines += [f"χ²(1) = {chi2:.4f}", f"{format_p(p)} {significance_stars(p)}"]
|
|
188
|
+
else:
|
|
189
|
+
lines.append("χ² not defined (no variance: no informative event times).")
|
|
190
|
+
return AnalysisResult(
|
|
191
|
+
name=f"Log-rank: {label_a} vs {label_b}",
|
|
192
|
+
method="log-rank",
|
|
193
|
+
source_table=table.name,
|
|
194
|
+
summary_text="\n".join(lines),
|
|
195
|
+
details={"chi2": chi2, "p": p, **cnt},
|
|
196
|
+
)
|
staplot/stats/tests.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from scipy import stats
|
|
3
|
+
|
|
4
|
+
from ..models.project import DataTable, AnalysisResult
|
|
5
|
+
from .descriptive import describe, format_p, significance_stars
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _two_group_header(ga: str, da: dict, gb: str, db: dict, metric: str = "mean") -> list[str]:
|
|
9
|
+
return [
|
|
10
|
+
f"{'':30s} {ga:>15s} {gb:>15s}",
|
|
11
|
+
f"{'N':30s} {da['n']:>15d} {db['n']:>15d}",
|
|
12
|
+
f"{'Mean':30s} {da['mean']:>15.4f} {db['mean']:>15.4f}",
|
|
13
|
+
f"{'SD':30s} {da['sd']:>15.4f} {db['sd']:>15.4f}",
|
|
14
|
+
f"{'SEM':30s} {da['sem']:>15.4f} {db['sem']:>15.4f}",
|
|
15
|
+
f"{'Median':30s} {da['median']:>15.4f} {db['median']:>15.4f}",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def run_ttest(
|
|
20
|
+
table: DataTable,
|
|
21
|
+
group_a: str,
|
|
22
|
+
group_b: str,
|
|
23
|
+
paired: bool = False,
|
|
24
|
+
alternative: str = "two-sided",
|
|
25
|
+
) -> AnalysisResult:
|
|
26
|
+
if paired:
|
|
27
|
+
# complete subjects only: both measurements present in the same row
|
|
28
|
+
a, b = table.paired_arrays(group_a, group_b)
|
|
29
|
+
else:
|
|
30
|
+
groups = table.group_arrays()
|
|
31
|
+
a, b = groups[group_a], groups[group_b]
|
|
32
|
+
if len(a) < 2 or len(b) < 2:
|
|
33
|
+
raise ValueError("Each group needs at least 2 values"
|
|
34
|
+
+ (" (complete pairs)." if paired else "."))
|
|
35
|
+
|
|
36
|
+
if paired:
|
|
37
|
+
t_stat, p = stats.ttest_rel(a, b, alternative=alternative)
|
|
38
|
+
test_name = "Paired t-test"
|
|
39
|
+
else:
|
|
40
|
+
t_stat, p = stats.ttest_ind(a, b, equal_var=False, alternative=alternative)
|
|
41
|
+
test_name = "Unpaired t-test (Welch)"
|
|
42
|
+
|
|
43
|
+
da, db = describe(a), describe(b)
|
|
44
|
+
lines = [
|
|
45
|
+
f"=== {test_name} ===",
|
|
46
|
+
f"Groups: {group_a} vs {group_b}",
|
|
47
|
+
f"Alternative: {alternative}",
|
|
48
|
+
"",
|
|
49
|
+
*_two_group_header(group_a, da, group_b, db),
|
|
50
|
+
"",
|
|
51
|
+
f"t statistic: {t_stat:.4f}",
|
|
52
|
+
f"{format_p(p)} {significance_stars(p)}",
|
|
53
|
+
]
|
|
54
|
+
return AnalysisResult(
|
|
55
|
+
name=f"{test_name}: {group_a} vs {group_b}",
|
|
56
|
+
method="t-test",
|
|
57
|
+
source_table=table.name,
|
|
58
|
+
summary_text="\n".join(lines),
|
|
59
|
+
details={"t": float(t_stat), "p": float(p), "group_a": group_a, "group_b": group_b},
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def run_mann_whitney(
|
|
64
|
+
table: DataTable,
|
|
65
|
+
group_a: str,
|
|
66
|
+
group_b: str,
|
|
67
|
+
alternative: str = "two-sided",
|
|
68
|
+
) -> AnalysisResult:
|
|
69
|
+
groups = table.group_arrays()
|
|
70
|
+
a, b = groups[group_a], groups[group_b]
|
|
71
|
+
if len(a) < 1 or len(b) < 1:
|
|
72
|
+
raise ValueError("Each group needs at least 1 value.")
|
|
73
|
+
|
|
74
|
+
u_stat, p = stats.mannwhitneyu(a, b, alternative=alternative)
|
|
75
|
+
da, db = describe(a), describe(b)
|
|
76
|
+
lines = [
|
|
77
|
+
"=== Mann-Whitney U Test ===",
|
|
78
|
+
f"Groups: {group_a} vs {group_b}",
|
|
79
|
+
f"Alternative: {alternative}",
|
|
80
|
+
"",
|
|
81
|
+
*_two_group_header(group_a, da, group_b, db),
|
|
82
|
+
"",
|
|
83
|
+
f"U statistic: {u_stat:.0f}",
|
|
84
|
+
f"{format_p(p)} {significance_stars(p)}",
|
|
85
|
+
]
|
|
86
|
+
return AnalysisResult(
|
|
87
|
+
name=f"Mann-Whitney: {group_a} vs {group_b}",
|
|
88
|
+
method="mann-whitney",
|
|
89
|
+
source_table=table.name,
|
|
90
|
+
summary_text="\n".join(lines),
|
|
91
|
+
details={"U": float(u_stat), "p": float(p), "group_a": group_a, "group_b": group_b},
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def run_wilcoxon(
|
|
96
|
+
table: DataTable,
|
|
97
|
+
group_a: str,
|
|
98
|
+
group_b: str,
|
|
99
|
+
alternative: str = "two-sided",
|
|
100
|
+
) -> AnalysisResult:
|
|
101
|
+
a, b = table.paired_arrays(group_a, group_b)
|
|
102
|
+
if len(a) < 1:
|
|
103
|
+
raise ValueError("Wilcoxon signed-rank needs complete pairs (same row in both columns).")
|
|
104
|
+
|
|
105
|
+
w_stat, p = stats.wilcoxon(a, b, alternative=alternative)
|
|
106
|
+
lines = [
|
|
107
|
+
"=== Wilcoxon Signed-Rank Test ===",
|
|
108
|
+
f"Groups: {group_a} vs {group_b}",
|
|
109
|
+
f"Alternative: {alternative}",
|
|
110
|
+
"",
|
|
111
|
+
f"W statistic: {w_stat:.4f}",
|
|
112
|
+
f"{format_p(p)} {significance_stars(p)}",
|
|
113
|
+
]
|
|
114
|
+
return AnalysisResult(
|
|
115
|
+
name=f"Wilcoxon: {group_a} vs {group_b}",
|
|
116
|
+
method="wilcoxon",
|
|
117
|
+
source_table=table.name,
|
|
118
|
+
summary_text="\n".join(lines),
|
|
119
|
+
details={"W": float(w_stat), "p": float(p)},
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def run_descriptive(table: DataTable) -> AnalysisResult:
|
|
124
|
+
header = f"{'Group':20s} {'N':>6s} {'Mean':>12s} {'SD':>12s} {'SEM':>12s} {'Median':>12s} {'Min':>10s} {'Max':>10s}"
|
|
125
|
+
sep = "-" * len(header)
|
|
126
|
+
rows = []
|
|
127
|
+
for col in table.columns:
|
|
128
|
+
d = describe(col.valid_values())
|
|
129
|
+
if d["n"] == 0:
|
|
130
|
+
continue
|
|
131
|
+
rows.append(
|
|
132
|
+
f"{col.name:20s} {d['n']:>6d} {d['mean']:>12.4f} {d['sd']:>12.4f} "
|
|
133
|
+
f"{d['sem']:>12.4f} {d['median']:>12.4f} {d['min']:>10.4f} {d['max']:>10.4f}"
|
|
134
|
+
)
|
|
135
|
+
lines = [f"=== Descriptive Statistics: {table.name} ===", "", header, sep, *rows]
|
|
136
|
+
return AnalysisResult(
|
|
137
|
+
name=f"Descriptive: {table.name}",
|
|
138
|
+
method="descriptive",
|
|
139
|
+
source_table=table.name,
|
|
140
|
+
summary_text="\n".join(lines),
|
|
141
|
+
details={},
|
|
142
|
+
)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import statsmodels.formula.api as smf
|
|
3
|
+
from statsmodels.stats.anova import anova_lm
|
|
4
|
+
from statsmodels.stats.multicomp import pairwise_tukeyhsd
|
|
5
|
+
|
|
6
|
+
from ..models.project import GroupedDataTable, AnalysisResult
|
|
7
|
+
from .descriptive import format_p, significance_stars
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def run_two_way_anova(table: GroupedDataTable) -> AnalysisResult:
|
|
11
|
+
df = table.to_long_dataframe()
|
|
12
|
+
if df.empty:
|
|
13
|
+
raise ValueError("No numeric data in table.")
|
|
14
|
+
if df["factor_a"].nunique() < 2:
|
|
15
|
+
raise ValueError("Need at least 2 levels for Factor A (columns).")
|
|
16
|
+
|
|
17
|
+
model = smf.ols(
|
|
18
|
+
"value ~ C(factor_a) + C(factor_b) + C(factor_a):C(factor_b)", data=df
|
|
19
|
+
).fit()
|
|
20
|
+
anova_tbl = anova_lm(model, typ=2)
|
|
21
|
+
|
|
22
|
+
fa_label = "Factor A (columns)"
|
|
23
|
+
fb_label = "Factor B (rows)"
|
|
24
|
+
|
|
25
|
+
def _fmt_row(label: str, row) -> str:
|
|
26
|
+
f = row.get("F", np.nan)
|
|
27
|
+
p = row["PR(>F)"]
|
|
28
|
+
df_res = row.get("df", "")
|
|
29
|
+
return (
|
|
30
|
+
f" {label:40s} F = {f:8.3f} {format_p(p):15s} {significance_stars(p):4s}"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
anova_lines = []
|
|
34
|
+
row_labels = {
|
|
35
|
+
"C(factor_a)": fa_label,
|
|
36
|
+
"C(factor_b)": fb_label,
|
|
37
|
+
"C(factor_a):C(factor_b)": "Interaction (A × B)",
|
|
38
|
+
}
|
|
39
|
+
for key, lbl in row_labels.items():
|
|
40
|
+
if key in anova_tbl.index:
|
|
41
|
+
anova_lines.append(_fmt_row(lbl, anova_tbl.loc[key]))
|
|
42
|
+
|
|
43
|
+
# Tukey post-hoc for Factor A
|
|
44
|
+
tukey_lines: list[str] = []
|
|
45
|
+
if df["factor_a"].nunique() > 2:
|
|
46
|
+
tukey = pairwise_tukeyhsd(df["value"], df["factor_a"])
|
|
47
|
+
tukey_lines = ["", "Post-hoc Factor A (Tukey HSD):", str(tukey.summary())]
|
|
48
|
+
|
|
49
|
+
# Cell means table
|
|
50
|
+
means = df.groupby(["factor_a", "factor_b"])["value"].agg(["mean", "std", "count"])
|
|
51
|
+
cell_header = f"\n{'':5s}" + "".join(f"{c:>12s}" for c in table.col_groups)
|
|
52
|
+
cell_lines = [cell_header]
|
|
53
|
+
for rl in table.row_labels:
|
|
54
|
+
row_str = f"{rl:5s}"
|
|
55
|
+
for cg in table.col_groups:
|
|
56
|
+
try:
|
|
57
|
+
m = means.loc[(cg, rl), "mean"]
|
|
58
|
+
row_str += f"{m:>12.4f}"
|
|
59
|
+
except KeyError:
|
|
60
|
+
row_str += f"{'—':>12s}"
|
|
61
|
+
cell_lines.append(row_str)
|
|
62
|
+
|
|
63
|
+
lines = [
|
|
64
|
+
"=== Two-Way ANOVA ===",
|
|
65
|
+
f"Table: {table.name}",
|
|
66
|
+
f"Factor A (columns): {', '.join(table.col_groups)}",
|
|
67
|
+
f"Factor B (rows): {', '.join(table.row_labels)}",
|
|
68
|
+
"",
|
|
69
|
+
"ANOVA Table (Type II SS):",
|
|
70
|
+
*anova_lines,
|
|
71
|
+
"",
|
|
72
|
+
"Cell Means:",
|
|
73
|
+
*cell_lines,
|
|
74
|
+
*tukey_lines,
|
|
75
|
+
]
|
|
76
|
+
return AnalysisResult(
|
|
77
|
+
name=f"Two-Way ANOVA: {table.name}",
|
|
78
|
+
method="two-way-anova",
|
|
79
|
+
source_table=table.name,
|
|
80
|
+
summary_text="\n".join(lines),
|
|
81
|
+
details={
|
|
82
|
+
"fa_p": float(anova_tbl.loc["C(factor_a)", "PR(>F)"]) if "C(factor_a)" in anova_tbl.index else np.nan,
|
|
83
|
+
"fb_p": float(anova_tbl.loc["C(factor_b)", "PR(>F)"]) if "C(factor_b)" in anova_tbl.index else np.nan,
|
|
84
|
+
"interaction_p": float(anova_tbl.loc["C(factor_a):C(factor_b)", "PR(>F)"])
|
|
85
|
+
if "C(factor_a):C(factor_b)" in anova_tbl.index
|
|
86
|
+
else np.nan,
|
|
87
|
+
},
|
|
88
|
+
)
|
staplot/ui/__init__.py
ADDED
|
File without changes
|