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
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def unique_name(name: str, taken) -> str:
|
|
12
|
+
"""*name*, or *name* (2), (3)… if already in *taken*."""
|
|
13
|
+
taken = set(taken)
|
|
14
|
+
if name not in taken:
|
|
15
|
+
return name
|
|
16
|
+
k = 2
|
|
17
|
+
while f"{name} ({k})" in taken:
|
|
18
|
+
k += 1
|
|
19
|
+
return f"{name} ({k})"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DataColumn:
|
|
23
|
+
def __init__(self, name: str, values: list | None = None):
|
|
24
|
+
self.name = name
|
|
25
|
+
self.values: list = values if values is not None else []
|
|
26
|
+
self.excluded: set[int] = set() # row indices excluded by the user
|
|
27
|
+
|
|
28
|
+
@staticmethod
|
|
29
|
+
def _num(v) -> float:
|
|
30
|
+
"""Cell → float; empty or non-numeric (e.g. a text label column) → NaN."""
|
|
31
|
+
if v is None:
|
|
32
|
+
return float("nan")
|
|
33
|
+
try:
|
|
34
|
+
return float(v)
|
|
35
|
+
except (TypeError, ValueError):
|
|
36
|
+
return float("nan")
|
|
37
|
+
|
|
38
|
+
def as_array(self) -> np.ndarray:
|
|
39
|
+
return np.array([self._num(v) for v in self.values], dtype=float)
|
|
40
|
+
|
|
41
|
+
def valid_values(self) -> np.ndarray:
|
|
42
|
+
arr = self.as_array()
|
|
43
|
+
mask = ~np.isnan(arr)
|
|
44
|
+
if self.excluded:
|
|
45
|
+
for idx in self.excluded:
|
|
46
|
+
if 0 <= idx < len(mask):
|
|
47
|
+
mask[idx] = False
|
|
48
|
+
return arr[mask]
|
|
49
|
+
|
|
50
|
+
def valid_values_with_indices(self) -> tuple[np.ndarray, list[int]]:
|
|
51
|
+
"""Return (values, original_row_indices) skipping NaN and excluded rows."""
|
|
52
|
+
result_vals: list[float] = []
|
|
53
|
+
result_idxs: list[int] = []
|
|
54
|
+
for i, v in enumerate(self.values):
|
|
55
|
+
if i in self.excluded:
|
|
56
|
+
continue
|
|
57
|
+
f = self._num(v)
|
|
58
|
+
if not np.isnan(f):
|
|
59
|
+
result_vals.append(f)
|
|
60
|
+
result_idxs.append(i)
|
|
61
|
+
return np.array(result_vals, dtype=float), result_idxs
|
|
62
|
+
|
|
63
|
+
def toggle_excluded(self, row: int):
|
|
64
|
+
if row in self.excluded:
|
|
65
|
+
self.excluded.discard(row)
|
|
66
|
+
else:
|
|
67
|
+
self.excluded.add(row)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class DataTable:
|
|
71
|
+
"""Spreadsheet-like data container matching Prism's Column format."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, name: str, table_type: str = "column"):
|
|
74
|
+
self.name = name
|
|
75
|
+
self.table_type = table_type # "column" | "xy"
|
|
76
|
+
self.columns: list[DataColumn] = []
|
|
77
|
+
|
|
78
|
+
# ------------------------------------------------------------------
|
|
79
|
+
def add_column(self, name: str | None = None) -> DataColumn:
|
|
80
|
+
"""Column names are the keys analyses use, so they are kept unique:
|
|
81
|
+
a taken name gets a ' (2)', ' (3)'… suffix."""
|
|
82
|
+
if name is None:
|
|
83
|
+
name = f"Group {len(self.columns) + 1}"
|
|
84
|
+
col = DataColumn(name=unique_name(name, [c.name for c in self.columns]))
|
|
85
|
+
self.columns.append(col)
|
|
86
|
+
return col
|
|
87
|
+
|
|
88
|
+
def remove_column(self, index: int):
|
|
89
|
+
if 0 <= index < len(self.columns):
|
|
90
|
+
self.columns.pop(index)
|
|
91
|
+
|
|
92
|
+
def rename_column(self, index: int, new_name: str):
|
|
93
|
+
if 0 <= index < len(self.columns):
|
|
94
|
+
if any(c.name == new_name for i, c in enumerate(self.columns) if i != index):
|
|
95
|
+
raise ValueError(f"A column named '{new_name}' already exists.")
|
|
96
|
+
self.columns[index].name = new_name
|
|
97
|
+
|
|
98
|
+
def num_rows(self) -> int:
|
|
99
|
+
if not self.columns:
|
|
100
|
+
return 0
|
|
101
|
+
return max(len(c.values) for c in self.columns)
|
|
102
|
+
|
|
103
|
+
def ensure_row(self, row: int):
|
|
104
|
+
for col in self.columns:
|
|
105
|
+
while len(col.values) <= row:
|
|
106
|
+
col.values.append(None)
|
|
107
|
+
|
|
108
|
+
def set_value(self, row: int, col_index: int, value):
|
|
109
|
+
self.ensure_row(row)
|
|
110
|
+
col = self.columns[col_index]
|
|
111
|
+
col.values[row] = value
|
|
112
|
+
|
|
113
|
+
def to_dataframe(self) -> pd.DataFrame:
|
|
114
|
+
if not self.columns:
|
|
115
|
+
return pd.DataFrame()
|
|
116
|
+
n = self.num_rows()
|
|
117
|
+
data = {}
|
|
118
|
+
for col in self.columns:
|
|
119
|
+
vals = list(col.values) + [np.nan] * (n - len(col.values))
|
|
120
|
+
data[col.name] = vals
|
|
121
|
+
return pd.DataFrame(data)
|
|
122
|
+
|
|
123
|
+
def group_arrays(self) -> dict[str, np.ndarray]:
|
|
124
|
+
"""Each column's valid values, filtered independently — for UNPAIRED
|
|
125
|
+
comparisons only. Paired analyses must use paired_arrays()."""
|
|
126
|
+
return {col.name: col.valid_values() for col in self.columns}
|
|
127
|
+
|
|
128
|
+
def get_column(self, name: str) -> DataColumn | None:
|
|
129
|
+
return next((c for c in self.columns if c.name == name), None)
|
|
130
|
+
|
|
131
|
+
def paired_arrays(self, *names: str) -> list[np.ndarray]:
|
|
132
|
+
"""Values of the named columns restricted to the rows that are valid
|
|
133
|
+
(present, numeric, not excluded) in ALL of them, so element i of every
|
|
134
|
+
array comes from the same original row (subject / x-y pair)."""
|
|
135
|
+
cols = []
|
|
136
|
+
for nm in names:
|
|
137
|
+
col = self.get_column(nm)
|
|
138
|
+
if col is None:
|
|
139
|
+
raise ValueError(f"Column '{nm}' not found.")
|
|
140
|
+
cols.append(col)
|
|
141
|
+
rows = None
|
|
142
|
+
per_col = []
|
|
143
|
+
for col in cols:
|
|
144
|
+
vals, idx = col.valid_values_with_indices()
|
|
145
|
+
per_col.append(dict(zip(idx, vals)))
|
|
146
|
+
rows = set(idx) if rows is None else rows & set(idx)
|
|
147
|
+
rows = sorted(rows or [])
|
|
148
|
+
return [np.array([d[r] for r in rows], dtype=float) for d in per_col]
|
|
149
|
+
|
|
150
|
+
def analysis_dataframe(self) -> pd.DataFrame:
|
|
151
|
+
"""to_dataframe() with excluded cells masked to NaN (row alignment kept),
|
|
152
|
+
for analyses; to_dataframe() stays the raw data for export."""
|
|
153
|
+
df = self.to_dataframe()
|
|
154
|
+
for col in self.columns:
|
|
155
|
+
for idx in col.excluded:
|
|
156
|
+
if 0 <= idx < len(df):
|
|
157
|
+
df.loc[idx, col.name] = np.nan
|
|
158
|
+
return df
|
|
159
|
+
|
|
160
|
+
# ------------------------------------------------------------------
|
|
161
|
+
def to_dict(self) -> dict:
|
|
162
|
+
return {
|
|
163
|
+
"name": self.name,
|
|
164
|
+
"table_type": self.table_type,
|
|
165
|
+
"columns": [
|
|
166
|
+
{"name": c.name, "values": c.values, "excluded": list(c.excluded)}
|
|
167
|
+
for c in self.columns
|
|
168
|
+
],
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
@classmethod
|
|
172
|
+
def from_dict(cls, d: dict) -> DataTable:
|
|
173
|
+
t = cls(d["name"], d.get("table_type", "column"))
|
|
174
|
+
for cd in d.get("columns", []):
|
|
175
|
+
col = DataColumn(name=cd["name"], values=cd["values"])
|
|
176
|
+
col.excluded = set(cd.get("excluded", []))
|
|
177
|
+
t.columns.append(col)
|
|
178
|
+
return t
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class GroupedDataTable:
|
|
182
|
+
"""
|
|
183
|
+
Prism-style Grouped data table.
|
|
184
|
+
Factor A = column groups (col_groups).
|
|
185
|
+
Factor B = row labels (row_labels).
|
|
186
|
+
Each cell contains n_reps replicates.
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
def __init__(self, name: str, n_reps: int = 3):
|
|
190
|
+
self.name = name
|
|
191
|
+
self.table_type = "grouped"
|
|
192
|
+
self.col_groups: list[str] = []
|
|
193
|
+
self.row_labels: list[str] = []
|
|
194
|
+
self.n_reps: int = n_reps
|
|
195
|
+
self.data: dict[str, dict[str, list]] = {}
|
|
196
|
+
# data[col_group][row_label] = [val0, val1, …]
|
|
197
|
+
|
|
198
|
+
def add_col_group(self, name: str):
|
|
199
|
+
if name not in self.col_groups:
|
|
200
|
+
self.col_groups.append(name)
|
|
201
|
+
self.data[name] = {rl: [None] * self.n_reps for rl in self.row_labels}
|
|
202
|
+
|
|
203
|
+
def add_row_label(self, name: str):
|
|
204
|
+
if name not in self.row_labels:
|
|
205
|
+
self.row_labels.append(name)
|
|
206
|
+
for cg in self.col_groups:
|
|
207
|
+
self.data.setdefault(cg, {})[name] = [None] * self.n_reps
|
|
208
|
+
|
|
209
|
+
def set_value(self, col_group: str, row_label: str, rep: int, value):
|
|
210
|
+
cell = self.data.setdefault(col_group, {}).setdefault(row_label, [None] * self.n_reps)
|
|
211
|
+
while len(cell) <= rep:
|
|
212
|
+
cell.append(None)
|
|
213
|
+
cell[rep] = value
|
|
214
|
+
|
|
215
|
+
def to_long_dataframe(self) -> pd.DataFrame:
|
|
216
|
+
rows = []
|
|
217
|
+
for cg in self.col_groups:
|
|
218
|
+
for rl in self.row_labels:
|
|
219
|
+
for v in self.data.get(cg, {}).get(rl, []):
|
|
220
|
+
if v is not None and not (isinstance(v, float) and np.isnan(v)):
|
|
221
|
+
rows.append({"value": float(v), "factor_a": cg, "factor_b": rl})
|
|
222
|
+
return pd.DataFrame(rows)
|
|
223
|
+
|
|
224
|
+
def to_dict(self) -> dict:
|
|
225
|
+
return {
|
|
226
|
+
"name": self.name,
|
|
227
|
+
"table_type": "grouped",
|
|
228
|
+
"col_groups": self.col_groups,
|
|
229
|
+
"row_labels": self.row_labels,
|
|
230
|
+
"n_reps": self.n_reps,
|
|
231
|
+
"data": self.data,
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
@classmethod
|
|
235
|
+
def from_dict(cls, d: dict) -> GroupedDataTable:
|
|
236
|
+
t = cls(d["name"], d.get("n_reps", 3))
|
|
237
|
+
t.col_groups = d.get("col_groups", [])
|
|
238
|
+
t.row_labels = d.get("row_labels", [])
|
|
239
|
+
t.data = d.get("data", {})
|
|
240
|
+
return t
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class ContingencyTable:
|
|
244
|
+
"""
|
|
245
|
+
r×c contingency table for chi-square / Fisher's exact tests.
|
|
246
|
+
self.counts is a list-of-lists [row][col] aligned with row_labels × col_labels.
|
|
247
|
+
"""
|
|
248
|
+
|
|
249
|
+
def __init__(self, name: str):
|
|
250
|
+
self.name = name
|
|
251
|
+
self.table_type = "contingency"
|
|
252
|
+
self.row_labels: list[str] = []
|
|
253
|
+
self.col_labels: list[str] = []
|
|
254
|
+
self.counts: list[list[int]] = []
|
|
255
|
+
|
|
256
|
+
# ------------------------------------------------------------------
|
|
257
|
+
def _ensure_shape(self):
|
|
258
|
+
nrows, ncols = len(self.row_labels), len(self.col_labels)
|
|
259
|
+
while len(self.counts) < nrows:
|
|
260
|
+
self.counts.append([0] * ncols)
|
|
261
|
+
for row in self.counts:
|
|
262
|
+
while len(row) < ncols:
|
|
263
|
+
row.append(0)
|
|
264
|
+
|
|
265
|
+
def add_row(self, label: str):
|
|
266
|
+
if label not in self.row_labels:
|
|
267
|
+
self.row_labels.append(label)
|
|
268
|
+
self.counts.append([0] * len(self.col_labels))
|
|
269
|
+
|
|
270
|
+
def add_col(self, label: str):
|
|
271
|
+
if label not in self.col_labels:
|
|
272
|
+
self.col_labels.append(label)
|
|
273
|
+
for row in self.counts:
|
|
274
|
+
row.append(0)
|
|
275
|
+
|
|
276
|
+
def remove_row(self, label: str):
|
|
277
|
+
if label in self.row_labels:
|
|
278
|
+
idx = self.row_labels.index(label)
|
|
279
|
+
self.row_labels.pop(idx)
|
|
280
|
+
if idx < len(self.counts):
|
|
281
|
+
self.counts.pop(idx)
|
|
282
|
+
|
|
283
|
+
def remove_col(self, label: str):
|
|
284
|
+
if label in self.col_labels:
|
|
285
|
+
idx = self.col_labels.index(label)
|
|
286
|
+
self.col_labels.pop(idx)
|
|
287
|
+
for row in self.counts:
|
|
288
|
+
if idx < len(row):
|
|
289
|
+
row.pop(idx)
|
|
290
|
+
|
|
291
|
+
def set_count(self, row_label: str, col_label: str, value: int):
|
|
292
|
+
self._ensure_shape()
|
|
293
|
+
r = self.row_labels.index(row_label)
|
|
294
|
+
c = self.col_labels.index(col_label)
|
|
295
|
+
self.counts[r][c] = int(value)
|
|
296
|
+
|
|
297
|
+
def get_count(self, row_label: str, col_label: str) -> int:
|
|
298
|
+
self._ensure_shape()
|
|
299
|
+
r = self.row_labels.index(row_label)
|
|
300
|
+
c = self.col_labels.index(col_label)
|
|
301
|
+
return self.counts[r][c]
|
|
302
|
+
|
|
303
|
+
def get_matrix(self) -> np.ndarray:
|
|
304
|
+
self._ensure_shape()
|
|
305
|
+
return np.array(self.counts, dtype=int)
|
|
306
|
+
|
|
307
|
+
# ------------------------------------------------------------------
|
|
308
|
+
def to_dict(self) -> dict:
|
|
309
|
+
return {
|
|
310
|
+
"name": self.name,
|
|
311
|
+
"table_type": "contingency",
|
|
312
|
+
"row_labels": self.row_labels,
|
|
313
|
+
"col_labels": self.col_labels,
|
|
314
|
+
"counts": self.counts,
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
@classmethod
|
|
318
|
+
def from_dict(cls, d: dict) -> ContingencyTable:
|
|
319
|
+
t = cls(d["name"])
|
|
320
|
+
t.row_labels = d.get("row_labels", [])
|
|
321
|
+
t.col_labels = d.get("col_labels", [])
|
|
322
|
+
t.counts = d.get("counts", [])
|
|
323
|
+
return t
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@dataclass
|
|
327
|
+
class AnalysisResult:
|
|
328
|
+
name: str
|
|
329
|
+
method: str
|
|
330
|
+
source_table: str
|
|
331
|
+
summary_text: str
|
|
332
|
+
details: dict = field(default_factory=dict)
|
|
333
|
+
run_params: dict = field(default_factory=dict) # inputs for live re-run
|
|
334
|
+
|
|
335
|
+
def to_dict(self) -> dict:
|
|
336
|
+
safe_details = {}
|
|
337
|
+
for k, v in self.details.items():
|
|
338
|
+
safe_details[k] = v.tolist() if hasattr(v, "tolist") else v
|
|
339
|
+
return {
|
|
340
|
+
"name": self.name,
|
|
341
|
+
"method": self.method,
|
|
342
|
+
"source_table": self.source_table,
|
|
343
|
+
"summary_text": self.summary_text,
|
|
344
|
+
"details": safe_details,
|
|
345
|
+
"run_params": self.run_params,
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@dataclass
|
|
350
|
+
class GraphConfig:
|
|
351
|
+
name: str
|
|
352
|
+
source_table: str
|
|
353
|
+
plot_type: str # "bar" | "scatter" | "box" | "violin" | "survival"
|
|
354
|
+
options: dict = field(default_factory=dict)
|
|
355
|
+
|
|
356
|
+
def to_dict(self) -> dict:
|
|
357
|
+
return {
|
|
358
|
+
"name": self.name,
|
|
359
|
+
"source_table": self.source_table,
|
|
360
|
+
"plot_type": self.plot_type,
|
|
361
|
+
"options": self.options,
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class Project:
|
|
366
|
+
def __init__(self, name: str = "Untitled Project"):
|
|
367
|
+
self.name = name
|
|
368
|
+
self.filepath: Optional[str] = None
|
|
369
|
+
self.tables: list[DataTable] = []
|
|
370
|
+
self.analyses: list[AnalysisResult] = []
|
|
371
|
+
self.graphs: list[GraphConfig] = []
|
|
372
|
+
|
|
373
|
+
def _table_name(self, name):
|
|
374
|
+
# graphs / analyses find their table by name: keep names unique
|
|
375
|
+
return unique_name(name, [t.name for t in self.tables])
|
|
376
|
+
|
|
377
|
+
def add_table(self, name: str | None = None) -> DataTable:
|
|
378
|
+
if name is None:
|
|
379
|
+
name = f"Data {len(self.tables) + 1}"
|
|
380
|
+
t = DataTable(name=self._table_name(name))
|
|
381
|
+
self.tables.append(t)
|
|
382
|
+
return t
|
|
383
|
+
|
|
384
|
+
def add_grouped_table(self, name: str | None = None, n_reps: int = 3) -> GroupedDataTable:
|
|
385
|
+
if name is None:
|
|
386
|
+
name = f"Grouped {len(self.tables) + 1}"
|
|
387
|
+
t = GroupedDataTable(name=self._table_name(name), n_reps=n_reps)
|
|
388
|
+
self.tables.append(t)
|
|
389
|
+
return t
|
|
390
|
+
|
|
391
|
+
def add_contingency_table(self, name: str | None = None) -> ContingencyTable:
|
|
392
|
+
if name is None:
|
|
393
|
+
name = f"Contingency {len(self.tables) + 1}"
|
|
394
|
+
t = ContingencyTable(name=self._table_name(name))
|
|
395
|
+
self.tables.append(t)
|
|
396
|
+
return t
|
|
397
|
+
|
|
398
|
+
def get_table(self, name: str) -> Optional[DataTable | GroupedDataTable | ContingencyTable]:
|
|
399
|
+
return next((t for t in self.tables if t.name == name), None)
|
|
400
|
+
|
|
401
|
+
def add_graph(
|
|
402
|
+
self, name: str, source_table: str, plot_type: str, options: dict | None = None
|
|
403
|
+
) -> GraphConfig:
|
|
404
|
+
g = GraphConfig(name=name, source_table=source_table, plot_type=plot_type, options=options or {})
|
|
405
|
+
self.graphs.append(g)
|
|
406
|
+
return g
|
|
407
|
+
|
|
408
|
+
def save(self, filepath: str):
|
|
409
|
+
"""Write atomically: a failed save (full disk, crash, serialisation
|
|
410
|
+
error) leaves the previous file intact."""
|
|
411
|
+
import os
|
|
412
|
+
import tempfile
|
|
413
|
+
data = {
|
|
414
|
+
"name": self.name,
|
|
415
|
+
"tables": [t.to_dict() for t in self.tables],
|
|
416
|
+
"analyses": [a.to_dict() for a in self.analyses],
|
|
417
|
+
"graphs": [g.to_dict() for g in self.graphs],
|
|
418
|
+
}
|
|
419
|
+
folder = os.path.dirname(os.path.abspath(filepath))
|
|
420
|
+
fd, tmp = tempfile.mkstemp(prefix=".staplot_", suffix=".tmp", dir=folder)
|
|
421
|
+
try:
|
|
422
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
423
|
+
json.dump(data, f, indent=2)
|
|
424
|
+
f.flush()
|
|
425
|
+
os.fsync(f.fileno())
|
|
426
|
+
os.replace(tmp, filepath)
|
|
427
|
+
except BaseException:
|
|
428
|
+
try:
|
|
429
|
+
os.remove(tmp)
|
|
430
|
+
except OSError:
|
|
431
|
+
pass
|
|
432
|
+
raise
|
|
433
|
+
self.filepath = filepath
|
|
434
|
+
|
|
435
|
+
@classmethod
|
|
436
|
+
def load(cls, filepath: str) -> Project:
|
|
437
|
+
with open(filepath, encoding="utf-8") as f:
|
|
438
|
+
data = json.load(f)
|
|
439
|
+
p = cls(data.get("name", "Untitled"))
|
|
440
|
+
p.filepath = filepath
|
|
441
|
+
for td in data.get("tables", []):
|
|
442
|
+
tt = td.get("table_type", "column")
|
|
443
|
+
if tt == "grouped":
|
|
444
|
+
p.tables.append(GroupedDataTable.from_dict(td))
|
|
445
|
+
elif tt == "contingency":
|
|
446
|
+
p.tables.append(ContingencyTable.from_dict(td))
|
|
447
|
+
else:
|
|
448
|
+
p.tables.append(DataTable.from_dict(td))
|
|
449
|
+
for ad in data.get("analyses", []):
|
|
450
|
+
r = AnalysisResult(
|
|
451
|
+
name=ad["name"],
|
|
452
|
+
method=ad["method"],
|
|
453
|
+
source_table=ad["source_table"],
|
|
454
|
+
summary_text=ad["summary_text"],
|
|
455
|
+
details=ad.get("details", {}),
|
|
456
|
+
run_params=ad.get("run_params", {}),
|
|
457
|
+
)
|
|
458
|
+
p.analyses.append(r)
|
|
459
|
+
for gd in data.get("graphs", []):
|
|
460
|
+
p.graphs.append(GraphConfig(**gd))
|
|
461
|
+
return p
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .bar import plot_bar
|
|
2
|
+
from .scatter import plot_scatter
|
|
3
|
+
from .box import plot_box
|
|
4
|
+
from .survival import plot_survival
|
|
5
|
+
from .before_after import plot_before_after
|
|
6
|
+
from .histogram import plot_histogram
|
|
7
|
+
from .qq import plot_qq
|
|
8
|
+
from .heatmap import plot_heatmap
|
|
9
|
+
from .roc_plot import plot_roc
|
|
10
|
+
from .bland_altman import plot_bland_altman
|
|
11
|
+
from .residuals import plot_residuals
|
|
12
|
+
from .grouped_bar import plot_grouped_bar
|
|
13
|
+
from .volcano import plot_volcano
|
|
14
|
+
from .distribution_plot import plot_distribution, plot_distribution_grid
|
staplot/plots/bar.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import matplotlib.pyplot as plt
|
|
3
|
+
import matplotlib.figure
|
|
4
|
+
|
|
5
|
+
from ..models.project import DataTable
|
|
6
|
+
from ..stats.descriptive import describe
|
|
7
|
+
from . import styles
|
|
8
|
+
from .significance import add_significance_brackets
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@styles.styled
|
|
12
|
+
def plot_bar(
|
|
13
|
+
table: DataTable,
|
|
14
|
+
error_type: str = "sem",
|
|
15
|
+
show_points: bool = True,
|
|
16
|
+
title: str = "",
|
|
17
|
+
ylabel: str = "",
|
|
18
|
+
colors: list | None = None,
|
|
19
|
+
sig_pairs: list | None = None,
|
|
20
|
+
) -> matplotlib.figure.Figure:
|
|
21
|
+
"""sig_pairs: list of (name_a, name_b, p_value) to annotate."""
|
|
22
|
+
cols = table.columns
|
|
23
|
+
names = [c.name for c in cols]
|
|
24
|
+
if not names:
|
|
25
|
+
fig, ax = plt.subplots()
|
|
26
|
+
ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)
|
|
27
|
+
return fig
|
|
28
|
+
|
|
29
|
+
fig, ax = plt.subplots(figsize=(max(3.5, len(names) * 0.9), 4))
|
|
30
|
+
x_pos = np.arange(len(names))
|
|
31
|
+
bar_width = 0.6
|
|
32
|
+
|
|
33
|
+
for i, col in enumerate(cols):
|
|
34
|
+
arr = col.valid_values()
|
|
35
|
+
d = describe(arr)
|
|
36
|
+
if d["n"] == 0:
|
|
37
|
+
continue
|
|
38
|
+
color = (colors[i] if colors and i < len(colors) else styles.color(i))
|
|
39
|
+
err = d.get(error_type, d["sem"])
|
|
40
|
+
if np.isnan(err):
|
|
41
|
+
err = 0.0
|
|
42
|
+
|
|
43
|
+
ax.bar(
|
|
44
|
+
x_pos[i],
|
|
45
|
+
d["mean"],
|
|
46
|
+
width=bar_width,
|
|
47
|
+
color=color,
|
|
48
|
+
alpha=0.85,
|
|
49
|
+
zorder=2,
|
|
50
|
+
linewidth=0.8,
|
|
51
|
+
edgecolor="#444444",
|
|
52
|
+
)
|
|
53
|
+
ax.errorbar(
|
|
54
|
+
x_pos[i],
|
|
55
|
+
d["mean"],
|
|
56
|
+
yerr=err,
|
|
57
|
+
fmt="none",
|
|
58
|
+
color="#222222",
|
|
59
|
+
linewidth=1.2,
|
|
60
|
+
capsize=5,
|
|
61
|
+
zorder=3,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
if show_points and d["n"] > 0:
|
|
65
|
+
vals, row_idxs = col.valid_values_with_indices()
|
|
66
|
+
jitter = np.random.default_rng(i).uniform(-0.12, 0.12, size=len(vals))
|
|
67
|
+
sc = ax.scatter(
|
|
68
|
+
x_pos[i] + jitter,
|
|
69
|
+
vals,
|
|
70
|
+
color="#222222",
|
|
71
|
+
s=25,
|
|
72
|
+
zorder=4,
|
|
73
|
+
alpha=0.7,
|
|
74
|
+
linewidths=0.4,
|
|
75
|
+
edgecolors="white",
|
|
76
|
+
picker=5,
|
|
77
|
+
)
|
|
78
|
+
sc._staplot_meta = {"column": col.name, "rows": row_idxs, "exclude_all": False}
|
|
79
|
+
|
|
80
|
+
err_label = {"sem": "± SEM", "sd": "± SD", "ci95": "± 95% CI"}.get(error_type, "")
|
|
81
|
+
ax.set_xticks(x_pos)
|
|
82
|
+
rotation = 20 if max(len(n) for n in names) > 8 else 0
|
|
83
|
+
# tilted labels end at their tick; level ones are centred on it
|
|
84
|
+
ax.set_xticklabels(names, rotation=rotation, ha="right" if rotation else "center")
|
|
85
|
+
ax.set_ylabel(ylabel or "Value")
|
|
86
|
+
ax.set_title(title or table.name)
|
|
87
|
+
if err_label:
|
|
88
|
+
# as the (otherwise unused) x-axis label: matplotlib places it below the
|
|
89
|
+
# tick labels, so it no longer collides with rotated / long group names
|
|
90
|
+
# (a fixed ax.text at y=-0.12 did), and tight bounding boxes include it
|
|
91
|
+
ax.set_xlabel(f"Bars: mean {err_label}", fontsize=7, color="#666666",
|
|
92
|
+
loc="right")
|
|
93
|
+
|
|
94
|
+
if sig_pairs:
|
|
95
|
+
bar_tops: dict[str, float] = {}
|
|
96
|
+
for col in cols:
|
|
97
|
+
d = describe(col.valid_values())
|
|
98
|
+
if d["n"] > 0:
|
|
99
|
+
err = d.get(error_type, d["sem"])
|
|
100
|
+
bar_tops[col.name] = d["mean"] + (err if not np.isnan(err) else 0)
|
|
101
|
+
add_significance_brackets(ax, names, sig_pairs, bar_tops)
|
|
102
|
+
|
|
103
|
+
fig.tight_layout()
|
|
104
|
+
return fig
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Before/after (paired) plot — individual trajectories + mean±error overlay."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
import matplotlib.figure
|
|
6
|
+
|
|
7
|
+
from ..models.project import DataTable
|
|
8
|
+
from ..stats.descriptive import describe
|
|
9
|
+
from . import styles
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@styles.styled
|
|
13
|
+
def plot_before_after(
|
|
14
|
+
table: DataTable,
|
|
15
|
+
show_mean: bool = True,
|
|
16
|
+
error_type: str = "sem",
|
|
17
|
+
connect_lines: bool = True,
|
|
18
|
+
line_alpha: float = 0.35,
|
|
19
|
+
title: str = "",
|
|
20
|
+
ylabel: str = "",
|
|
21
|
+
colors: list | None = None,
|
|
22
|
+
) -> matplotlib.figure.Figure:
|
|
23
|
+
cols = table.columns
|
|
24
|
+
names = [c.name for c in cols]
|
|
25
|
+
if not names:
|
|
26
|
+
fig, ax = plt.subplots()
|
|
27
|
+
ax.text(0.5, 0.5, "No data", ha="center", va="center", transform=ax.transAxes)
|
|
28
|
+
return fig
|
|
29
|
+
|
|
30
|
+
fig, ax = plt.subplots(figsize=(max(3.5, len(names) * 0.9), 4))
|
|
31
|
+
x_pos = list(range(len(names)))
|
|
32
|
+
|
|
33
|
+
# Build index-aware data: use the intersection of valid row indices across all columns
|
|
34
|
+
per_col_data: list[tuple[np.ndarray, list[int]]] = [
|
|
35
|
+
c.valid_values_with_indices() for c in cols
|
|
36
|
+
]
|
|
37
|
+
# Common subject rows = rows present in ALL columns
|
|
38
|
+
common_idx: list[int] = sorted(
|
|
39
|
+
set(per_col_data[0][1]).intersection(*[set(d[1]) for d in per_col_data[1:]])
|
|
40
|
+
) if len(per_col_data) > 1 else list(per_col_data[0][1]) if per_col_data else []
|
|
41
|
+
|
|
42
|
+
# --- individual connecting lines ---
|
|
43
|
+
if connect_lines and len(names) >= 2 and common_idx:
|
|
44
|
+
rng = np.random.default_rng(99)
|
|
45
|
+
col_val_maps = [
|
|
46
|
+
{ri: rv for ri, rv in zip(d[1], d[0])} for d in per_col_data
|
|
47
|
+
]
|
|
48
|
+
for orig_row in common_idx:
|
|
49
|
+
y_vals = [cvm[orig_row] for cvm in col_val_maps]
|
|
50
|
+
jitter = rng.uniform(-0.04, 0.04, size=len(y_vals))
|
|
51
|
+
ax.plot(
|
|
52
|
+
[xi + ji for xi, ji in zip(x_pos, jitter)],
|
|
53
|
+
y_vals,
|
|
54
|
+
color="#aaaaaa",
|
|
55
|
+
alpha=line_alpha,
|
|
56
|
+
linewidth=0.9,
|
|
57
|
+
zorder=2,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# --- scatter points ---
|
|
61
|
+
for i, (col, (vals, row_idxs)) in enumerate(zip(cols, per_col_data)):
|
|
62
|
+
color = (colors[i] if colors and i < len(colors) else styles.color(i))
|
|
63
|
+
rng = np.random.default_rng(i)
|
|
64
|
+
jitter = rng.uniform(-0.07, 0.07, size=len(vals))
|
|
65
|
+
sc = ax.scatter(
|
|
66
|
+
x_pos[i] + jitter,
|
|
67
|
+
vals,
|
|
68
|
+
color=color,
|
|
69
|
+
s=28,
|
|
70
|
+
zorder=4,
|
|
71
|
+
alpha=0.8,
|
|
72
|
+
linewidths=0.4,
|
|
73
|
+
edgecolors="white",
|
|
74
|
+
picker=5,
|
|
75
|
+
)
|
|
76
|
+
# exclude_all=True so clicking removes the subject from all time-points
|
|
77
|
+
sc._staplot_meta = {"column": col.name, "rows": row_idxs, "exclude_all": True}
|
|
78
|
+
|
|
79
|
+
# --- mean ± error overlay ---
|
|
80
|
+
if show_mean:
|
|
81
|
+
for i, (col, (vals, _)) in enumerate(zip(cols, per_col_data)):
|
|
82
|
+
d = describe(vals)
|
|
83
|
+
if d["n"] == 0:
|
|
84
|
+
continue
|
|
85
|
+
color = (colors[i] if colors and i < len(colors) else styles.color(i))
|
|
86
|
+
err = d.get(error_type, d["sem"])
|
|
87
|
+
if np.isnan(err):
|
|
88
|
+
err = 0.0
|
|
89
|
+
ax.errorbar(
|
|
90
|
+
x_pos[i],
|
|
91
|
+
d["mean"],
|
|
92
|
+
yerr=err,
|
|
93
|
+
fmt="D",
|
|
94
|
+
color=color,
|
|
95
|
+
markersize=9,
|
|
96
|
+
capsize=6,
|
|
97
|
+
linewidth=2.0,
|
|
98
|
+
zorder=5,
|
|
99
|
+
markeredgecolor="#222222",
|
|
100
|
+
markeredgewidth=0.6,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
ax.set_xticks(x_pos)
|
|
104
|
+
rotation = 20 if max(len(n) for n in names) > 8 else 0
|
|
105
|
+
# tilted labels end at their tick; level ones are centred on it
|
|
106
|
+
ax.set_xticklabels(names, rotation=rotation, ha="right" if rotation else "center")
|
|
107
|
+
ax.set_ylabel(ylabel or "Value")
|
|
108
|
+
ax.set_title(title or table.name)
|
|
109
|
+
fig.tight_layout()
|
|
110
|
+
return fig
|