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/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
staplot/api.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
"""UI-free façade over staplot's statistics + plotting engine.
|
|
2
|
+
|
|
3
|
+
This module is the *embedding* entry point for other tools (e.g. PyFigures) that
|
|
4
|
+
want to turn a CSV of measurements into a publication-styled plot panel with
|
|
5
|
+
automatic significance brackets — without launching the staplot GUI.
|
|
6
|
+
|
|
7
|
+
Import safety
|
|
8
|
+
-------------
|
|
9
|
+
It imports only ``numpy`` / ``scipy`` / ``pandas`` / ``matplotlib`` /
|
|
10
|
+
``statsmodels`` and staplot's *model* + *stats* + *plots* subpackages, none of
|
|
11
|
+
which touch Qt. ``import staplot.api`` therefore never pulls in a GUI toolkit and
|
|
12
|
+
is safe to run headless (e.g. inside a PyFigures ``custom_loading_script``).
|
|
13
|
+
|
|
14
|
+
Public API
|
|
15
|
+
----------
|
|
16
|
+
``table_from_csv`` / ``table_from_columns`` -> build a column DataTable
|
|
17
|
+
``grouped_table_from_csv`` -> build a two-factor GroupedDataTable
|
|
18
|
+
``auto_test`` -> pick + run the right test, return
|
|
19
|
+
machine-readable stats + sig_pairs
|
|
20
|
+
``plot`` -> render a Figure (+ stats record),
|
|
21
|
+
auto-annotated with brackets
|
|
22
|
+
|
|
23
|
+
The test-selection logic mirrors what a careful analyst would do by hand:
|
|
24
|
+
|
|
25
|
+
* **2 groups** normal -> Welch's t-test ; else Mann-Whitney U.
|
|
26
|
+
* **>2 groups** normal -> one-way ANOVA + Tukey HSD (family-wise corrected);
|
|
27
|
+
else Kruskal-Wallis + Dunn's test (Bonferroni-corrected).
|
|
28
|
+
|
|
29
|
+
Normality is judged per group with Shapiro-Wilk; any group failing drops the
|
|
30
|
+
comparison to the non-parametric branch. When normality *cannot* be tested
|
|
31
|
+
(some group has n<3) the parametric branch is used and the record says so: rank
|
|
32
|
+
tests are powerless at such n (Mann-Whitney 3 vs 3 can never reach p<0.05), so
|
|
33
|
+
defaulting to them would silently hide every effect.
|
|
34
|
+
|
|
35
|
+
For >2 groups, post-hoc brackets are only drawn when the omnibus test
|
|
36
|
+
(ANOVA / Kruskal-Wallis) is significant; all pairwise p-values are still
|
|
37
|
+
reported in ``comparisons``.
|
|
38
|
+
"""
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import itertools
|
|
42
|
+
import os
|
|
43
|
+
|
|
44
|
+
import numpy as np
|
|
45
|
+
from scipy import stats as _sp
|
|
46
|
+
|
|
47
|
+
from .models.project import DataTable, GroupedDataTable
|
|
48
|
+
from .stats.descriptive import describe, significance_stars, format_p
|
|
49
|
+
from .stats.tests import run_ttest, run_mann_whitney
|
|
50
|
+
from . import plots as _plots
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"table_from_columns",
|
|
54
|
+
"table_from_csv",
|
|
55
|
+
"grouped_table_from_csv",
|
|
56
|
+
"auto_test",
|
|
57
|
+
"plot",
|
|
58
|
+
"PLOT_KINDS",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
PLOT_KINDS = ("bar", "box", "violin", "scatter", "grouped")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ---------------------------------------------------------------------------
|
|
65
|
+
# Table builders
|
|
66
|
+
# ---------------------------------------------------------------------------
|
|
67
|
+
def _to_float_or_none(v):
|
|
68
|
+
if v is None:
|
|
69
|
+
return None
|
|
70
|
+
try:
|
|
71
|
+
f = float(v)
|
|
72
|
+
except (TypeError, ValueError):
|
|
73
|
+
return None
|
|
74
|
+
return None if np.isnan(f) else f
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def table_from_columns(columns: dict, name: str = "data") -> DataTable:
|
|
78
|
+
"""Build a column DataTable from ``{group_name: [values...]}``."""
|
|
79
|
+
t = DataTable(str(name))
|
|
80
|
+
for cname, vals in columns.items():
|
|
81
|
+
col = t.add_column(str(cname))
|
|
82
|
+
col.values = [_to_float_or_none(v) for v in vals]
|
|
83
|
+
return t
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def csv_format(sample: str) -> tuple[str, str]:
|
|
87
|
+
"""(separator, decimal mark) of a CSV from its first lines: ';' or tab when
|
|
88
|
+
every line has the same number of them (Excel in French, German... writes
|
|
89
|
+
``1,5;2,5``), with a decimal comma when the numbers use one; else ','."""
|
|
90
|
+
import re
|
|
91
|
+
lines = [ln for ln in sample.splitlines()[:20] if ln.strip()]
|
|
92
|
+
if len(lines) > 1 and not sample.endswith("\n"):
|
|
93
|
+
lines = lines[:-1] # the sample may cut the last line
|
|
94
|
+
for sep in (";", "\t"):
|
|
95
|
+
counts = {ln.count(sep) for ln in lines}
|
|
96
|
+
if lines and len(counts) == 1 and counts.pop() > 0:
|
|
97
|
+
return sep, ("," if re.search(r"\d,\d", sample) else ".")
|
|
98
|
+
return ",", "."
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _read_csv(path):
|
|
102
|
+
import pandas as pd
|
|
103
|
+
with open(path, encoding="utf-8-sig", errors="replace", newline="") as f:
|
|
104
|
+
sep, decimal = csv_format(f.read(4096))
|
|
105
|
+
return pd.read_csv(path, sep=sep, decimal=decimal, encoding="utf-8-sig")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def table_from_csv(path: str, layout: str = "auto", name: str | None = None) -> DataTable:
|
|
109
|
+
"""Build a column DataTable from a CSV.
|
|
110
|
+
|
|
111
|
+
*layout*:
|
|
112
|
+
- ``"wide"`` — every column is a group; rows are replicates (Prism-style).
|
|
113
|
+
- ``"long"`` — first column = group label, second column = value.
|
|
114
|
+
- ``"auto"`` — long when there are exactly two columns and the first is
|
|
115
|
+
non-numeric; wide otherwise.
|
|
116
|
+
"""
|
|
117
|
+
import pandas as pd
|
|
118
|
+
df = _read_csv(path)
|
|
119
|
+
nm = name or os.path.splitext(os.path.basename(str(path)))[0]
|
|
120
|
+
if df.shape[1] == 0:
|
|
121
|
+
return DataTable(nm)
|
|
122
|
+
|
|
123
|
+
if layout == "auto":
|
|
124
|
+
first_numeric = pd.to_numeric(df.iloc[:, 0], errors="coerce").notna().mean()
|
|
125
|
+
layout = "long" if (df.shape[1] == 2 and first_numeric < 0.5) else "wide"
|
|
126
|
+
|
|
127
|
+
if layout == "long":
|
|
128
|
+
gcol, vcol = df.columns[0], df.columns[1]
|
|
129
|
+
vals = pd.to_numeric(df[vcol], errors="coerce")
|
|
130
|
+
columns: dict = {}
|
|
131
|
+
for g, v in zip(df[gcol].astype(str), vals):
|
|
132
|
+
columns.setdefault(g, []).append(v)
|
|
133
|
+
return table_from_columns(columns, name=nm)
|
|
134
|
+
|
|
135
|
+
# wide
|
|
136
|
+
columns = {}
|
|
137
|
+
for c in df.columns:
|
|
138
|
+
columns[str(c)] = pd.to_numeric(df[c], errors="coerce").tolist()
|
|
139
|
+
return table_from_columns(columns, name=nm)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def grouped_table_from_csv(path: str, name: str | None = None) -> GroupedDataTable:
|
|
143
|
+
"""Build a two-factor GroupedDataTable from a *long* CSV with three columns:
|
|
144
|
+
``factor_a`` (column group), ``factor_b`` (row label), ``value``."""
|
|
145
|
+
import pandas as pd
|
|
146
|
+
df = _read_csv(path)
|
|
147
|
+
nm = name or os.path.splitext(os.path.basename(str(path)))[0]
|
|
148
|
+
if df.shape[1] < 3:
|
|
149
|
+
raise ValueError("grouped plot needs a long CSV with 3 columns: "
|
|
150
|
+
"factor_a, factor_b, value")
|
|
151
|
+
fa, fb, val = df.columns[0], df.columns[1], df.columns[2]
|
|
152
|
+
values = pd.to_numeric(df[val], errors="coerce")
|
|
153
|
+
|
|
154
|
+
def numeric_share(col):
|
|
155
|
+
return pd.to_numeric(df[col], errors="coerce").notna().mean()
|
|
156
|
+
# a wide table (one column per condition) read as long gives a nonsense
|
|
157
|
+
# plot and a degenerate ANOVA instead of an error
|
|
158
|
+
if values.notna().mean() < 0.5 or numeric_share(fa) > 0.5 or numeric_share(fb) > 0.5:
|
|
159
|
+
raise ValueError(
|
|
160
|
+
"grouped plot needs a long CSV: one row per measurement, with columns "
|
|
161
|
+
"factor_a (text), factor_b (text), value (number), e.g. 'Genotype,Day,Length' "
|
|
162
|
+
"then 'WT,Day 1,10.2'; this file's first three columns are "
|
|
163
|
+
f"{', '.join(map(str, df.columns[:3]))}")
|
|
164
|
+
# count replicates per (a, b) so n_reps is large enough for every cell
|
|
165
|
+
cells: dict = {}
|
|
166
|
+
for a, b, v in zip(df[fa].astype(str), df[fb].astype(str), values):
|
|
167
|
+
cells.setdefault((a, b), []).append(_to_float_or_none(v))
|
|
168
|
+
n_reps = max((len(v) for v in cells.values()), default=1)
|
|
169
|
+
t = GroupedDataTable(nm, n_reps=n_reps)
|
|
170
|
+
for a in df[fa].astype(str):
|
|
171
|
+
t.add_col_group(a)
|
|
172
|
+
for b in df[fb].astype(str):
|
|
173
|
+
t.add_row_label(b)
|
|
174
|
+
for (a, b), vs in cells.items():
|
|
175
|
+
for rep, v in enumerate(vs):
|
|
176
|
+
t.set_value(a, b, rep, v)
|
|
177
|
+
return t
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---------------------------------------------------------------------------
|
|
181
|
+
# Automatic test selection
|
|
182
|
+
# ---------------------------------------------------------------------------
|
|
183
|
+
def _normality_testable(arr: np.ndarray) -> bool:
|
|
184
|
+
"""Shapiro-Wilk needs n>=3 and some spread."""
|
|
185
|
+
arr = arr[~np.isnan(arr)]
|
|
186
|
+
return len(arr) >= 3 and float(np.std(arr, ddof=1)) > 0.0
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _min_mann_whitney_p(n1: int, n2: int) -> float:
|
|
190
|
+
"""Smallest two-sided exact p-value Mann-Whitney U can produce for n1 vs n2
|
|
191
|
+
(both samples completely separated): 2 / C(n1+n2, n1)."""
|
|
192
|
+
from math import comb
|
|
193
|
+
return min(1.0, 2.0 / comb(n1 + n2, n1))
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _is_normal(arr: np.ndarray) -> bool:
|
|
197
|
+
arr = arr[~np.isnan(arr)]
|
|
198
|
+
if len(arr) < 3:
|
|
199
|
+
return False
|
|
200
|
+
if float(np.std(arr, ddof=1)) == 0.0:
|
|
201
|
+
return False
|
|
202
|
+
try:
|
|
203
|
+
_, p = _sp.shapiro(arr)
|
|
204
|
+
except Exception:
|
|
205
|
+
return False
|
|
206
|
+
return bool(p > 0.05)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _tukey_pairs(names, arrays):
|
|
210
|
+
"""Return [(name_a, name_b, p_adj), ...] from Tukey HSD (already corrected)."""
|
|
211
|
+
from statsmodels.stats.multicomp import pairwise_tukeyhsd
|
|
212
|
+
all_vals = np.concatenate(arrays)
|
|
213
|
+
all_labels = np.concatenate([[n] * len(a) for n, a in zip(names, arrays)])
|
|
214
|
+
res = pairwise_tukeyhsd(all_vals, all_labels)
|
|
215
|
+
groups_sorted = list(res.groupsunique)
|
|
216
|
+
pairs = list(itertools.combinations(groups_sorted, 2))
|
|
217
|
+
return [(str(a), str(b), float(p)) for (a, b), p in zip(pairs, res.pvalues)]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _dunn_pairs(names, arrays):
|
|
221
|
+
"""Dunn's test after Kruskal-Wallis, Bonferroni-corrected (see
|
|
222
|
+
stats.anova.dunn_test). Previously this ran separate pairwise Mann-Whitney
|
|
223
|
+
tests — a different procedure from the "Dunn" reported in Methods text."""
|
|
224
|
+
from .stats.anova import dunn_test
|
|
225
|
+
return [(str(names[i]), str(names[j]), float(p)) for i, j, p in dunn_test(arrays)]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def auto_test(table: DataTable, only_significant: bool = True,
|
|
229
|
+
parametric: bool | None = None) -> dict:
|
|
230
|
+
"""Pick and run the appropriate comparison for *table*'s groups.
|
|
231
|
+
|
|
232
|
+
Returns a JSON-serialisable dict with the chosen test, omnibus result (for
|
|
233
|
+
>2 groups), a per-group descriptive summary, every pairwise comparison, and
|
|
234
|
+
``sig_pairs`` (``[(a, b, p), ...]``) ready to hand to a plotter. When
|
|
235
|
+
*only_significant* is True (default) ``sig_pairs`` keeps only p<0.05 pairs so
|
|
236
|
+
the figure isn't cluttered with 'ns' brackets; the full set is always in
|
|
237
|
+
``comparisons``.
|
|
238
|
+
|
|
239
|
+
*parametric*: ``None`` (default) chooses parametric vs non-parametric from a
|
|
240
|
+
per-group Shapiro normality check; ``True`` forces the parametric branch
|
|
241
|
+
(t-test / ANOVA), ``False`` forces the non-parametric branch (Mann-Whitney /
|
|
242
|
+
Kruskal).
|
|
243
|
+
"""
|
|
244
|
+
groups = table.group_arrays()
|
|
245
|
+
names = [n for n in groups if len(groups[n]) > 0]
|
|
246
|
+
arrays = [np.asarray(groups[n], dtype=float) for n in names]
|
|
247
|
+
k = len(names)
|
|
248
|
+
|
|
249
|
+
rec: dict = {
|
|
250
|
+
"n_groups": k,
|
|
251
|
+
"groups": {n: describe(a) for n, a in zip(names, arrays)},
|
|
252
|
+
"test": "none",
|
|
253
|
+
"omnibus": None,
|
|
254
|
+
"correction": None,
|
|
255
|
+
"comparisons": [],
|
|
256
|
+
"sig_pairs": [],
|
|
257
|
+
}
|
|
258
|
+
if k < 2 or any(len(a) < 2 for a in arrays):
|
|
259
|
+
rec["note"] = "Need at least 2 groups with >=2 values each."
|
|
260
|
+
return rec
|
|
261
|
+
|
|
262
|
+
warnings: list[str] = []
|
|
263
|
+
if parametric is None:
|
|
264
|
+
if all(_normality_testable(a) for a in arrays):
|
|
265
|
+
normal = all(_is_normal(a) for a in arrays)
|
|
266
|
+
rec["normality"] = "normal" if normal else "non-normal"
|
|
267
|
+
else:
|
|
268
|
+
# can't test normality (n<3 or no spread): a rank test would be
|
|
269
|
+
# powerless here, so assume normality and say so
|
|
270
|
+
normal = True
|
|
271
|
+
rec["normality"] = "untestable (n<3 or constant group); normality assumed"
|
|
272
|
+
warnings.append("Normality could not be tested (a group has n<3 or no "
|
|
273
|
+
"variance); the parametric test was used.")
|
|
274
|
+
else:
|
|
275
|
+
normal = bool(parametric)
|
|
276
|
+
rec["normality"] = "forced-parametric" if normal else "forced-nonparametric"
|
|
277
|
+
|
|
278
|
+
omnibus_sig = True
|
|
279
|
+
if k == 2:
|
|
280
|
+
if normal:
|
|
281
|
+
r = run_ttest(table, names[0], names[1])
|
|
282
|
+
rec["test"] = "Welch's t-test"
|
|
283
|
+
else:
|
|
284
|
+
r = run_mann_whitney(table, names[0], names[1])
|
|
285
|
+
rec["test"] = "Mann-Whitney U test"
|
|
286
|
+
p_floor = _min_mann_whitney_p(len(arrays[0]), len(arrays[1]))
|
|
287
|
+
if p_floor >= 0.05:
|
|
288
|
+
warnings.append(
|
|
289
|
+
f"With n={len(arrays[0])} vs n={len(arrays[1])}, Mann-Whitney "
|
|
290
|
+
f"cannot reach p<0.05 (smallest possible p={p_floor:.3g}); "
|
|
291
|
+
"absence of a bracket is not evidence of no effect.")
|
|
292
|
+
p = float(r.details["p"])
|
|
293
|
+
rec["comparisons"] = [_cmp(names[0], names[1], p)]
|
|
294
|
+
else:
|
|
295
|
+
if normal:
|
|
296
|
+
F, p_omni = _sp.f_oneway(*arrays)
|
|
297
|
+
rec["test"] = "One-way ANOVA + Tukey HSD"
|
|
298
|
+
rec["omnibus"] = {"stat_name": "F", "stat": float(F), "p": float(p_omni)}
|
|
299
|
+
rec["correction"] = "Tukey HSD (family-wise)"
|
|
300
|
+
pairs = _tukey_pairs(names, arrays)
|
|
301
|
+
else:
|
|
302
|
+
H, p_omni = _sp.kruskal(*arrays)
|
|
303
|
+
rec["test"] = "Kruskal-Wallis + Dunn's test"
|
|
304
|
+
rec["omnibus"] = {"stat_name": "H", "stat": float(H), "p": float(p_omni)}
|
|
305
|
+
rec["correction"] = "Bonferroni"
|
|
306
|
+
pairs = _dunn_pairs(names, arrays)
|
|
307
|
+
rec["comparisons"] = [_cmp(a, b, p) for a, b, p in pairs]
|
|
308
|
+
omnibus_sig = bool(np.isfinite(p_omni) and p_omni < 0.05)
|
|
309
|
+
rec["posthoc_shown"] = omnibus_sig
|
|
310
|
+
if not omnibus_sig:
|
|
311
|
+
warnings.append("Omnibus test not significant (p="
|
|
312
|
+
f"{format_p(float(p_omni))}); post-hoc brackets are not drawn.")
|
|
313
|
+
|
|
314
|
+
sig = [(c["a"], c["b"], c["p"]) for c in rec["comparisons"]
|
|
315
|
+
if omnibus_sig and not np.isnan(c["p"])
|
|
316
|
+
and (c["p"] < 0.05 or not only_significant)]
|
|
317
|
+
rec["sig_pairs"] = sig
|
|
318
|
+
if warnings:
|
|
319
|
+
rec["warnings"] = warnings
|
|
320
|
+
return rec
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _cmp(a, b, p):
|
|
324
|
+
return {"a": str(a), "b": str(b), "p": float(p),
|
|
325
|
+
"stars": significance_stars(p), "p_text": format_p(p)}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def two_way_test(gtable: GroupedDataTable) -> dict:
|
|
329
|
+
"""Run a two-way ANOVA on a GroupedDataTable and return the main effects and
|
|
330
|
+
interaction as a machine-readable record (for grouped-bar panels)."""
|
|
331
|
+
from .stats.two_way_anova import run_two_way_anova
|
|
332
|
+
rec: dict = {"test": "Two-way ANOVA", "effects": []}
|
|
333
|
+
try:
|
|
334
|
+
r = run_two_way_anova(gtable)
|
|
335
|
+
except Exception as e:
|
|
336
|
+
rec["error"] = f"{type(e).__name__}: {e}"
|
|
337
|
+
return rec
|
|
338
|
+
d = r.details
|
|
339
|
+
for key, lbl in (("fa_p", "factor A"), ("fb_p", "factor B"),
|
|
340
|
+
("interaction_p", "A x B")):
|
|
341
|
+
p = d.get(key)
|
|
342
|
+
pf = None if (p is None or (isinstance(p, float) and np.isnan(p))) else float(p)
|
|
343
|
+
rec["effects"].append({"effect": lbl, "p": pf,
|
|
344
|
+
"stars": significance_stars(pf) if pf is not None else "n/a"})
|
|
345
|
+
return rec
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def correlation_test(table: DataTable, method: str = "pearson") -> dict:
|
|
349
|
+
"""Correlate the first two numeric columns of *table* (x, y) — for scatter
|
|
350
|
+
panels. Returns r, r^2, p, n."""
|
|
351
|
+
from .stats.correlation import run_correlation
|
|
352
|
+
names = [c.name for c in table.columns if len(c.valid_values()) > 0]
|
|
353
|
+
rec: dict = {"test": f"{method.capitalize()} correlation"}
|
|
354
|
+
if len(names) < 2:
|
|
355
|
+
rec["error"] = "need at least 2 columns (x, y)"
|
|
356
|
+
return rec
|
|
357
|
+
try:
|
|
358
|
+
r = run_correlation(table, names[0], names[1], method=method)
|
|
359
|
+
except Exception as e:
|
|
360
|
+
rec["error"] = f"{type(e).__name__}: {e}"
|
|
361
|
+
return rec
|
|
362
|
+
d = r.details
|
|
363
|
+
rec.update({"x": names[0], "y": names[1], "r": d["r"], "r2": d["r2"],
|
|
364
|
+
"p": d["p"], "n": d["n"], "stars": significance_stars(d["p"])})
|
|
365
|
+
return rec
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _annotate_two_way(fig, rec):
|
|
369
|
+
parts = []
|
|
370
|
+
for e in rec.get("effects", []):
|
|
371
|
+
if e["p"] is None:
|
|
372
|
+
continue
|
|
373
|
+
tail = "" if e["stars"] in ("ns", "n/a") else " " + e["stars"]
|
|
374
|
+
parts.append(f"{e['effect']}: p={e['p']:.3g}{tail}")
|
|
375
|
+
if parts:
|
|
376
|
+
fig.text(0.5, 0.005, "Two-way ANOVA — " + "; ".join(parts),
|
|
377
|
+
ha="center", va="bottom", fontsize=7, color="#444444")
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# ---------------------------------------------------------------------------
|
|
381
|
+
# Plotting
|
|
382
|
+
# ---------------------------------------------------------------------------
|
|
383
|
+
_STATS_MODE = {"auto": None, "parametric": True, "nonparametric": False}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
@_plots.styles.styled # the two-way ANOVA note is added after the plot is built
|
|
387
|
+
def plot(table, kind: str = "bar", *, error: str = "sem", annotate: bool = True,
|
|
388
|
+
only_significant: bool = True, stats_mode: str = "auto", title: str = "",
|
|
389
|
+
ylabel: str = "", xlabel: str = "", colors=None, show_title: bool = True):
|
|
390
|
+
"""Render *table* to a matplotlib Figure and return ``(fig, stats_record)``.
|
|
391
|
+
|
|
392
|
+
*kind*: ``"bar"`` | ``"box"`` | ``"violin"`` | ``"scatter"`` | ``"grouped"``.
|
|
393
|
+
When *annotate* is set:
|
|
394
|
+
* bar/box/violin — groups compared with :func:`auto_test`; significant
|
|
395
|
+
pairs drawn as brackets.
|
|
396
|
+
* grouped — two-way ANOVA (:func:`two_way_test`); main effects + interaction
|
|
397
|
+
printed under the axes.
|
|
398
|
+
* scatter — correlation of the first two columns (:func:`correlation_test`);
|
|
399
|
+
R^2/p already shown in the plot legend.
|
|
400
|
+
|
|
401
|
+
*stats_mode*: ``"auto"`` (normality-based), ``"parametric"``, or
|
|
402
|
+
``"nonparametric"`` — forces the test family for group comparisons.
|
|
403
|
+
|
|
404
|
+
*show_title*: False draws no title unless *title* is given (otherwise the
|
|
405
|
+
table name is used) — journals rarely want titles on figure panels.
|
|
406
|
+
"""
|
|
407
|
+
kind = kind.lower()
|
|
408
|
+
if kind not in PLOT_KINDS:
|
|
409
|
+
raise ValueError(f"unknown plot kind {kind!r}; expected one of {PLOT_KINDS}")
|
|
410
|
+
parametric = _STATS_MODE.get(stats_mode, None)
|
|
411
|
+
|
|
412
|
+
stats_record = None
|
|
413
|
+
sig_pairs = None
|
|
414
|
+
if annotate and kind in ("bar", "box", "violin"):
|
|
415
|
+
stats_record = auto_test(table, only_significant=only_significant,
|
|
416
|
+
parametric=parametric)
|
|
417
|
+
sig_pairs = stats_record["sig_pairs"] or None
|
|
418
|
+
|
|
419
|
+
if kind == "bar":
|
|
420
|
+
fig = _plots.plot_bar(table, error_type=error, title=title, ylabel=ylabel,
|
|
421
|
+
colors=colors, sig_pairs=sig_pairs)
|
|
422
|
+
elif kind in ("box", "violin"):
|
|
423
|
+
fig = _plots.plot_box(table, plot_type=kind, title=title, ylabel=ylabel,
|
|
424
|
+
colors=colors, sig_pairs=sig_pairs)
|
|
425
|
+
elif kind == "scatter":
|
|
426
|
+
fig = _plots.plot_scatter(table, title=title, xlabel=xlabel, ylabel=ylabel,
|
|
427
|
+
colors=colors)
|
|
428
|
+
if annotate:
|
|
429
|
+
stats_record = correlation_test(table)
|
|
430
|
+
elif kind == "grouped":
|
|
431
|
+
fig = _plots.plot_grouped_bar(table, error_type=error, title=title,
|
|
432
|
+
ylabel=ylabel, colors=colors)
|
|
433
|
+
if annotate:
|
|
434
|
+
stats_record = two_way_test(table)
|
|
435
|
+
if "error" not in stats_record:
|
|
436
|
+
_annotate_two_way(fig, stats_record)
|
|
437
|
+
if not show_title and not title:
|
|
438
|
+
for ax in fig.axes:
|
|
439
|
+
ax.set_title("")
|
|
440
|
+
fig.tight_layout() # give the title's room back to the axes
|
|
441
|
+
return fig, stats_record
|
staplot/main.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
os.environ.setdefault("QT_API", "pyqt6")
|
|
5
|
+
|
|
6
|
+
from qtpy.QtWidgets import QApplication
|
|
7
|
+
from .ui.main_window import MainWindow
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def main():
|
|
11
|
+
app = QApplication.instance() or QApplication(sys.argv)
|
|
12
|
+
app.setApplicationName("Staplot")
|
|
13
|
+
app.setOrganizationName("Staplot")
|
|
14
|
+
app.setStyle("Fusion")
|
|
15
|
+
window = MainWindow()
|
|
16
|
+
window.show()
|
|
17
|
+
sys.exit(app.exec())
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
if __name__ == "__main__":
|
|
21
|
+
main()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .project import DataColumn, DataTable, GroupedDataTable, AnalysisResult, GraphConfig, Project
|