staplot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. staplot/__init__.py +1 -0
  2. staplot/api.py +441 -0
  3. staplot/main.py +21 -0
  4. staplot/models/__init__.py +1 -0
  5. staplot/models/project.py +461 -0
  6. staplot/plots/__init__.py +14 -0
  7. staplot/plots/bar.py +104 -0
  8. staplot/plots/before_after.py +110 -0
  9. staplot/plots/bland_altman.py +73 -0
  10. staplot/plots/box.py +95 -0
  11. staplot/plots/distribution_plot.py +188 -0
  12. staplot/plots/grouped_bar.py +112 -0
  13. staplot/plots/heatmap.py +73 -0
  14. staplot/plots/histogram.py +76 -0
  15. staplot/plots/qq.py +61 -0
  16. staplot/plots/residuals.py +72 -0
  17. staplot/plots/roc_plot.py +40 -0
  18. staplot/plots/scatter.py +61 -0
  19. staplot/plots/significance.py +94 -0
  20. staplot/plots/styles.py +154 -0
  21. staplot/plots/survival.py +78 -0
  22. staplot/plots/volcano.py +110 -0
  23. staplot/stats/__init__.py +15 -0
  24. staplot/stats/anova.py +124 -0
  25. staplot/stats/chi_square.py +85 -0
  26. staplot/stats/correlation.py +71 -0
  27. staplot/stats/curve_fit.py +85 -0
  28. staplot/stats/descriptive.py +52 -0
  29. staplot/stats/distribution.py +223 -0
  30. staplot/stats/multiple_comparisons.py +104 -0
  31. staplot/stats/normality.py +67 -0
  32. staplot/stats/outliers.py +62 -0
  33. staplot/stats/power.py +130 -0
  34. staplot/stats/regression.py +95 -0
  35. staplot/stats/repeated_measures.py +114 -0
  36. staplot/stats/roc.py +196 -0
  37. staplot/stats/tests.py +142 -0
  38. staplot/stats/two_way_anova.py +88 -0
  39. staplot/ui/__init__.py +0 -0
  40. staplot/ui/analysis_dialog.py +406 -0
  41. staplot/ui/axis_dialog.py +104 -0
  42. staplot/ui/computed_column_dialog.py +261 -0
  43. staplot/ui/contingency_table_widget.py +158 -0
  44. staplot/ui/data_table_widget.py +277 -0
  45. staplot/ui/distribution_inspector.py +431 -0
  46. staplot/ui/figure_layout_widget.py +236 -0
  47. staplot/ui/graph_gallery.py +117 -0
  48. staplot/ui/graph_options_dialog.py +325 -0
  49. staplot/ui/grouped_table_widget.py +190 -0
  50. staplot/ui/layout_dialog.py +218 -0
  51. staplot/ui/main_window.py +1126 -0
  52. staplot/ui/multiple_comparisons_dialog.py +168 -0
  53. staplot/ui/navigator.py +88 -0
  54. staplot/ui/plot_canvas.py +251 -0
  55. staplot/ui/power_dialog.py +108 -0
  56. staplot/ui/report_dialog.py +255 -0
  57. staplot/ui/reshape_dialog.py +286 -0
  58. staplot/ui/results_widget.py +19 -0
  59. staplot/ui/standard_curve_dialog.py +150 -0
  60. staplot/ui/test_wizard.py +252 -0
  61. staplot/ui/transform_dialog.py +137 -0
  62. staplot/ui/undo_commands.py +86 -0
  63. staplot-0.1.0.dist-info/METADATA +85 -0
  64. staplot-0.1.0.dist-info/RECORD +68 -0
  65. staplot-0.1.0.dist-info/WHEEL +5 -0
  66. staplot-0.1.0.dist-info/entry_points.txt +2 -0
  67. staplot-0.1.0.dist-info/licenses/LICENSE +24 -0
  68. staplot-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,117 @@
