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,1126 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from qtpy.QtWidgets import (
|
|
4
|
+
QMainWindow, QWidget, QHBoxLayout, QSplitter, QStackedWidget,
|
|
5
|
+
QAction, QFileDialog, QMessageBox, QInputDialog, QLabel, QMenu,
|
|
6
|
+
)
|
|
7
|
+
from qtpy.QtCore import Qt, QSettings, QTimer
|
|
8
|
+
from qtpy.QtGui import QKeySequence
|
|
9
|
+
# QUndoStack lives in QtWidgets (PyQt5) or QtGui (PyQt6) — try both
|
|
10
|
+
try:
|
|
11
|
+
from qtpy.QtWidgets import QUndoStack
|
|
12
|
+
except ImportError:
|
|
13
|
+
from qtpy.QtGui import QUndoStack # type: ignore[no-redef]
|
|
14
|
+
|
|
15
|
+
from ..models.project import (
|
|
16
|
+
Project, GraphConfig, GroupedDataTable, ContingencyTable, DataTable,
|
|
17
|
+
)
|
|
18
|
+
from .navigator import NavigatorPanel
|
|
19
|
+
from .data_table_widget import DataTableWidget
|
|
20
|
+
from .grouped_table_widget import GroupedTableWidget
|
|
21
|
+
from .contingency_table_widget import ContingencyTableWidget
|
|
22
|
+
from .plot_canvas import PlotCanvas, apply_axis_settings
|
|
23
|
+
from .results_widget import ResultsWidget
|
|
24
|
+
from .analysis_dialog import AnalysisDialog
|
|
25
|
+
from .graph_options_dialog import GraphOptionsDialog
|
|
26
|
+
from .. import plots as plot_lib
|
|
27
|
+
from ..plots import styles as plot_styles
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class MainWindow(QMainWindow):
|
|
31
|
+
def __init__(self):
|
|
32
|
+
super().__init__()
|
|
33
|
+
self.setWindowTitle("Staplot")
|
|
34
|
+
self.resize(1100, 700)
|
|
35
|
+
|
|
36
|
+
self.project = Project()
|
|
37
|
+
self._undo_stack = QUndoStack(self)
|
|
38
|
+
self._active_gc: GraphConfig | None = None
|
|
39
|
+
self._dirty = False
|
|
40
|
+
|
|
41
|
+
self._setup_ui()
|
|
42
|
+
self._setup_menu()
|
|
43
|
+
self._setup_toolbar()
|
|
44
|
+
self._new_default_table()
|
|
45
|
+
self._start_autosave()
|
|
46
|
+
|
|
47
|
+
# ------------------------------------------------------------------
|
|
48
|
+
# UI setup
|
|
49
|
+
# ------------------------------------------------------------------
|
|
50
|
+
def _setup_ui(self):
|
|
51
|
+
central = QWidget()
|
|
52
|
+
self.setCentralWidget(central)
|
|
53
|
+
root_layout = QHBoxLayout(central)
|
|
54
|
+
root_layout.setContentsMargins(0, 0, 0, 0)
|
|
55
|
+
root_layout.setSpacing(0)
|
|
56
|
+
|
|
57
|
+
self.splitter = QSplitter(Qt.Orientation.Horizontal)
|
|
58
|
+
root_layout.addWidget(self.splitter)
|
|
59
|
+
|
|
60
|
+
self.navigator = NavigatorPanel(self)
|
|
61
|
+
self.navigator.item_activated.connect(self._on_nav_item)
|
|
62
|
+
self.splitter.addWidget(self.navigator)
|
|
63
|
+
|
|
64
|
+
self.stack = QStackedWidget()
|
|
65
|
+
self.splitter.addWidget(self.stack)
|
|
66
|
+
self.splitter.setSizes([200, 900])
|
|
67
|
+
self.splitter.setStretchFactor(1, 1)
|
|
68
|
+
|
|
69
|
+
self.table_widget = DataTableWidget(self)
|
|
70
|
+
self.table_widget._undo_stack = self._undo_stack
|
|
71
|
+
self.table_widget.data_changed.connect(self._on_data_changed)
|
|
72
|
+
|
|
73
|
+
self.grouped_widget = GroupedTableWidget(self)
|
|
74
|
+
self.grouped_widget.data_changed.connect(self._on_data_changed)
|
|
75
|
+
|
|
76
|
+
self.contingency_widget = ContingencyTableWidget(self)
|
|
77
|
+
self.contingency_widget.data_changed.connect(self._on_data_changed)
|
|
78
|
+
|
|
79
|
+
self.plot_canvas = PlotCanvas(self)
|
|
80
|
+
self.plot_canvas.axes_changed.connect(self._on_axes_changed)
|
|
81
|
+
self.plot_canvas.point_excluded.connect(self._on_point_excluded)
|
|
82
|
+
|
|
83
|
+
self.results_widget = ResultsWidget(self)
|
|
84
|
+
|
|
85
|
+
self.stack.addWidget(self.table_widget) # 0
|
|
86
|
+
self.stack.addWidget(self.plot_canvas) # 1
|
|
87
|
+
self.stack.addWidget(self.results_widget) # 2
|
|
88
|
+
self.stack.addWidget(self.grouped_widget) # 3
|
|
89
|
+
self.stack.addWidget(self.contingency_widget) # 4
|
|
90
|
+
|
|
91
|
+
self._status_label = QLabel("Ready")
|
|
92
|
+
self.statusBar().addPermanentWidget(self._status_label)
|
|
93
|
+
|
|
94
|
+
# ------------------------------------------------------------------
|
|
95
|
+
def _setup_menu(self):
|
|
96
|
+
mb = self.menuBar()
|
|
97
|
+
|
|
98
|
+
# ── File ──────────────────────────────────────────────────────
|
|
99
|
+
file_m = mb.addMenu("&File")
|
|
100
|
+
self._add_action(file_m, "&New Project", self.new_project, "Ctrl+N")
|
|
101
|
+
self._add_action(file_m, "&Open…", self.open_project, "Ctrl+O")
|
|
102
|
+
self._add_action(file_m, "&Save", self.save_project, "Ctrl+S")
|
|
103
|
+
self._add_action(file_m, "Save &As…", self.save_project_as)
|
|
104
|
+
file_m.addSeparator()
|
|
105
|
+
|
|
106
|
+
self._recent_menu = file_m.addMenu("Recent Files")
|
|
107
|
+
self._update_recent_menu()
|
|
108
|
+
|
|
109
|
+
file_m.addSeparator()
|
|
110
|
+
self._add_action(file_m, "Import CSV…", self.import_csv)
|
|
111
|
+
self._add_action(file_m, "Import Excel…", self.import_excel)
|
|
112
|
+
self._add_action(file_m, "Export Graph…", self.export_graph)
|
|
113
|
+
file_m.addSeparator()
|
|
114
|
+
self._add_action(file_m, "&Quit", self.close, "Ctrl+Q")
|
|
115
|
+
|
|
116
|
+
# ── Edit ──────────────────────────────────────────────────────
|
|
117
|
+
edit_m = mb.addMenu("&Edit")
|
|
118
|
+
undo_act = self._undo_stack.createUndoAction(self, "&Undo")
|
|
119
|
+
undo_act.setShortcut(QKeySequence("Ctrl+Z"))
|
|
120
|
+
edit_m.addAction(undo_act)
|
|
121
|
+
redo_act = self._undo_stack.createRedoAction(self, "&Redo")
|
|
122
|
+
redo_act.setShortcut(QKeySequence("Ctrl+Y"))
|
|
123
|
+
edit_m.addAction(redo_act)
|
|
124
|
+
edit_m.addSeparator()
|
|
125
|
+
self._add_action(edit_m, "Copy Graph to Clipboard",
|
|
126
|
+
lambda: self.plot_canvas.copy_to_clipboard(), "Ctrl+Shift+C")
|
|
127
|
+
|
|
128
|
+
# ── Data ──────────────────────────────────────────────────────
|
|
129
|
+
data_m = mb.addMenu("&Data")
|
|
130
|
+
self._add_action(data_m, "Add Table", self.add_table)
|
|
131
|
+
self._add_action(data_m, "Add Grouped Table…", self.add_grouped_table)
|
|
132
|
+
self._add_action(data_m, "Add Contingency Table…", self.add_contingency_table)
|
|
133
|
+
self._add_action(data_m, "Rename Table…", self.rename_table)
|
|
134
|
+
data_m.addSeparator()
|
|
135
|
+
self._add_action(data_m, "Add Column", self.table_widget.add_column)
|
|
136
|
+
self._add_action(data_m, "Remove Column", self.table_widget.remove_selected_column)
|
|
137
|
+
data_m.addSeparator()
|
|
138
|
+
self._add_action(data_m, "Transform Data…", self.transform_data)
|
|
139
|
+
self._add_action(data_m, "Row Statistics…", self.compute_row_stats)
|
|
140
|
+
self._add_action(data_m, "Paste from Clipboard",
|
|
141
|
+
self.table_widget.paste_from_clipboard, "Ctrl+Shift+V")
|
|
142
|
+
|
|
143
|
+
# ── Statistics ────────────────────────────────────────────────
|
|
144
|
+
stat_m = mb.addMenu("&Statistics")
|
|
145
|
+
self._add_action(stat_m, "What test should I use?…", self.open_test_wizard)
|
|
146
|
+
stat_m.addSeparator()
|
|
147
|
+
self._add_action(stat_m, "Descriptive Statistics", self._run_descriptive)
|
|
148
|
+
self._add_action(stat_m, "Distribution Inspector…", self.open_distribution_inspector)
|
|
149
|
+
self._add_action(stat_m, "Normality Tests", lambda: self._open_analysis(4))
|
|
150
|
+
self._add_action(stat_m, "Outlier Test (Grubbs)…", lambda: self._open_analysis(9))
|
|
151
|
+
stat_m.addSeparator()
|
|
152
|
+
self._add_action(stat_m, "t-test…", lambda: self._open_analysis(0))
|
|
153
|
+
self._add_action(stat_m, "One-Way ANOVA…", lambda: self._open_analysis(1))
|
|
154
|
+
self._add_action(stat_m, "Two-Way ANOVA…", lambda: self._open_analysis(2))
|
|
155
|
+
self._add_action(stat_m, "RM ANOVA / Friedman…", lambda: self._open_analysis(8))
|
|
156
|
+
self._add_action(stat_m, "Correlation…", lambda: self._open_analysis(3))
|
|
157
|
+
self._add_action(stat_m, "Chi-square / Fisher…", lambda: self._open_analysis(7))
|
|
158
|
+
stat_m.addSeparator()
|
|
159
|
+
self._add_action(stat_m, "Curve Fitting…", lambda: self._open_analysis(5))
|
|
160
|
+
self._add_action(stat_m, "Multiple Regression…", lambda: self._open_analysis(11))
|
|
161
|
+
self._add_action(stat_m, "ROC Curve…", lambda: self._open_analysis(10))
|
|
162
|
+
stat_m.addSeparator()
|
|
163
|
+
self._add_action(stat_m, "Multiple Comparisons…", self.open_multiple_comparisons)
|
|
164
|
+
self._add_action(stat_m, "Power Analysis…", self.open_power_dialog)
|
|
165
|
+
|
|
166
|
+
# ── Graphs ────────────────────────────────────────────────────
|
|
167
|
+
graph_m = mb.addMenu("&Graphs")
|
|
168
|
+
for label, ptype in [
|
|
169
|
+
("Bar Chart", "bar"),
|
|
170
|
+
("Before/After", "before_after"),
|
|
171
|
+
("Scatter Plot", "scatter"),
|
|
172
|
+
("Box Plot", "box"),
|
|
173
|
+
("Violin Plot", "violin"),
|
|
174
|
+
("Histogram", "histogram"),
|
|
175
|
+
("Survival Curve", "survival"),
|
|
176
|
+
]:
|
|
177
|
+
self._add_action(graph_m, label, lambda pt=ptype: self.new_graph(pt))
|
|
178
|
+
graph_m.addSeparator()
|
|
179
|
+
for label, ptype in [
|
|
180
|
+
("Q-Q Plot", "qq"),
|
|
181
|
+
("Heatmap", "heatmap"),
|
|
182
|
+
("ROC Curve Plot", "roc"),
|
|
183
|
+
("Bland-Altman", "bland_altman"),
|
|
184
|
+
]:
|
|
185
|
+
self._add_action(graph_m, label, lambda pt=ptype: self.new_graph(pt))
|
|
186
|
+
for label, ptype in [
|
|
187
|
+
("Grouped Bar", "grouped_bar"),
|
|
188
|
+
("Volcano Plot", "volcano"),
|
|
189
|
+
]:
|
|
190
|
+
self._add_action(graph_m, label, lambda pt=ptype: self.new_graph(pt))
|
|
191
|
+
graph_m.addSeparator()
|
|
192
|
+
self._add_action(graph_m, "Multi-Panel Figure…", self.open_figure_layout)
|
|
193
|
+
self._add_action(graph_m, "Graph Gallery…", self.open_graph_gallery)
|
|
194
|
+
|
|
195
|
+
# ── Tools ─────────────────────────────────────────────────────
|
|
196
|
+
tools_m = mb.addMenu("&Tools")
|
|
197
|
+
self._add_action(tools_m, "Standard Curve…", self.open_standard_curve)
|
|
198
|
+
self._add_action(tools_m, "Generate Report…", self.open_report)
|
|
199
|
+
tools_m.addSeparator()
|
|
200
|
+
self._add_action(tools_m, "Computed Column…", self.open_computed_column)
|
|
201
|
+
self._add_action(tools_m, "Reshape Table…", self.open_reshape)
|
|
202
|
+
self._add_action(tools_m, "Export Table as CSV…", self.export_table_csv)
|
|
203
|
+
|
|
204
|
+
# ── Help ──────────────────────────────────────────────────────
|
|
205
|
+
help_m = mb.addMenu("&Help")
|
|
206
|
+
self._add_action(help_m, "About", self._about)
|
|
207
|
+
|
|
208
|
+
# ------------------------------------------------------------------
|
|
209
|
+
def _setup_toolbar(self):
|
|
210
|
+
tb = self.addToolBar("Main")
|
|
211
|
+
tb.setMovable(False)
|
|
212
|
+
self._add_action(tb, "New Table", self.add_table)
|
|
213
|
+
self._add_action(tb, "Wizard", self.open_test_wizard)
|
|
214
|
+
tb.addSeparator()
|
|
215
|
+
for label, pt in [
|
|
216
|
+
("Bar", "bar"),
|
|
217
|
+
("B/A", "before_after"),
|
|
218
|
+
("Scatter", "scatter"),
|
|
219
|
+
("Box", "box"),
|
|
220
|
+
("Violin", "violin"),
|
|
221
|
+
("Hist", "histogram"),
|
|
222
|
+
("Q-Q", "qq"),
|
|
223
|
+
("Heatmap", "heatmap"),
|
|
224
|
+
("Grp Bar", "grouped_bar"),
|
|
225
|
+
("Volcano", "volcano"),
|
|
226
|
+
]:
|
|
227
|
+
self._add_action(tb, label, lambda p=pt: self.new_graph(p))
|
|
228
|
+
|
|
229
|
+
def _add_action(self, parent, label, slot, shortcut=None) -> QAction:
|
|
230
|
+
act = QAction(label, self)
|
|
231
|
+
act.triggered.connect(slot)
|
|
232
|
+
if shortcut:
|
|
233
|
+
act.setShortcut(QKeySequence(shortcut))
|
|
234
|
+
parent.addAction(act)
|
|
235
|
+
return act
|
|
236
|
+
|
|
237
|
+
# ------------------------------------------------------------------
|
|
238
|
+
# Auto-save
|
|
239
|
+
# ------------------------------------------------------------------
|
|
240
|
+
def _start_autosave(self):
|
|
241
|
+
self._autosave_timer = QTimer(self)
|
|
242
|
+
self._autosave_timer.setInterval(5 * 60 * 1000) # 5 minutes
|
|
243
|
+
self._autosave_timer.timeout.connect(self._auto_save)
|
|
244
|
+
self._autosave_timer.start()
|
|
245
|
+
|
|
246
|
+
def _mark_modified(self, message: str = "Modified"):
|
|
247
|
+
"""The project has unsaved changes (dedicated flag: status-bar text is
|
|
248
|
+
overwritten by informational messages, so it can't carry this state)."""
|
|
249
|
+
self._dirty = True
|
|
250
|
+
self._status_label.setText(message)
|
|
251
|
+
|
|
252
|
+
def _auto_save(self):
|
|
253
|
+
if self.project.filepath and self._dirty:
|
|
254
|
+
try:
|
|
255
|
+
self.project.save(self.project.filepath)
|
|
256
|
+
except Exception as exc:
|
|
257
|
+
# Project.save is atomic: the previous file is intact
|
|
258
|
+
self._status_label.setText(f"Auto-save FAILED: {exc}")
|
|
259
|
+
return
|
|
260
|
+
self._dirty = False
|
|
261
|
+
self._status_label.setText("Auto-saved")
|
|
262
|
+
|
|
263
|
+
# ------------------------------------------------------------------
|
|
264
|
+
# Recent files
|
|
265
|
+
# ------------------------------------------------------------------
|
|
266
|
+
def _get_recent_files(self) -> list[str]:
|
|
267
|
+
settings = QSettings("Staplot", "Staplot")
|
|
268
|
+
val = settings.value("recent_files", [])
|
|
269
|
+
return val if isinstance(val, list) else []
|
|
270
|
+
|
|
271
|
+
def _add_to_recent(self, path: str):
|
|
272
|
+
recent = self._get_recent_files()
|
|
273
|
+
if path in recent:
|
|
274
|
+
recent.remove(path)
|
|
275
|
+
recent.insert(0, path)
|
|
276
|
+
recent = recent[:8]
|
|
277
|
+
settings = QSettings("Staplot", "Staplot")
|
|
278
|
+
settings.setValue("recent_files", recent)
|
|
279
|
+
self._update_recent_menu()
|
|
280
|
+
|
|
281
|
+
def _update_recent_menu(self):
|
|
282
|
+
self._recent_menu.clear()
|
|
283
|
+
recent = self._get_recent_files()
|
|
284
|
+
for path in recent:
|
|
285
|
+
name = os.path.basename(path)
|
|
286
|
+
act = QAction(name, self)
|
|
287
|
+
act.setData(path)
|
|
288
|
+
act.setStatusTip(path)
|
|
289
|
+
act.triggered.connect(lambda checked=False, p=path: self._open_recent(p))
|
|
290
|
+
self._recent_menu.addAction(act)
|
|
291
|
+
if not recent:
|
|
292
|
+
placeholder = QAction("(none)", self)
|
|
293
|
+
placeholder.setEnabled(False)
|
|
294
|
+
self._recent_menu.addAction(placeholder)
|
|
295
|
+
|
|
296
|
+
def _open_recent(self, path: str):
|
|
297
|
+
if not os.path.exists(path):
|
|
298
|
+
QMessageBox.warning(self, "File not found",
|
|
299
|
+
f"'{path}' no longer exists.")
|
|
300
|
+
return
|
|
301
|
+
if not self._confirm_discard():
|
|
302
|
+
return
|
|
303
|
+
try:
|
|
304
|
+
self.project = Project.load(path)
|
|
305
|
+
self._dirty = False
|
|
306
|
+
self._active_gc = None
|
|
307
|
+
self.navigator.populate(self.project)
|
|
308
|
+
self._load_first_table()
|
|
309
|
+
self.setWindowTitle(f"Staplot — {self.project.name}")
|
|
310
|
+
self._add_to_recent(path)
|
|
311
|
+
except Exception as exc:
|
|
312
|
+
QMessageBox.critical(self, "Open failed", str(exc))
|
|
313
|
+
|
|
314
|
+
# ------------------------------------------------------------------
|
|
315
|
+
# Tables
|
|
316
|
+
# ------------------------------------------------------------------
|
|
317
|
+
def _new_default_table(self):
|
|
318
|
+
t = self.project.add_table("Data 1")
|
|
319
|
+
for name in ["Group A", "Group B", "Group C"]:
|
|
320
|
+
t.add_column(name)
|
|
321
|
+
self.navigator.add_table(t.name)
|
|
322
|
+
self.table_widget.load_table(t)
|
|
323
|
+
self.stack.setCurrentIndex(0)
|
|
324
|
+
|
|
325
|
+
def add_table(self):
|
|
326
|
+
name, ok = QInputDialog.getText(self, "New Table", "Table name:")
|
|
327
|
+
if not ok or not name.strip():
|
|
328
|
+
return
|
|
329
|
+
t = self.project.add_table(name.strip())
|
|
330
|
+
t.add_column("Group A"); t.add_column("Group B")
|
|
331
|
+
self.navigator.add_table(t.name)
|
|
332
|
+
self.table_widget.load_table(t)
|
|
333
|
+
self.stack.setCurrentIndex(0)
|
|
334
|
+
|
|
335
|
+
def add_grouped_table(self):
|
|
336
|
+
name, ok = QInputDialog.getText(self, "New Grouped Table", "Table name:")
|
|
337
|
+
if not ok or not name.strip():
|
|
338
|
+
return
|
|
339
|
+
reps, ok2 = QInputDialog.getInt(self, "Replicates", "Replicates per cell:", 3, 1, 20)
|
|
340
|
+
if not ok2:
|
|
341
|
+
return
|
|
342
|
+
t = self.project.add_grouped_table(name.strip(), n_reps=reps)
|
|
343
|
+
for cg in ["Group A", "Group B"]:
|
|
344
|
+
t.add_col_group(cg)
|
|
345
|
+
for rl in ["Row 1", "Row 2", "Row 3"]:
|
|
346
|
+
t.add_row_label(rl)
|
|
347
|
+
self.navigator.add_table(t.name)
|
|
348
|
+
self.grouped_widget.load_table(t)
|
|
349
|
+
self.stack.setCurrentIndex(3)
|
|
350
|
+
|
|
351
|
+
def add_contingency_table(self):
|
|
352
|
+
name, ok = QInputDialog.getText(self, "New Contingency Table", "Table name:")
|
|
353
|
+
if not ok or not name.strip():
|
|
354
|
+
return
|
|
355
|
+
t = self.project.add_contingency_table(name.strip())
|
|
356
|
+
for r in ["Row 1", "Row 2"]:
|
|
357
|
+
t.add_row(r)
|
|
358
|
+
for c in ["Col 1", "Col 2"]:
|
|
359
|
+
t.add_col(c)
|
|
360
|
+
self.navigator.add_table(t.name)
|
|
361
|
+
self.contingency_widget.load_table(t)
|
|
362
|
+
self.stack.setCurrentIndex(4)
|
|
363
|
+
|
|
364
|
+
def rename_table(self):
|
|
365
|
+
t = self._active_table()
|
|
366
|
+
if t is None:
|
|
367
|
+
return
|
|
368
|
+
new_name, ok = QInputDialog.getText(self, "Rename Table", "New name:", text=t.name)
|
|
369
|
+
if ok and new_name.strip():
|
|
370
|
+
old, new = t.name, new_name.strip()
|
|
371
|
+
if new == old:
|
|
372
|
+
return
|
|
373
|
+
if self.project.get_table(new) is not None:
|
|
374
|
+
QMessageBox.warning(self, "Rename Table",
|
|
375
|
+
f"A table named '{new}' already exists.")
|
|
376
|
+
return
|
|
377
|
+
t.name = new
|
|
378
|
+
# graphs and analyses refer to their table by name
|
|
379
|
+
for gc in self.project.graphs:
|
|
380
|
+
if gc.source_table == old:
|
|
381
|
+
gc.source_table = new
|
|
382
|
+
for a in self.project.analyses:
|
|
383
|
+
if a.source_table == old:
|
|
384
|
+
a.source_table = new
|
|
385
|
+
self.navigator.rename_last_table(old, t.name)
|
|
386
|
+
self._mark_modified()
|
|
387
|
+
|
|
388
|
+
def _active_table(self):
|
|
389
|
+
idx = self.stack.currentIndex()
|
|
390
|
+
if idx == 0:
|
|
391
|
+
return self.table_widget._table
|
|
392
|
+
if idx == 3:
|
|
393
|
+
return self.grouped_widget._table
|
|
394
|
+
if idx == 4:
|
|
395
|
+
return self.contingency_widget._table
|
|
396
|
+
return self.project.tables[0] if self.project.tables else None
|
|
397
|
+
|
|
398
|
+
# ------------------------------------------------------------------
|
|
399
|
+
# Row statistics
|
|
400
|
+
# ------------------------------------------------------------------
|
|
401
|
+
def compute_row_stats(self):
|
|
402
|
+
t = self._active_table()
|
|
403
|
+
if t is None or not isinstance(t, DataTable) or not t.columns:
|
|
404
|
+
QMessageBox.warning(self, "No table",
|
|
405
|
+
"Open a standard data table first.")
|
|
406
|
+
return
|
|
407
|
+
import numpy as np
|
|
408
|
+
n_rows = t.num_rows()
|
|
409
|
+
new_t = DataTable(f"{t.name} (Row Stats)")
|
|
410
|
+
for col_name in ["Mean", "SD", "SEM", "N"]:
|
|
411
|
+
new_t.add_column(col_name)
|
|
412
|
+
|
|
413
|
+
df = t.to_dataframe()
|
|
414
|
+
for row_idx in range(n_rows):
|
|
415
|
+
vals = df.iloc[row_idx].dropna().values.astype(float)
|
|
416
|
+
if len(vals) == 0:
|
|
417
|
+
continue
|
|
418
|
+
mean = float(np.mean(vals))
|
|
419
|
+
sd = float(np.std(vals, ddof=1)) if len(vals) > 1 else float("nan")
|
|
420
|
+
sem = sd / float(np.sqrt(len(vals))) if len(vals) > 1 else float("nan")
|
|
421
|
+
n = float(len(vals))
|
|
422
|
+
for col_idx, v in enumerate([mean, sd, sem, n]):
|
|
423
|
+
new_t.set_value(row_idx, col_idx, v)
|
|
424
|
+
|
|
425
|
+
new_t.name = self.project._table_name(new_t.name)
|
|
426
|
+
self.project.tables.append(new_t)
|
|
427
|
+
self.navigator.add_table(new_t.name)
|
|
428
|
+
self.table_widget.load_table(new_t)
|
|
429
|
+
self.stack.setCurrentIndex(0)
|
|
430
|
+
self._mark_modified(f"Created: {new_t.name}")
|
|
431
|
+
|
|
432
|
+
# ------------------------------------------------------------------
|
|
433
|
+
# Live graph update
|
|
434
|
+
# ------------------------------------------------------------------
|
|
435
|
+
def _on_data_changed(self):
|
|
436
|
+
self._mark_modified()
|
|
437
|
+
# Live graph refresh
|
|
438
|
+
if self.stack.currentIndex() == 1 and self._active_gc is not None:
|
|
439
|
+
self._render_graph(self._active_gc, live_refresh=True)
|
|
440
|
+
# Live re-analysis for the currently-edited table
|
|
441
|
+
t = self._active_table()
|
|
442
|
+
if t is not None:
|
|
443
|
+
self._rerun_analyses_for_table(t.name)
|
|
444
|
+
|
|
445
|
+
# ------------------------------------------------------------------
|
|
446
|
+
# Interactive point exclusion
|
|
447
|
+
# ------------------------------------------------------------------
|
|
448
|
+
def _on_point_excluded(self, col_name: str, row_idx: int, exclude_all: bool):
|
|
449
|
+
"""Toggle exclusion of a clicked data point and refresh everything."""
|
|
450
|
+
if self._active_gc is None:
|
|
451
|
+
return
|
|
452
|
+
t = self.project.get_table(self._active_gc.source_table)
|
|
453
|
+
if t is None or not isinstance(t, DataTable):
|
|
454
|
+
return
|
|
455
|
+
if exclude_all:
|
|
456
|
+
for col in t.columns:
|
|
457
|
+
col.toggle_excluded(row_idx)
|
|
458
|
+
else:
|
|
459
|
+
for col in t.columns:
|
|
460
|
+
if col.name == col_name:
|
|
461
|
+
col.toggle_excluded(row_idx)
|
|
462
|
+
break
|
|
463
|
+
# Sync table widget (only if it is displaying this table)
|
|
464
|
+
if self.table_widget._table is t:
|
|
465
|
+
self.table_widget._refresh()
|
|
466
|
+
self._on_data_changed()
|
|
467
|
+
|
|
468
|
+
# ------------------------------------------------------------------
|
|
469
|
+
# Live re-analysis dispatcher
|
|
470
|
+
# ------------------------------------------------------------------
|
|
471
|
+
def _rerun_analyses_for_table(self, table_name: str):
|
|
472
|
+
"""Re-run all analyses whose source_table matches *table_name*."""
|
|
473
|
+
from .. import stats as stat_lib
|
|
474
|
+
|
|
475
|
+
t = self.project.get_table(table_name)
|
|
476
|
+
if t is None:
|
|
477
|
+
return
|
|
478
|
+
|
|
479
|
+
refreshed_names = []
|
|
480
|
+
for result in self.project.analyses:
|
|
481
|
+
if result.source_table != table_name or not result.run_params:
|
|
482
|
+
continue
|
|
483
|
+
new_r = self._dispatch_analysis(result, t, stat_lib)
|
|
484
|
+
if new_r is not None:
|
|
485
|
+
result.summary_text = new_r.summary_text
|
|
486
|
+
result.details = new_r.details
|
|
487
|
+
refreshed_names.append(result.name)
|
|
488
|
+
|
|
489
|
+
if refreshed_names and self.stack.currentIndex() == 2:
|
|
490
|
+
# Refresh results widget if it is showing one of the updated analyses
|
|
491
|
+
shown = getattr(self.results_widget, "_current_result", None)
|
|
492
|
+
if shown is not None and shown.name in refreshed_names:
|
|
493
|
+
self.results_widget.show_result(shown)
|
|
494
|
+
|
|
495
|
+
@staticmethod
|
|
496
|
+
def _dispatch_analysis(result, table, stat_lib):
|
|
497
|
+
"""Re-run a single analysis from its stored method + run_params."""
|
|
498
|
+
m = result.method
|
|
499
|
+
p = result.run_params
|
|
500
|
+
try:
|
|
501
|
+
if m == "t-test":
|
|
502
|
+
if p.get("non_parametric"):
|
|
503
|
+
if p.get("paired"):
|
|
504
|
+
return stat_lib.run_wilcoxon(table, p["group_a"], p["group_b"], p.get("alternative", "two-sided"))
|
|
505
|
+
return stat_lib.run_mann_whitney(table, p["group_a"], p["group_b"], p.get("alternative", "two-sided"))
|
|
506
|
+
return stat_lib.run_ttest(table, p["group_a"], p["group_b"], p.get("paired", False), p.get("alternative", "two-sided"))
|
|
507
|
+
if m in ("one-way-anova", "kruskal-wallis"):
|
|
508
|
+
if p.get("non_parametric"):
|
|
509
|
+
return stat_lib.run_kruskal_wallis(table)
|
|
510
|
+
return stat_lib.run_one_way_anova(table, p.get("post_hoc", "tukey"))
|
|
511
|
+
if m == "two-way-anova":
|
|
512
|
+
return stat_lib.run_two_way_anova(table)
|
|
513
|
+
if m.startswith("correlation"):
|
|
514
|
+
return stat_lib.run_correlation(table, p["col_a"], p["col_b"], p.get("method", "pearson"))
|
|
515
|
+
if m == "normality":
|
|
516
|
+
return stat_lib.run_normality(table)
|
|
517
|
+
if m.startswith("curve-fit"):
|
|
518
|
+
return stat_lib.run_curve_fit(table, p["x_col"], p["y_col"], p.get("model", "linear"))
|
|
519
|
+
if m == "grubbs":
|
|
520
|
+
return stat_lib.run_grubbs(table, alpha=p.get("alpha", 0.05))
|
|
521
|
+
if m == "roc":
|
|
522
|
+
return stat_lib.run_roc(table, p["label_col"], p["score_col"])
|
|
523
|
+
if m == "rm-anova":
|
|
524
|
+
return stat_lib.run_rm_anova(table)
|
|
525
|
+
if m == "friedman":
|
|
526
|
+
return stat_lib.run_friedman(table)
|
|
527
|
+
if m == "multiple-regression":
|
|
528
|
+
return stat_lib.run_multiple_regression(table, p["y_col"], p["x_cols"])
|
|
529
|
+
if m == "descriptive":
|
|
530
|
+
from ..stats.tests import run_descriptive
|
|
531
|
+
return run_descriptive(table)
|
|
532
|
+
if m in ("mann-whitney", "wilcoxon"):
|
|
533
|
+
alt = p.get("alternative", "two-sided")
|
|
534
|
+
if m == "wilcoxon":
|
|
535
|
+
return stat_lib.run_wilcoxon(table, p["group_a"], p["group_b"], alt)
|
|
536
|
+
return stat_lib.run_mann_whitney(table, p["group_a"], p["group_b"], alt)
|
|
537
|
+
except Exception:
|
|
538
|
+
pass
|
|
539
|
+
return None
|
|
540
|
+
|
|
541
|
+
def _on_axes_changed(self, opts: dict):
|
|
542
|
+
if self._active_gc is not None:
|
|
543
|
+
self._active_gc.options["axis"] = opts
|
|
544
|
+
|
|
545
|
+
# ------------------------------------------------------------------
|
|
546
|
+
# Navigator
|
|
547
|
+
# ------------------------------------------------------------------
|
|
548
|
+
def _on_nav_item(self, section: str, name: str, _kind: str):
|
|
549
|
+
if section == "table":
|
|
550
|
+
t = self.project.get_table(name)
|
|
551
|
+
if t:
|
|
552
|
+
if isinstance(t, GroupedDataTable):
|
|
553
|
+
self.grouped_widget.load_table(t)
|
|
554
|
+
self.stack.setCurrentIndex(3)
|
|
555
|
+
elif isinstance(t, ContingencyTable):
|
|
556
|
+
self.contingency_widget.load_table(t)
|
|
557
|
+
self.stack.setCurrentIndex(4)
|
|
558
|
+
else:
|
|
559
|
+
self.table_widget.load_table(t)
|
|
560
|
+
self.stack.setCurrentIndex(0)
|
|
561
|
+
elif section == "analysis":
|
|
562
|
+
result = next((a for a in self.project.analyses if a.name == name), None)
|
|
563
|
+
if result:
|
|
564
|
+
self.results_widget.show_result(result)
|
|
565
|
+
self.stack.setCurrentIndex(2)
|
|
566
|
+
elif section == "graph":
|
|
567
|
+
gc = next((g for g in self.project.graphs if g.name == name), None)
|
|
568
|
+
if gc:
|
|
569
|
+
self._render_graph(gc)
|
|
570
|
+
|
|
571
|
+
# ------------------------------------------------------------------
|
|
572
|
+
# Statistics
|
|
573
|
+
# ------------------------------------------------------------------
|
|
574
|
+
def _run_descriptive(self):
|
|
575
|
+
t = self._active_table()
|
|
576
|
+
if t is None:
|
|
577
|
+
QMessageBox.warning(self, "No table", "Open a data table first.")
|
|
578
|
+
return
|
|
579
|
+
from ..stats.tests import run_descriptive
|
|
580
|
+
self._save_and_show_result(run_descriptive(t))
|
|
581
|
+
|
|
582
|
+
def _open_analysis(self, tab: int = 0):
|
|
583
|
+
if not self.project.tables:
|
|
584
|
+
QMessageBox.warning(self, "No data", "Create a data table first.")
|
|
585
|
+
return
|
|
586
|
+
dlg = AnalysisDialog(self.project.tables, parent=self, initial_tab=tab)
|
|
587
|
+
if dlg.exec() and dlg.get_result():
|
|
588
|
+
self._save_and_show_result(dlg.get_result())
|
|
589
|
+
|
|
590
|
+
def _save_and_show_result(self, result):
|
|
591
|
+
self.project.analyses.append(result)
|
|
592
|
+
self.navigator.add_analysis(result.name)
|
|
593
|
+
self.results_widget.show_result(result)
|
|
594
|
+
self.stack.setCurrentIndex(2)
|
|
595
|
+
self._mark_modified(f"Analysis: {result.name}")
|
|
596
|
+
|
|
597
|
+
def open_test_wizard(self):
|
|
598
|
+
if not self.project.tables:
|
|
599
|
+
QMessageBox.warning(self, "No data", "Create a data table first.")
|
|
600
|
+
return
|
|
601
|
+
from .test_wizard import TestWizard
|
|
602
|
+
dlg = TestWizard(self.project.tables, parent=self)
|
|
603
|
+
if dlg.exec() and dlg.get_result():
|
|
604
|
+
self._save_and_show_result(dlg.get_result())
|
|
605
|
+
|
|
606
|
+
def open_power_dialog(self):
|
|
607
|
+
from .power_dialog import PowerDialog
|
|
608
|
+
dlg = PowerDialog(parent=self)
|
|
609
|
+
dlg.exec()
|
|
610
|
+
|
|
611
|
+
# ------------------------------------------------------------------
|
|
612
|
+
# Distribution Inspector
|
|
613
|
+
# ------------------------------------------------------------------
|
|
614
|
+
def open_distribution_inspector(self):
|
|
615
|
+
col_tables = [t for t in self.project.tables if isinstance(t, DataTable)]
|
|
616
|
+
if not col_tables:
|
|
617
|
+
QMessageBox.warning(self, "No data", "Create a data table first.")
|
|
618
|
+
return
|
|
619
|
+
from .distribution_inspector import DistributionInspector
|
|
620
|
+
dlg = DistributionInspector(col_tables, parent=self)
|
|
621
|
+
dlg.run_test_requested.connect(self._on_dist_test_requested)
|
|
622
|
+
if dlg.exec():
|
|
623
|
+
# Save distribution-check result to the project
|
|
624
|
+
result = dlg.get_result()
|
|
625
|
+
if result:
|
|
626
|
+
self._save_and_show_result(result)
|
|
627
|
+
# If the inspector recommended a non-parametric test, open the
|
|
628
|
+
# analysis dialog on the t-test tab with the checkbox pre-ticked
|
|
629
|
+
if dlg.nonpar_recommended():
|
|
630
|
+
self._open_analysis_nonpar()
|
|
631
|
+
|
|
632
|
+
def _on_dist_test_requested(self, tab_idx: int):
|
|
633
|
+
"""Called when user clicks 'Run recommended test' inside the inspector."""
|
|
634
|
+
pass # handled via dialog accept + nonpar_recommended()
|
|
635
|
+
|
|
636
|
+
def _open_analysis_nonpar(self):
|
|
637
|
+
"""Open the analysis dialog on tab 0 with non-parametric pre-selected."""
|
|
638
|
+
from .analysis_dialog import AnalysisDialog
|
|
639
|
+
dlg = AnalysisDialog(self.project.tables, parent=self, initial_tab=0)
|
|
640
|
+
dlg._tt_nonpar.setChecked(True)
|
|
641
|
+
if dlg.exec() and dlg.get_result():
|
|
642
|
+
self._save_and_show_result(dlg.get_result())
|
|
643
|
+
|
|
644
|
+
# ------------------------------------------------------------------
|
|
645
|
+
# Graphs
|
|
646
|
+
# ------------------------------------------------------------------
|
|
647
|
+
def new_graph(self, plot_type: str = "bar"):
|
|
648
|
+
if not self.project.tables:
|
|
649
|
+
QMessageBox.warning(self, "No data", "Create a data table first.")
|
|
650
|
+
return
|
|
651
|
+
dlg = GraphOptionsDialog(self.project.tables, initial_type=plot_type, parent=self)
|
|
652
|
+
if not dlg.exec():
|
|
653
|
+
return
|
|
654
|
+
opts = dlg.get_options()
|
|
655
|
+
# Apply journal preset
|
|
656
|
+
plot_styles.set_preset(opts.get("journal_preset", "Default (Staplot)"))
|
|
657
|
+
name = f"{opts['plot_type'].capitalize()} — {opts['table_name']}"
|
|
658
|
+
gc = self.project.add_graph(name, opts["table_name"], opts["plot_type"], opts)
|
|
659
|
+
self.navigator.add_graph(gc.name)
|
|
660
|
+
self._dirty = True
|
|
661
|
+
self._render_graph(gc)
|
|
662
|
+
|
|
663
|
+
def _sig_pairs_for_table(self, table_name: str) -> list[tuple]:
|
|
664
|
+
pairs = []
|
|
665
|
+
for a in self.project.analyses:
|
|
666
|
+
if a.source_table != table_name:
|
|
667
|
+
continue
|
|
668
|
+
d = a.details
|
|
669
|
+
if "p" in d and "group_a" in d and "group_b" in d:
|
|
670
|
+
pairs.append((d["group_a"], d["group_b"], float(d["p"])))
|
|
671
|
+
return pairs
|
|
672
|
+
|
|
673
|
+
def _plot_gc_to_fig(self, gc: GraphConfig):
|
|
674
|
+
"""Render a GraphConfig to a Figure with no side effects (for gallery/layout)."""
|
|
675
|
+
t = self.project.get_table(gc.source_table)
|
|
676
|
+
if t is None:
|
|
677
|
+
return None
|
|
678
|
+
opts = gc.options
|
|
679
|
+
colors = opts.get("colors") or None
|
|
680
|
+
sig_pairs = self._sig_pairs_for_table(gc.source_table) if opts.get("sig_brackets", True) else []
|
|
681
|
+
# Select the stored preset if present (plots apply it while they are built)
|
|
682
|
+
plot_styles.apply(opts.get("journal_preset"))
|
|
683
|
+
try:
|
|
684
|
+
return self._make_fig(gc.plot_type, t, opts, colors, sig_pairs)
|
|
685
|
+
except Exception:
|
|
686
|
+
return None
|
|
687
|
+
|
|
688
|
+
def _make_fig(self, pt: str, t, opts: dict, colors, sig_pairs):
|
|
689
|
+
"""Pure function: build and return a Figure for the given plot type."""
|
|
690
|
+
import matplotlib.pyplot as plt
|
|
691
|
+
if pt in ("box", "violin"):
|
|
692
|
+
return plot_lib.plot_box(t, plot_type=pt,
|
|
693
|
+
show_points=opts.get("show_points", True),
|
|
694
|
+
title=opts.get("title", ""),
|
|
695
|
+
ylabel=opts.get("ylabel", ""),
|
|
696
|
+
colors=colors,
|
|
697
|
+
sig_pairs=sig_pairs or None)
|
|
698
|
+
elif pt == "scatter":
|
|
699
|
+
return plot_lib.plot_scatter(t,
|
|
700
|
+
show_regression=opts.get("show_regression", True),
|
|
701
|
+
title=opts.get("title", ""),
|
|
702
|
+
xlabel=opts.get("xlabel", ""),
|
|
703
|
+
ylabel=opts.get("ylabel", ""),
|
|
704
|
+
colors=colors)
|
|
705
|
+
elif pt == "before_after":
|
|
706
|
+
return plot_lib.plot_before_after(t,
|
|
707
|
+
show_mean=True,
|
|
708
|
+
error_type=opts.get("error_type", "sem"),
|
|
709
|
+
title=opts.get("title", ""),
|
|
710
|
+
ylabel=opts.get("ylabel", ""),
|
|
711
|
+
colors=colors)
|
|
712
|
+
elif pt == "histogram":
|
|
713
|
+
return plot_lib.plot_histogram(t,
|
|
714
|
+
bins=opts.get("hist_bins", "auto"),
|
|
715
|
+
density=opts.get("hist_density", False),
|
|
716
|
+
show_kde=opts.get("hist_kde", True),
|
|
717
|
+
cumulative=opts.get("hist_cumulative", False),
|
|
718
|
+
title=opts.get("title", ""),
|
|
719
|
+
xlabel=opts.get("xlabel", "Value"),
|
|
720
|
+
ylabel=opts.get("ylabel", ""),
|
|
721
|
+
colors=colors)
|
|
722
|
+
elif pt == "survival":
|
|
723
|
+
return plot_lib.plot_survival(t,
|
|
724
|
+
title=opts.get("title", ""),
|
|
725
|
+
xlabel=opts.get("xlabel", "Time"),
|
|
726
|
+
ylabel=opts.get("ylabel", "Survival probability"))
|
|
727
|
+
elif pt == "qq":
|
|
728
|
+
return plot_lib.plot_qq(t,
|
|
729
|
+
title=opts.get("title", ""),
|
|
730
|
+
colors=colors)
|
|
731
|
+
elif pt == "heatmap":
|
|
732
|
+
return plot_lib.plot_heatmap(t,
|
|
733
|
+
mode=opts.get("heatmap_mode", "values"),
|
|
734
|
+
cmap=opts.get("heatmap_cmap", "RdYlBu_r"),
|
|
735
|
+
annotate=opts.get("heatmap_annotate", True),
|
|
736
|
+
title=opts.get("title", ""))
|
|
737
|
+
elif pt == "roc":
|
|
738
|
+
return plot_lib.plot_roc(t,
|
|
739
|
+
label_col=opts.get("roc_label", ""),
|
|
740
|
+
score_col=opts.get("roc_score", ""),
|
|
741
|
+
title=opts.get("title", ""),
|
|
742
|
+
color=colors[0] if colors else None)
|
|
743
|
+
elif pt == "bland_altman":
|
|
744
|
+
return plot_lib.plot_bland_altman(t,
|
|
745
|
+
col_a=opts.get("ba_col_a", ""),
|
|
746
|
+
col_b=opts.get("ba_col_b", ""),
|
|
747
|
+
percentage=opts.get("ba_percentage", False),
|
|
748
|
+
title=opts.get("title", ""),
|
|
749
|
+
color=colors[0] if colors else None)
|
|
750
|
+
elif pt == "grouped_bar":
|
|
751
|
+
return plot_lib.plot_grouped_bar(t,
|
|
752
|
+
error_type=opts.get("error_type", "sem"),
|
|
753
|
+
show_points=opts.get("show_points", True),
|
|
754
|
+
title=opts.get("title", ""),
|
|
755
|
+
ylabel=opts.get("ylabel", ""),
|
|
756
|
+
colors=colors,
|
|
757
|
+
sig_pairs=sig_pairs or None)
|
|
758
|
+
elif pt == "volcano":
|
|
759
|
+
return plot_lib.plot_volcano(t,
|
|
760
|
+
fc_col=opts.get("volcano_fc", ""),
|
|
761
|
+
p_col=opts.get("volcano_p", ""),
|
|
762
|
+
fc_thresh=opts.get("volcano_fc_thresh", 1.0),
|
|
763
|
+
p_thresh=opts.get("volcano_p_thresh", 0.05),
|
|
764
|
+
title=opts.get("title", ""),
|
|
765
|
+
label_col=opts.get("volcano_label"),
|
|
766
|
+
label_top=opts.get("volcano_top", 10),
|
|
767
|
+
color_up=colors[0] if colors else None,
|
|
768
|
+
color_down=colors[1] if colors and len(colors) > 1 else None)
|
|
769
|
+
else: # bar (default)
|
|
770
|
+
return plot_lib.plot_bar(t,
|
|
771
|
+
error_type=opts.get("error_type", "sem"),
|
|
772
|
+
show_points=opts.get("show_points", True),
|
|
773
|
+
title=opts.get("title", ""),
|
|
774
|
+
ylabel=opts.get("ylabel", ""),
|
|
775
|
+
colors=colors,
|
|
776
|
+
sig_pairs=sig_pairs or None)
|
|
777
|
+
|
|
778
|
+
def _render_graph(self, gc: GraphConfig, live_refresh: bool = False):
|
|
779
|
+
t = self.project.get_table(gc.source_table)
|
|
780
|
+
if t is None:
|
|
781
|
+
return
|
|
782
|
+
opts = gc.options
|
|
783
|
+
colors = opts.get("colors") or None
|
|
784
|
+
sig_pairs = (self._sig_pairs_for_table(gc.source_table)
|
|
785
|
+
if opts.get("sig_brackets", True) else [])
|
|
786
|
+
plot_styles.apply(opts.get("journal_preset"))
|
|
787
|
+
try:
|
|
788
|
+
fig = self._make_fig(gc.plot_type, t, opts, colors, sig_pairs)
|
|
789
|
+
axis_opts = opts.get("axis", {})
|
|
790
|
+
self._active_gc = gc
|
|
791
|
+
self.plot_canvas.show_figure(fig, axis_opts if axis_opts else None)
|
|
792
|
+
if not live_refresh:
|
|
793
|
+
self.stack.setCurrentIndex(1)
|
|
794
|
+
except Exception as exc:
|
|
795
|
+
if not live_refresh:
|
|
796
|
+
QMessageBox.critical(self, "Plot error", str(exc))
|
|
797
|
+
else:
|
|
798
|
+
self._status_label.setText(f"Plot error: {exc}")
|
|
799
|
+
|
|
800
|
+
# ------------------------------------------------------------------
|
|
801
|
+
# Multi-panel / gallery
|
|
802
|
+
# ------------------------------------------------------------------
|
|
803
|
+
def _render_for_layout(self, gc: GraphConfig):
|
|
804
|
+
"""Used by FigureLayoutDialog — renders without touching the canvas."""
|
|
805
|
+
return self._plot_gc_to_fig(gc)
|
|
806
|
+
|
|
807
|
+
def open_figure_layout(self):
|
|
808
|
+
if not self.project.graphs:
|
|
809
|
+
QMessageBox.information(self, "No graphs", "Create some graphs first.")
|
|
810
|
+
return
|
|
811
|
+
from .layout_dialog import LayoutDialog
|
|
812
|
+
dlg = LayoutDialog(self.project, self._plot_gc_to_fig, parent=self)
|
|
813
|
+
dlg.exec()
|
|
814
|
+
|
|
815
|
+
def open_graph_gallery(self):
|
|
816
|
+
if not self.project.graphs:
|
|
817
|
+
QMessageBox.information(self, "No graphs", "Create some graphs first.")
|
|
818
|
+
return
|
|
819
|
+
from .graph_gallery import GraphGallery
|
|
820
|
+
dlg = GraphGallery(self.project, self._plot_gc_to_fig, parent=self)
|
|
821
|
+
dlg.graph_selected.connect(self._on_gallery_select)
|
|
822
|
+
dlg.exec()
|
|
823
|
+
|
|
824
|
+
def _on_gallery_select(self, name: str):
|
|
825
|
+
gc = next((g for g in self.project.graphs if g.name == name), None)
|
|
826
|
+
if gc:
|
|
827
|
+
self._render_graph(gc)
|
|
828
|
+
|
|
829
|
+
def export_graph(self):
|
|
830
|
+
self.stack.setCurrentIndex(1)
|
|
831
|
+
self.plot_canvas.export_dialog()
|
|
832
|
+
|
|
833
|
+
# ------------------------------------------------------------------
|
|
834
|
+
# Standard curve
|
|
835
|
+
# ------------------------------------------------------------------
|
|
836
|
+
def open_standard_curve(self):
|
|
837
|
+
fits = [a for a in self.project.analyses
|
|
838
|
+
if "r2" in a.details and "params" in a.details]
|
|
839
|
+
if not fits:
|
|
840
|
+
QMessageBox.information(self, "No fits",
|
|
841
|
+
"Run Statistics → Curve Fitting first.")
|
|
842
|
+
return
|
|
843
|
+
from .standard_curve_dialog import StandardCurveDialog
|
|
844
|
+
dlg = StandardCurveDialog(self.project.analyses, parent=self)
|
|
845
|
+
dlg.exec()
|
|
846
|
+
|
|
847
|
+
# ------------------------------------------------------------------
|
|
848
|
+
# Report
|
|
849
|
+
# ------------------------------------------------------------------
|
|
850
|
+
def open_report(self):
|
|
851
|
+
from .report_dialog import ReportDialog
|
|
852
|
+
dlg = ReportDialog(self.project, self._plot_gc_to_fig, parent=self)
|
|
853
|
+
dlg.exec()
|
|
854
|
+
|
|
855
|
+
# ------------------------------------------------------------------
|
|
856
|
+
# Multiple comparisons
|
|
857
|
+
# ------------------------------------------------------------------
|
|
858
|
+
def open_multiple_comparisons(self):
|
|
859
|
+
from .multiple_comparisons_dialog import MultipleComparisonsDialog
|
|
860
|
+
dlg = MultipleComparisonsDialog(self.project.analyses, parent=self)
|
|
861
|
+
if dlg.exec() and dlg.get_result():
|
|
862
|
+
self._save_and_show_result(dlg.get_result())
|
|
863
|
+
|
|
864
|
+
# ------------------------------------------------------------------
|
|
865
|
+
# Computed column
|
|
866
|
+
# ------------------------------------------------------------------
|
|
867
|
+
def open_computed_column(self):
|
|
868
|
+
col_tables = [t for t in self.project.tables
|
|
869
|
+
if isinstance(t, DataTable)]
|
|
870
|
+
if not col_tables:
|
|
871
|
+
QMessageBox.warning(self, "No table", "Create a data table first.")
|
|
872
|
+
return
|
|
873
|
+
from .computed_column_dialog import ComputedColumnDialog
|
|
874
|
+
dlg = ComputedColumnDialog(self.project.tables, parent=self)
|
|
875
|
+
if dlg.exec():
|
|
876
|
+
t = dlg.get_table()
|
|
877
|
+
if t is not None:
|
|
878
|
+
self.table_widget.load_table(t)
|
|
879
|
+
self.stack.setCurrentIndex(0)
|
|
880
|
+
self._mark_modified(f"Computed column added to: {t.name}")
|
|
881
|
+
self._on_data_changed()
|
|
882
|
+
|
|
883
|
+
# ------------------------------------------------------------------
|
|
884
|
+
# Reshape
|
|
885
|
+
# ------------------------------------------------------------------
|
|
886
|
+
def open_reshape(self):
|
|
887
|
+
col_tables = [t for t in self.project.tables
|
|
888
|
+
if isinstance(t, DataTable)]
|
|
889
|
+
if not col_tables:
|
|
890
|
+
QMessageBox.warning(self, "No table", "Create a data table first.")
|
|
891
|
+
return
|
|
892
|
+
from .reshape_dialog import ReshapeDialog
|
|
893
|
+
dlg = ReshapeDialog(self.project.tables, parent=self)
|
|
894
|
+
if dlg.exec():
|
|
895
|
+
new_t = dlg.get_result()
|
|
896
|
+
if new_t:
|
|
897
|
+
new_t.name = self.project._table_name(new_t.name)
|
|
898
|
+
self.project.tables.append(new_t)
|
|
899
|
+
self.navigator.add_table(new_t.name)
|
|
900
|
+
self.table_widget.load_table(new_t)
|
|
901
|
+
self.stack.setCurrentIndex(0)
|
|
902
|
+
self._mark_modified(f"Created: {new_t.name}")
|
|
903
|
+
|
|
904
|
+
# ------------------------------------------------------------------
|
|
905
|
+
# Export table as CSV
|
|
906
|
+
# ------------------------------------------------------------------
|
|
907
|
+
def export_table_csv(self):
|
|
908
|
+
t = self._active_table()
|
|
909
|
+
if t is None or not isinstance(t, DataTable):
|
|
910
|
+
QMessageBox.warning(self, "No table",
|
|
911
|
+
"Open a standard data table first.")
|
|
912
|
+
return
|
|
913
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
914
|
+
self, "Export Table as CSV", t.name + ".csv",
|
|
915
|
+
"CSV (*.csv);;TSV (*.tsv);;All files (*)")
|
|
916
|
+
if not path:
|
|
917
|
+
return
|
|
918
|
+
sep = "\t" if path.lower().endswith(".tsv") else ","
|
|
919
|
+
try:
|
|
920
|
+
df = t.to_dataframe()
|
|
921
|
+
df.to_csv(path, sep=sep, index=False, encoding="utf-8-sig")
|
|
922
|
+
self._status_label.setText(f"Exported: {os.path.basename(path)}")
|
|
923
|
+
except Exception as exc:
|
|
924
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
925
|
+
|
|
926
|
+
# ------------------------------------------------------------------
|
|
927
|
+
# Data transforms
|
|
928
|
+
# ------------------------------------------------------------------
|
|
929
|
+
def transform_data(self):
|
|
930
|
+
if not self.project.tables:
|
|
931
|
+
QMessageBox.warning(self, "No data", "Create a data table first.")
|
|
932
|
+
return
|
|
933
|
+
from .transform_dialog import TransformDialog
|
|
934
|
+
dlg = TransformDialog(self.project.tables, parent=self)
|
|
935
|
+
if dlg.exec():
|
|
936
|
+
new_t = dlg.get_new_table()
|
|
937
|
+
if new_t:
|
|
938
|
+
new_t.name = self.project._table_name(new_t.name)
|
|
939
|
+
self.project.tables.append(new_t)
|
|
940
|
+
self.navigator.add_table(new_t.name)
|
|
941
|
+
self.table_widget.load_table(new_t)
|
|
942
|
+
self.stack.setCurrentIndex(0)
|
|
943
|
+
self._mark_modified(f"Created: {new_t.name}")
|
|
944
|
+
|
|
945
|
+
# ------------------------------------------------------------------
|
|
946
|
+
# File I/O
|
|
947
|
+
# ------------------------------------------------------------------
|
|
948
|
+
def new_project(self):
|
|
949
|
+
if not self._confirm_discard():
|
|
950
|
+
return
|
|
951
|
+
self._dirty = False
|
|
952
|
+
self.project = Project()
|
|
953
|
+
self._undo_stack.clear()
|
|
954
|
+
self._active_gc = None
|
|
955
|
+
self.navigator.clear_all()
|
|
956
|
+
self._new_default_table()
|
|
957
|
+
self.setWindowTitle("Staplot")
|
|
958
|
+
self._status_label.setText("Ready")
|
|
959
|
+
|
|
960
|
+
def open_project(self):
|
|
961
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
962
|
+
self, "Open Project", "",
|
|
963
|
+
"Staplot Project (*.staplot);;JSON (*.json)")
|
|
964
|
+
if not path or not self._confirm_discard():
|
|
965
|
+
return
|
|
966
|
+
try:
|
|
967
|
+
self.project = Project.load(path)
|
|
968
|
+
self._dirty = False
|
|
969
|
+
self._active_gc = None
|
|
970
|
+
self.navigator.populate(self.project)
|
|
971
|
+
self._load_first_table()
|
|
972
|
+
self.setWindowTitle(f"Staplot — {self.project.name}")
|
|
973
|
+
self._add_to_recent(path)
|
|
974
|
+
except Exception as exc:
|
|
975
|
+
QMessageBox.critical(self, "Open failed", str(exc))
|
|
976
|
+
|
|
977
|
+
def _load_first_table(self):
|
|
978
|
+
if not self.project.tables:
|
|
979
|
+
return
|
|
980
|
+
t = self.project.tables[0]
|
|
981
|
+
if isinstance(t, GroupedDataTable):
|
|
982
|
+
self.grouped_widget.load_table(t)
|
|
983
|
+
self.stack.setCurrentIndex(3)
|
|
984
|
+
elif isinstance(t, ContingencyTable):
|
|
985
|
+
self.contingency_widget.load_table(t)
|
|
986
|
+
self.stack.setCurrentIndex(4)
|
|
987
|
+
else:
|
|
988
|
+
self.table_widget.load_table(t)
|
|
989
|
+
self.stack.setCurrentIndex(0)
|
|
990
|
+
|
|
991
|
+
def _save_to(self, path) -> bool:
|
|
992
|
+
try:
|
|
993
|
+
self.project.save(path)
|
|
994
|
+
except Exception as exc:
|
|
995
|
+
QMessageBox.critical(self, "Save failed",
|
|
996
|
+
f"{exc}\n\nThe previous file (if any) was left unchanged.")
|
|
997
|
+
return False
|
|
998
|
+
self._dirty = False
|
|
999
|
+
self._status_label.setText("Saved")
|
|
1000
|
+
return True
|
|
1001
|
+
|
|
1002
|
+
def save_project(self) -> bool:
|
|
1003
|
+
if self.project.filepath:
|
|
1004
|
+
return self._save_to(self.project.filepath)
|
|
1005
|
+
return self.save_project_as()
|
|
1006
|
+
|
|
1007
|
+
def save_project_as(self) -> bool:
|
|
1008
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
1009
|
+
self, "Save Project", "",
|
|
1010
|
+
"Staplot Project (*.staplot);;JSON (*.json)")
|
|
1011
|
+
if not path or not self._save_to(path):
|
|
1012
|
+
return False
|
|
1013
|
+
self.setWindowTitle(f"Staplot — {self.project.name}")
|
|
1014
|
+
self._add_to_recent(path)
|
|
1015
|
+
return True
|
|
1016
|
+
|
|
1017
|
+
def import_csv(self):
|
|
1018
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1019
|
+
self, "Import CSV", "",
|
|
1020
|
+
"CSV files (*.csv);;TSV (*.tsv *.txt);;All files (*)")
|
|
1021
|
+
if not path:
|
|
1022
|
+
return
|
|
1023
|
+
import csv as csv_lib
|
|
1024
|
+
sep = "\t" if path.lower().endswith((".tsv", ".txt")) else ","
|
|
1025
|
+
try:
|
|
1026
|
+
with open(path, newline="", encoding="utf-8-sig") as f:
|
|
1027
|
+
rows = list(csv_lib.reader(f, delimiter=sep))
|
|
1028
|
+
if not rows:
|
|
1029
|
+
return
|
|
1030
|
+
headers, data_rows = rows[0], rows[1:]
|
|
1031
|
+
name = os.path.splitext(os.path.basename(path))[0]
|
|
1032
|
+
t = self.project.add_table(name)
|
|
1033
|
+
for h in headers:
|
|
1034
|
+
t.add_column(h or f"Col{len(t.columns) + 1}")
|
|
1035
|
+
for r_idx, row in enumerate(data_rows):
|
|
1036
|
+
for c_idx, cell in enumerate(row):
|
|
1037
|
+
if c_idx >= len(t.columns):
|
|
1038
|
+
t.add_column()
|
|
1039
|
+
try:
|
|
1040
|
+
val = float(cell.strip()) if cell.strip() else None
|
|
1041
|
+
except ValueError:
|
|
1042
|
+
val = None
|
|
1043
|
+
t.set_value(r_idx, c_idx, val)
|
|
1044
|
+
self.navigator.add_table(t.name)
|
|
1045
|
+
self.table_widget.load_table(t)
|
|
1046
|
+
self.stack.setCurrentIndex(0)
|
|
1047
|
+
self._mark_modified(f"Imported: {name}")
|
|
1048
|
+
except Exception as exc:
|
|
1049
|
+
QMessageBox.critical(self, "Import failed", str(exc))
|
|
1050
|
+
|
|
1051
|
+
def import_excel(self):
|
|
1052
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1053
|
+
self, "Import Excel", "",
|
|
1054
|
+
"Excel files (*.xlsx *.xls *.xlsm);;All files (*)")
|
|
1055
|
+
if not path:
|
|
1056
|
+
return
|
|
1057
|
+
try:
|
|
1058
|
+
import openpyxl
|
|
1059
|
+
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
|
1060
|
+
sheet = wb.active
|
|
1061
|
+
rows = list(sheet.values)
|
|
1062
|
+
wb.close()
|
|
1063
|
+
if not rows:
|
|
1064
|
+
return
|
|
1065
|
+
headers = [
|
|
1066
|
+
str(h) if h is not None else f"Col{i + 1}"
|
|
1067
|
+
for i, h in enumerate(rows[0])
|
|
1068
|
+
]
|
|
1069
|
+
data_rows = rows[1:]
|
|
1070
|
+
name = os.path.splitext(os.path.basename(path))[0]
|
|
1071
|
+
t = self.project.add_table(name)
|
|
1072
|
+
for h in headers:
|
|
1073
|
+
t.add_column(h)
|
|
1074
|
+
for r_idx, row in enumerate(data_rows):
|
|
1075
|
+
for c_idx, cell in enumerate(row or []):
|
|
1076
|
+
if c_idx >= len(t.columns):
|
|
1077
|
+
t.add_column()
|
|
1078
|
+
try:
|
|
1079
|
+
val = float(cell) if cell is not None else None
|
|
1080
|
+
except (ValueError, TypeError):
|
|
1081
|
+
val = None
|
|
1082
|
+
t.set_value(r_idx, c_idx, val)
|
|
1083
|
+
self.navigator.add_table(t.name)
|
|
1084
|
+
self.table_widget.load_table(t)
|
|
1085
|
+
self.stack.setCurrentIndex(0)
|
|
1086
|
+
self._mark_modified(f"Imported: {name}")
|
|
1087
|
+
except ImportError:
|
|
1088
|
+
QMessageBox.critical(
|
|
1089
|
+
self, "Missing dependency",
|
|
1090
|
+
"openpyxl is required for Excel import.\n"
|
|
1091
|
+
"Install it with: pip install openpyxl"
|
|
1092
|
+
)
|
|
1093
|
+
except Exception as exc:
|
|
1094
|
+
QMessageBox.critical(self, "Import failed", str(exc))
|
|
1095
|
+
|
|
1096
|
+
# ------------------------------------------------------------------
|
|
1097
|
+
def _about(self):
|
|
1098
|
+
QMessageBox.about(
|
|
1099
|
+
self, "About Staplot",
|
|
1100
|
+
"<b>Staplot 0.6</b><br>"
|
|
1101
|
+
"Statistical analysis and publication-quality plotting.<br>"
|
|
1102
|
+
"A GraphPad Prism replacement built in Python.<br><br>"
|
|
1103
|
+
"Features: descriptive stats, t-tests, ANOVA, RM-ANOVA, "
|
|
1104
|
+
"correlation, curve fitting, chi-square, Fisher, Grubbs, "
|
|
1105
|
+
"power analysis, ROC, Bland-Altman, Q-Q, heatmap, survival, "
|
|
1106
|
+
"significance brackets, journal presets, and more.",
|
|
1107
|
+
)
|
|
1108
|
+
|
|
1109
|
+
def _confirm_discard(self) -> bool:
|
|
1110
|
+
"""True when it is fine to drop the current project (saved, or the
|
|
1111
|
+
user chose Save / Discard)."""
|
|
1112
|
+
if not self._dirty:
|
|
1113
|
+
return True
|
|
1114
|
+
ans = QMessageBox.question(
|
|
1115
|
+
self, "Unsaved changes", "Save changes to the current project?",
|
|
1116
|
+
QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Discard
|
|
1117
|
+
| QMessageBox.StandardButton.Cancel)
|
|
1118
|
+
if ans == QMessageBox.StandardButton.Save:
|
|
1119
|
+
return self.save_project()
|
|
1120
|
+
return ans == QMessageBox.StandardButton.Discard
|
|
1121
|
+
|
|
1122
|
+
def closeEvent(self, event):
|
|
1123
|
+
if self._confirm_discard():
|
|
1124
|
+
event.accept()
|
|
1125
|
+
else:
|
|
1126
|
+
event.ignore()
|