1
+ """Graph gallery — thumbnail grid of all graphs in the project."""
2
+
3
+ from io import BytesIO
4
+
5
+ from qtpy.QtWidgets import (
6
+ QDialog, QVBoxLayout, QGridLayout, QLabel, QWidget,
7
+ QScrollArea, QPushButton, QFrame,
8
+ )
9
+ from qtpy.QtCore import Qt, Signal
10
+ from qtpy.QtGui import QPixmap, QFont
11
+
12
+ from ..plots import styles
13
+
14
+
15
+ @styles.styled
16
+ def _fig_to_pixmap(fig, w: int = 220, h: int = 165) -> QPixmap:
17
+ """Render a matplotlib Figure to a QPixmap at thumbnail size."""
18
+ try:
19
+ buf = BytesIO()
20
+ fig.savefig(buf, format="png", dpi=80, bbox_inches="tight")
21
+ buf.seek(0)
22
+ px = QPixmap()
23
+ px.loadFromData(buf.read())
24
+ return px.scaled(w, h,
25
+ Qt.AspectRatioMode.KeepAspectRatio,
26
+ Qt.TransformationMode.SmoothTransformation)
27
+ except Exception:
28
+ px = QPixmap(w, h)
29
+ px.fill(Qt.GlobalColor.lightGray)
30
+ return px
31
+
32
+
33
+ class _Thumbnail(QFrame):
34
+ """Single graph thumbnail with name label and Open button."""
35
+
36
+ clicked = Signal(str) # graph name
37
+
38
+ def __init__(self, name: str, pixmap: QPixmap, parent=None):
39
+ super().__init__(parent)
40
+ self._name = name
41
+ self.setFrameShape(QFrame.Shape.StyledPanel)
42
+ self.setFixedSize(240, 230)
43
+
44
+ layout = QVBoxLayout(self)
45
+ layout.setContentsMargins(4, 4, 4, 4)
46
+ layout.setSpacing(4)
47
+
48
+ img_lbl = QLabel()
49
+ img_lbl.setPixmap(pixmap)
50
+ img_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
51
+ layout.addWidget(img_lbl)
52
+
53
+ name_lbl = QLabel(name)
54
+ name_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
55
+ name_lbl.setWordWrap(True)
56
+ f = QFont()
57
+ f.setPointSize(8)
58
+ name_lbl.setFont(f)
59
+ layout.addWidget(name_lbl)
60
+
61
+ open_btn = QPushButton("Open")
62
+ open_btn.setFixedHeight(24)
63
+ open_btn.clicked.connect(lambda: self.clicked.emit(self._name))
64
+ layout.addWidget(open_btn)
65
+
66
+
67
+ class GraphGallery(QDialog):
68
+ """Thumbnail gallery of every graph in the project."""
69
+
70
+ graph_selected = Signal(str) # emitted with the graph name
71
+
72
+ def __init__(self, project, render_fn, parent=None):
73
+ """
74
+ project — the Project instance
75
+ render_fn — callable(GraphConfig) → matplotlib.figure.Figure | None
76
+ """
77
+ super().__init__(parent)
78
+ self.setWindowTitle("Graph Gallery")
79
+ self.setMinimumSize(740, 520)
80
+
81
+ layout = QVBoxLayout(self)
82
+
83
+ scroll = QScrollArea()
84
+ scroll.setWidgetResizable(True)
85
+ inner = QWidget()
86
+ grid = QGridLayout(inner)
87
+ grid.setSpacing(12)
88
+ grid.setContentsMargins(8, 8, 8, 8)
89
+
90
+ cols = 3
91
+ visible = 0
92
+ for gc in project.graphs:
93
+ try:
94
+ fig = render_fn(gc)
95
+ except Exception:
96
+ fig = None
97
+ if fig is None:
98
+ continue
99
+ px = _fig_to_pixmap(fig)
100
+ thumb = _Thumbnail(gc.name, px)
101
+ thumb.clicked.connect(self._on_click)
102
+ grid.addWidget(thumb, visible // cols, visible % cols)
103
+ visible += 1
104
+
105
+ if visible == 0:
106
+ grid.addWidget(QLabel("No graphs in this project yet."), 0, 0)
107
+
108
+ scroll.setWidget(inner)
109
+ layout.addWidget(scroll)
110
+
111
+ close_btn = QPushButton("Close")
112
+ close_btn.clicked.connect(self.reject)
113
+ layout.addWidget(close_btn, alignment=Qt.AlignmentFlag.AlignRight)
114
+
115
+ def _on_click(self, name: str):
116
+ self.graph_selected.emit(name)
117
+ self.accept()
@@ -0,0 +1,325 @@
1
+ from qtpy.QtWidgets import (
2
+ QDialog, QVBoxLayout, QFormLayout, QComboBox, QCheckBox,
3
+ QLineEdit, QDialogButtonBox, QLabel, QPushButton, QHBoxLayout,
4
+ QScrollArea, QWidget, QGroupBox, QTabWidget,
5
+ )
6
+ from qtpy.QtGui import QColor
7
+ from qtpy.QtWidgets import QColorDialog
8
+ from qtpy.QtCore import Qt
9
+
10
+ from ..models.project import DataTable, GroupedDataTable
11
+ from ..plots.styles import PALETTE, JOURNAL_PRESETS
12
+
13
+ def _try_float(text: str, default: float) -> float:
14
+ try:
15
+ return float(text.strip())
16
+ except (ValueError, AttributeError):
17
+ return default
18
+
19
+
20
+ def _try_int(text: str, default: int) -> int:
21
+ try:
22
+ return int(text.strip())
23
+ except (ValueError, AttributeError):
24
+ return default
25
+
26
+
27
+ PLOT_TYPES = [
28
+ "bar", "before_after", "scatter", "box", "violin",
29
+ "histogram", "survival", "qq", "heatmap", "roc", "bland_altman",
30
+ "grouped_bar", "volcano",
31
+ ]
32
+
33
+ # Plot types that use per-group colour pickers
34
+ _COLORED_TYPES = {"bar", "before_after", "scatter", "box", "violin",
35
+ "histogram", "qq", "grouped_bar"}
36
+
37
+
38
+ class _ColorButton(QPushButton):
39
+ def __init__(self, color: str, parent=None):
40
+ super().__init__(parent)
41
+ self._color = color
42
+ self.setFixedSize(28, 22)
43
+ self._apply()
44
+ self.clicked.connect(self._pick)
45
+
46
+ def _apply(self):
47
+ self.setStyleSheet(f"background-color: {self._color}; border: 1px solid #666;")
48
+
49
+ def _pick(self):
50
+ c = QColorDialog.getColor(QColor(self._color), self)
51
+ if c.isValid():
52
+ self._color = c.name()
53
+ self._apply()
54
+
55
+ def color(self) -> str:
56
+ return self._color
57
+
58
+
59
+ class GraphOptionsDialog(QDialog):
60
+ def __init__(self, tables: list, initial_type: str = "bar", parent=None):
61
+ super().__init__(parent)
62
+ self.setWindowTitle("New Graph")
63
+ self.setMinimumWidth(430)
64
+ # Include all table types (grouped bar needs GroupedDataTable)
65
+ self._tables = [t for t in tables
66
+ if hasattr(t, "columns") or isinstance(t, GroupedDataTable)]
67
+ self._color_btns: list[_ColorButton] = []
68
+
69
+ layout = QVBoxLayout(self)
70
+ tabs = QTabWidget()
71
+ layout.addWidget(tabs)
72
+
73
+ # ── Tab 1: Graph ──────────────────────────────────────────────
74
+ graph_tab = QWidget()
75
+ form1 = QFormLayout(graph_tab)
76
+
77
+ # Journal preset
78
+ self._preset_cb = QComboBox()
79
+ self._preset_cb.addItems(list(JOURNAL_PRESETS.keys()))
80
+ form1.addRow("Journal preset:", self._preset_cb)
81
+
82
+ self._table_cb = QComboBox()
83
+ self._table_cb.addItems([t.name for t in self._tables])
84
+ self._table_cb.currentIndexChanged.connect(self._rebuild_colors)
85
+ self._table_cb.currentIndexChanged.connect(self._rebuild_col_selectors)
86
+ form1.addRow("Table:", self._table_cb)
87
+
88
+ self._type_cb = QComboBox()
89
+ self._type_cb.addItems(PLOT_TYPES)
90
+ if initial_type in PLOT_TYPES:
91
+ self._type_cb.setCurrentText(initial_type)
92
+ form1.addRow("Graph type:", self._type_cb)
93
+
94
+ self._title_edit = QLineEdit()
95
+ form1.addRow("Title:", self._title_edit)
96
+ self._xlabel_edit = QLineEdit()
97
+ form1.addRow("X label:", self._xlabel_edit)
98
+ self._ylabel_edit = QLineEdit()
99
+ form1.addRow("Y label:", self._ylabel_edit)
100
+
101
+ self._error_cb = QComboBox()
102
+ self._error_cb.addItems(["sem", "sd", "ci95", "none"])
103
+ form1.addRow("Error bars:", self._error_cb)
104
+
105
+ self._points_chk = QCheckBox("Show individual data points")
106
+ self._points_chk.setChecked(True)
107
+ form1.addRow("", self._points_chk)
108
+
109
+ self._regression_chk = QCheckBox("Show regression line (scatter)")
110
+ self._regression_chk.setChecked(True)
111
+ form1.addRow("", self._regression_chk)
112
+
113
+ self._sig_chk = QCheckBox("Auto-add significance brackets from analyses")
114
+ self._sig_chk.setChecked(True)
115
+ form1.addRow("", self._sig_chk)
116
+
117
+ tabs.addTab(graph_tab, "Graph")
118
+
119
+ # ── Tab 2: Colors ─────────────────────────────────────────────
120
+ self._color_tab = QWidget()
121
+ self._color_layout = QVBoxLayout(self._color_tab)
122
+ self._color_layout.addWidget(QLabel("Click a swatch to change group colour:"))
123
+ self._color_scroll = QScrollArea()
124
+ self._color_scroll.setWidgetResizable(True)
125
+ self._color_inner = QWidget()
126
+ self._color_inner_layout = QVBoxLayout(self._color_inner)
127
+ self._color_scroll.setWidget(self._color_inner)
128
+ self._color_layout.addWidget(self._color_scroll)
129
+ tabs.addTab(self._color_tab, "Colors")
130
+
131
+ # ── Tab 3: Histogram ──────────────────────────────────────────
132
+ hist_tab = QWidget()
133
+ form3 = QFormLayout(hist_tab)
134
+ self._bins_edit = QLineEdit("auto")
135
+ form3.addRow("Bins:", self._bins_edit)
136
+ self._density_chk = QCheckBox("Density (normalise area to 1)")
137
+ form3.addRow("", self._density_chk)
138
+ self._kde_chk = QCheckBox("KDE overlay")
139
+ self._kde_chk.setChecked(True)
140
+ form3.addRow("", self._kde_chk)
141
+ self._cumulative_chk = QCheckBox("Cumulative")
142
+ form3.addRow("", self._cumulative_chk)
143
+ tabs.addTab(hist_tab, "Histogram")
144
+
145
+ # ── Tab 4: Bland-Altman ───────────────────────────────────────
146
+ ba_tab = QWidget()
147
+ form4 = QFormLayout(ba_tab)
148
+ self._ba_col_a = QComboBox()
149
+ self._ba_col_b = QComboBox()
150
+ self._ba_pct = QCheckBox("Plot % difference instead of absolute")
151
+ form4.addRow("Method A column:", self._ba_col_a)
152
+ form4.addRow("Method B column:", self._ba_col_b)
153
+ form4.addRow("", self._ba_pct)
154
+ form4.addRow(QLabel(
155
+ "Select 'bland_altman' as graph type in the Graph tab."
156
+ ))
157
+ tabs.addTab(ba_tab, "Bland-Altman")
158
+
159
+ # ── Tab 5: ROC ────────────────────────────────────────────────
160
+ roc_tab = QWidget()
161
+ form5 = QFormLayout(roc_tab)
162
+ self._roc_label_cb = QComboBox()
163
+ self._roc_score_cb = QComboBox()
164
+ form5.addRow("Label column (0/1):", self._roc_label_cb)
165
+ form5.addRow("Score column:", self._roc_score_cb)
166
+ form5.addRow(QLabel(
167
+ "Label column: 0 = negative, 1 = positive.\n"
168
+ "Select 'roc' as graph type in the Graph tab."
169
+ ))
170
+ tabs.addTab(roc_tab, "ROC")
171
+
172
+ # ── Tab 6: Heatmap ────────────────────────────────────────────
173
+ hm_tab = QWidget()
174
+ form6 = QFormLayout(hm_tab)
175
+ self._hm_mode = QComboBox()
176
+ self._hm_mode.addItems(["values", "correlation"])
177
+ form6.addRow("Mode:", self._hm_mode)
178
+ self._hm_cmap = QComboBox()
179
+ self._hm_cmap.addItems(["RdYlBu_r", "RdBu_r", "viridis", "plasma", "coolwarm", "Blues"])
180
+ form6.addRow("Colour map:", self._hm_cmap)
181
+ self._hm_annotate = QCheckBox("Annotate cells with values")
182
+ self._hm_annotate.setChecked(True)
183
+ form6.addRow("", self._hm_annotate)
184
+ form6.addRow(QLabel("Select 'heatmap' as graph type in the Graph tab."))
185
+ tabs.addTab(hm_tab, "Heatmap")
186
+
187
+ # ── Tab 7: Volcano ───────────────────────────────────────────
188
+ vol_tab = QWidget()
189
+ form7 = QFormLayout(vol_tab)
190
+ self._vol_fc = QComboBox()
191
+ self._vol_p = QComboBox()
192
+ self._vol_lbl = QComboBox() # optional label column
193
+ self._vol_fc_thr = QLineEdit("1.0")
194
+ self._vol_p_thr = QLineEdit("0.05")
195
+ self._vol_top = QLineEdit("10")
196
+ form7.addRow("log2 FC column:", self._vol_fc)
197
+ form7.addRow("p-value column:", self._vol_p)
198
+ form7.addRow("Label column (optional):", self._vol_lbl)
199
+ form7.addRow("|log2FC| threshold:", self._vol_fc_thr)
200
+ form7.addRow("p threshold:", self._vol_p_thr)
201
+ form7.addRow("Label top N hits:", self._vol_top)
202
+ form7.addRow(QLabel("Select 'volcano' as graph type in the Graph tab."))
203
+ tabs.addTab(vol_tab, "Volcano")
204
+
205
+ # ── Tab 8: Grouped Bar ────────────────────────────────────────
206
+ grp_tab = QWidget()
207
+ form8 = QFormLayout(grp_tab)
208
+ form8.addRow(QLabel(
209
+ "For a Grouped Bar chart, select a Grouped table in the\n"
210
+ "Graph tab and choose 'grouped_bar' as the graph type.\n\n"
211
+ "Error bars use the Error Bars setting from the Graph tab.\n"
212
+ "Colours are set in the Colors tab."
213
+ ))
214
+ tabs.addTab(grp_tab, "Grouped Bar")
215
+
216
+ btns = QDialogButtonBox(
217
+ QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
218
+ )
219
+ btns.accepted.connect(self.accept)
220
+ btns.rejected.connect(self.reject)
221
+ layout.addWidget(btns)
222
+
223
+ self._rebuild_colors()
224
+ self._rebuild_col_selectors()
225
+
226
+ # ------------------------------------------------------------------
227
+ def _current_table(self):
228
+ idx = self._table_cb.currentIndex()
229
+ return self._tables[idx] if 0 <= idx < len(self._tables) else None
230
+
231
+ def _rebuild_colors(self):
232
+ while self._color_inner_layout.count():
233
+ item = self._color_inner_layout.takeAt(0)
234
+ if item.widget():
235
+ item.widget().deleteLater()
236
+ self._color_btns.clear()
237
+
238
+ t = self._current_table()
239
+ if t is None:
240
+ return
241
+ # GroupedDataTable uses col_groups; DataTable uses columns
242
+ if isinstance(t, GroupedDataTable):
243
+ entries = t.col_groups
244
+ else:
245
+ entries = [c.name for c in t.columns]
246
+
247
+ for i, name in enumerate(entries):
248
+ row_w = QHBoxLayout()
249
+ lbl = QLabel(name)
250
+ lbl.setFixedWidth(130)
251
+ btn = _ColorButton(PALETTE[i % len(PALETTE)])
252
+ self._color_btns.append(btn)
253
+ row_w.addWidget(lbl)
254
+ row_w.addWidget(btn)
255
+ row_w.addStretch()
256
+ container = QWidget()
257
+ container.setLayout(row_w)
258
+ self._color_inner_layout.addWidget(container)
259
+ self._color_inner_layout.addStretch()
260
+
261
+ def _rebuild_col_selectors(self):
262
+ t = self._current_table()
263
+ if isinstance(t, GroupedDataTable):
264
+ names = [] # grouped tables don't expose columns for BA/ROC/volcano
265
+ else:
266
+ names = [c.name for c in t.columns] if t else []
267
+ for cb in [self._ba_col_a, self._ba_col_b,
268
+ self._roc_label_cb, self._roc_score_cb,
269
+ self._vol_fc, self._vol_p]:
270
+ cb.clear()
271
+ cb.addItems(names)
272
+ # Volcano label column: include a "(none)" option
273
+ self._vol_lbl.clear()
274
+ self._vol_lbl.addItem("(none)")
275
+ self._vol_lbl.addItems(names)
276
+ if len(names) >= 2:
277
+ self._ba_col_b.setCurrentIndex(1)
278
+ self._roc_score_cb.setCurrentIndex(1)
279
+ self._vol_p.setCurrentIndex(1)
280
+
281
+ # ------------------------------------------------------------------
282
+ def get_options(self) -> dict:
283
+ bins_txt = self._bins_edit.text().strip()
284
+ try:
285
+ bins = int(bins_txt)
286
+ except ValueError:
287
+ bins = "auto"
288
+
289
+ return {
290
+ "table_name": self._table_cb.currentText(),
291
+ "plot_type": self._type_cb.currentText(),
292
+ "title": self._title_edit.text(),
293
+ "xlabel": self._xlabel_edit.text(),
294
+ "ylabel": self._ylabel_edit.text(),
295
+ "error_type": self._error_cb.currentText(),
296
+ "show_points": self._points_chk.isChecked(),
297
+ "show_regression": self._regression_chk.isChecked(),
298
+ "sig_brackets": self._sig_chk.isChecked(),
299
+ "colors": [btn.color() for btn in self._color_btns],
300
+ "journal_preset": self._preset_cb.currentText(),
301
+ # Histogram
302
+ "hist_bins": bins,
303
+ "hist_density": self._density_chk.isChecked(),
304
+ "hist_kde": self._kde_chk.isChecked(),
305
+ "hist_cumulative": self._cumulative_chk.isChecked(),
306
+ # Bland-Altman
307
+ "ba_col_a": self._ba_col_a.currentText(),
308
+ "ba_col_b": self._ba_col_b.currentText(),
309
+ "ba_percentage": self._ba_pct.isChecked(),
310
+ # ROC
311
+ "roc_label": self._roc_label_cb.currentText(),
312
+ "roc_score": self._roc_score_cb.currentText(),
313
+ # Heatmap
314
+ "heatmap_mode": self._hm_mode.currentText(),
315
+ "heatmap_cmap": self._hm_cmap.currentText(),
316
+ "heatmap_annotate": self._hm_annotate.isChecked(),
317
+ # Volcano
318
+ "volcano_fc": self._vol_fc.currentText(),
319
+ "volcano_p": self._vol_p.currentText(),
320
+ "volcano_label": (self._vol_lbl.currentText()
321
+ if self._vol_lbl.currentText() != "(none)" else None),
322
+ "volcano_fc_thresh": _try_float(self._vol_fc_thr.text(), 1.0),
323
+ "volcano_p_thresh": _try_float(self._vol_p_thr.text(), 0.05),
324
+ "volcano_top": _try_int(self._vol_top.text(), 10),
325
+ }
@@ -0,0 +1,190 @@
1
+ """
2
+ Spreadsheet widget for GroupedDataTable.
3
+
4
+ Layout mirrors Prism's Grouped format:
5
+ - Column groups = Factor A (major header, spans n_reps columns each)
6
+ - Row labels = Factor B (row headers)
7
+ - Replicates = sub-columns A, B, C… under each group
8
+ """
9
+
10
+ import numpy as np
11
+ from qtpy.QtWidgets import (
12
+ QTableWidget, QTableWidgetItem, QAbstractItemView,
13
+ QMenu, QHeaderView, QInputDialog,
14
+ )
15
+ from qtpy.QtCore import Qt, Signal
16
+ from qtpy.QtGui import QColor, QFont, QBrush
17
+
18
+ from ..models.project import GroupedDataTable
19
+
20
+ _GROUP_COLORS = [
21
+ QColor("#dce8f5"), QColor("#fde9d0"), QColor("#d9f0e1"),
22
+ QColor("#f5e0f0"), QColor("#e8e8d5"), QColor("#dde8f5"),
23
+ ]
24
+
25
+
26
+ class GroupedTableWidget(QTableWidget):
27
+ data_changed = Signal()
28
+
29
+ def __init__(self, parent=None):
30
+ super().__init__(parent)
31
+ self._table: GroupedDataTable | None = None
32
+ self._updating = False
33
+
34
+ self.setAlternatingRowColors(False)
35
+ self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectItems)
36
+ self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
37
+ self.horizontalHeader().setDefaultSectionSize(90)
38
+ self.verticalHeader().setDefaultSectionSize(22)
39
+
40
+ bold = QFont()
41
+ bold.setBold(True)
42
+ self.horizontalHeader().setFont(bold)
43
+
44
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
45
+ self.customContextMenuRequested.connect(self._context_menu)
46
+ self.itemChanged.connect(self._on_item_changed)
47
+
48
+ self.setStyleSheet("""
49
+ QTableWidget { gridline-color: #e0e0e0; border: none; }
50
+ """)
51
+
52
+ # ------------------------------------------------------------------
53
+ def load_table(self, table: GroupedDataTable):
54
+ self._table = table
55
+ self._refresh()
56
+
57
+ def _refresh(self):
58
+ if self._table is None:
59
+ return
60
+ t = self._table
61
+ self._updating = True
62
+
63
+ n_groups = len(t.col_groups)
64
+ n_reps = t.n_reps
65
+ n_rows = len(t.row_labels)
66
+ n_data_cols = n_groups * n_reps
67
+
68
+ self.setRowCount(n_rows + 1) # +1 for group-header pseudo-row
69
+ self.setColumnCount(n_data_cols)
70
+
71
+ # Build horizontal header labels: "Group A – 1", "Group A – 2", …
72
+ h_labels = []
73
+ for cg in t.col_groups:
74
+ for rep in range(n_reps):
75
+ h_labels.append(f"{cg} ({chr(65 + rep)})")
76
+ self.setHorizontalHeaderLabels(h_labels)
77
+
78
+ # Row headers: "Group header" + row_labels
79
+ v_labels = ["↑ Group"] + list(t.row_labels)
80
+ self.setVerticalHeaderLabels(v_labels)
81
+
82
+ # Row 0: group-name pseudo-header (merged visually by color)
83
+ for gi, cg in enumerate(t.col_groups):
84
+ col_start = gi * n_reps
85
+ bg = _GROUP_COLORS[gi % len(_GROUP_COLORS)]
86
+ for rep in range(n_reps):
87
+ ci = col_start + rep
88
+ item = QTableWidgetItem(cg if rep == 0 else "")
89
+ item.setBackground(bg)
90
+ item.setFont(QFont() if rep else self._bold_font())
91
+ item.setFlags(Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsEditable)
92
+ item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
93
+ item.setData(Qt.ItemDataRole.UserRole, ("group_header", gi, cg))
94
+ self.setItem(0, ci, item)
95
+
96
+ # Data rows
97
+ for ri, rl in enumerate(t.row_labels):
98
+ for gi, cg in enumerate(t.col_groups):
99
+ col_start = gi * n_reps
100
+ bg = _GROUP_COLORS[gi % len(_GROUP_COLORS)].lighter(110)
101
+ vals = t.data.get(cg, {}).get(rl, [])
102
+ for rep in range(n_reps):
103
+ ci = col_start + rep
104
+ val = vals[rep] if rep < len(vals) else None
105
+ text = "" if val is None or (isinstance(val, float) and np.isnan(val)) else str(val)
106
+ item = QTableWidgetItem(text)
107
+ item.setBackground(bg)
108
+ item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
109
+ self.setItem(ri + 1, ci, item)
110
+
111
+ self._updating = False
112
+
113
+ def _bold_font(self) -> QFont:
114
+ f = QFont()
115
+ f.setBold(True)
116
+ return f
117
+
118
+ # ------------------------------------------------------------------
119
+ def _on_item_changed(self, item: QTableWidgetItem):
120
+ if self._updating or self._table is None:
121
+ return
122
+ row, ci = item.row(), item.column()
123
+ role_data = item.data(Qt.ItemDataRole.UserRole)
124
+
125
+ if row == 0:
126
+ # Rename group header
127
+ if role_data and role_data[0] == "group_header":
128
+ gi = role_data[1]
129
+ new_name = item.text().strip()
130
+ if new_name and gi < len(self._table.col_groups):
131
+ old = self._table.col_groups[gi]
132
+ if old != new_name:
133
+ self._table.col_groups[gi] = new_name
134
+ if old in self._table.data:
135
+ self._table.data[new_name] = self._table.data.pop(old)
136
+ self._refresh()
137
+ self.data_changed.emit()
138
+ return
139
+
140
+ ri = row - 1
141
+ gi = ci // self._table.n_reps
142
+ rep = ci % self._table.n_reps
143
+
144
+ if ri >= len(self._table.row_labels) or gi >= len(self._table.col_groups):
145
+ return
146
+
147
+ rl = self._table.row_labels[ri]
148
+ cg = self._table.col_groups[gi]
149
+ text = item.text().strip()
150
+ try:
151
+ val = float(text) if text else None
152
+ except ValueError:
153
+ item.setText("")
154
+ return
155
+ self._table.set_value(cg, rl, rep, val)
156
+ self.data_changed.emit()
157
+
158
+ # ------------------------------------------------------------------
159
+ def _context_menu(self, pos):
160
+ menu = QMenu(self)
161
+ menu.addAction("Add Column Group", self._add_col_group)
162
+ menu.addAction("Add Row", self._add_row)
163
+ menu.addSeparator()
164
+ menu.addAction("Add Replicate Column", self._add_rep)
165
+ menu.exec(self.viewport().mapToGlobal(pos))
166
+
167
+ def _add_col_group(self):
168
+ if self._table is None:
169
+ return
170
+ name, ok = QInputDialog.getText(self, "New Group", "Group name:")
171
+ if ok and name.strip():
172
+ self._table.add_col_group(name.strip())
173
+ self._refresh()
174
+
175
+ def _add_row(self):
176
+ if self._table is None:
177
+ return
178
+ name, ok = QInputDialog.getText(self, "New Row", "Row label:")
179
+ if ok and name.strip():
180
+ self._table.add_row_label(name.strip())
181
+ self._refresh()
182
+
183
+ def _add_rep(self):
184
+ if self._table is None:
185
+ return
186
+ self._table.n_reps += 1
187
+ for cg in self._table.col_groups:
188
+ for rl in self._table.row_labels:
189
+ self._table.data.setdefault(cg, {}).setdefault(rl, []).append(None)
190
+ self._refresh()