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,150 @@
1
+ """Standard curve dialog — interpolate unknown X values from measured Y values."""
2
+
3
+ import numpy as np
4
+ from qtpy.QtWidgets import (
5
+ QDialog, QVBoxLayout, QFormLayout, QComboBox, QTextEdit,
6
+ QPushButton, QDialogButtonBox, QLabel, QLineEdit,
7
+ )
8
+ from qtpy.QtGui import QFont
9
+
10
+
11
+ class StandardCurveDialog(QDialog):
12
+ """
13
+ Given a previously computed curve-fit result, interpolate unknown
14
+ X values from user-supplied Y values by numerically inverting the model.
15
+ """
16
+
17
+ def __init__(self, analyses: list, parent=None):
18
+ super().__init__(parent)
19
+ self.setWindowTitle("Standard Curve — Interpolate Unknowns")
20
+ self.setMinimumWidth(460)
21
+
22
+ # Only analyses that carry a fitted model with numeric params
23
+ self._fits = [
24
+ a for a in analyses
25
+ if "r2" in a.details and "params" in a.details and "model" in a.details
26
+ ]
27
+
28
+ layout = QVBoxLayout(self)
29
+
30
+ form = QFormLayout()
31
+
32
+ self._fit_cb = QComboBox()
33
+ self._fit_cb.addItems([a.name for a in self._fits])
34
+ self._fit_cb.currentIndexChanged.connect(self._update_info)
35
+ form.addRow("Fitted model:", self._fit_cb)
36
+ layout.addLayout(form)
37
+
38
+ self._info_lbl = QLabel()
39
+ self._info_lbl.setStyleSheet("color: #444; font-size: 10px;")
40
+ layout.addWidget(self._info_lbl)
41
+
42
+ form2 = QFormLayout()
43
+ self._y_edit = QLineEdit()
44
+ self._y_edit.setPlaceholderText("e.g. 0.45, 0.78, 1.23")
45
+ form2.addRow("Unknown Y values:", self._y_edit)
46
+ layout.addLayout(form2)
47
+
48
+ hint = QLabel(
49
+ "Enter measured response (Y) values separated by commas.\n"
50
+ "The corresponding X values (e.g. concentrations) will be interpolated."
51
+ )
52
+ hint.setStyleSheet("color: #666; font-size: 10px;")
53
+ layout.addWidget(hint)
54
+
55
+ calc_btn = QPushButton("Interpolate X values")
56
+ calc_btn.setDefault(True)
57
+ calc_btn.clicked.connect(self._interpolate)
58
+ layout.addWidget(calc_btn)
59
+
60
+ self._result_box = QTextEdit()
61
+ self._result_box.setReadOnly(True)
62
+ mono = QFont("Courier New", 9)
63
+ mono.setStyleHint(QFont.StyleHint.Monospace)
64
+ self._result_box.setFont(mono)
65
+ self._result_box.setMinimumHeight(160)
66
+ layout.addWidget(self._result_box)
67
+
68
+ btns = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
69
+ btns.rejected.connect(self.reject)
70
+ layout.addWidget(btns)
71
+
72
+ if self._fits:
73
+ self._update_info()
74
+ else:
75
+ self._info_lbl.setText(
76
+ "No curve fits available. Run Statistics → Curve Fitting first."
77
+ )
78
+
79
+ # ------------------------------------------------------------------
80
+ def _current_fit(self):
81
+ idx = self._fit_cb.currentIndex()
82
+ return self._fits[idx] if 0 <= idx < len(self._fits) else None
83
+
84
+ def _update_info(self):
85
+ fit = self._current_fit()
86
+ if fit is None:
87
+ self._info_lbl.setText("")
88
+ return
89
+ d = fit.details
90
+ r2 = d.get("r2", float("nan"))
91
+ model = d.get("model", "?")
92
+ params = d.get("params", {})
93
+ p_str = " ".join(f"{k}={v:.4g}" for k, v in params.items())
94
+ self._info_lbl.setText(f"Model: {model} R² = {r2:.4f}\nParams: {p_str}")
95
+
96
+ # ------------------------------------------------------------------
97
+ def _interpolate(self):
98
+ fit = self._current_fit()
99
+ if fit is None:
100
+ self._result_box.setPlainText("No fit selected.")
101
+ return
102
+
103
+ text = self._y_edit.text().strip()
104
+ if not text:
105
+ self._result_box.setPlainText("Enter Y values above.")
106
+ return
107
+ try:
108
+ y_vals = [float(s.strip()) for s in text.split(",") if s.strip()]
109
+ except ValueError:
110
+ self._result_box.setPlainText("Invalid input — enter numbers separated by commas.")
111
+ return
112
+
113
+ d = fit.details
114
+ model_name = d.get("model", "")
115
+ params_dict = d.get("params", {}) # dict {name: value} from curve_fit.py
116
+
117
+ try:
118
+ from ..stats.curve_fit import MODELS
119
+ if model_name not in MODELS:
120
+ raise ValueError(f"Model '{model_name}' not registered.")
121
+
122
+ func, param_names = MODELS[model_name]
123
+ params = [params_dict[n] for n in param_names]
124
+
125
+ from scipy.optimize import brentq
126
+
127
+ lines = [f"{'Y value':>14s} → {'X (interpolated)':>16s}"]
128
+ lines.append("─" * 36)
129
+ for y_target in y_vals:
130
+ try:
131
+ # Try to bracket the solution
132
+ x_lo, x_hi = 1e-12, 1e9
133
+ # Scan a few orders of magnitude to find a sign change
134
+ xs = np.logspace(-6, 6, 500)
135
+ ys = func(xs, *params) - y_target
136
+ sign_changes = np.where(np.diff(np.sign(ys)))[0]
137
+ if len(sign_changes) == 0:
138
+ lines.append(f"{y_target:>14.6g} → no solution found")
139
+ continue
140
+ i = sign_changes[0]
141
+ x_lo, x_hi = float(xs[i]), float(xs[i + 1])
142
+ x_val = brentq(lambda x: func(x, *params) - y_target,
143
+ x_lo, x_hi, xtol=1e-10, maxiter=500)
144
+ lines.append(f"{y_target:>14.6g} → {x_val:>16.6g}")
145
+ except Exception:
146
+ lines.append(f"{y_target:>14.6g} → no solution in search range")
147
+ self._result_box.setPlainText("\n".join(lines))
148
+
149
+ except Exception as exc:
150
+ self._result_box.setPlainText(f"Error: {exc}")
@@ -0,0 +1,252 @@
1
+ """
2
+ 'What test should I use?' wizard.
3
+ Walks the user through: data shape → normality check → recommendation → run.
4
+ """
5
+
6
+ from qtpy.QtWidgets import (
7
+ QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, QStackedWidget,
8
+ QComboBox, QRadioButton, QButtonGroup, QPushButton, QLabel,
9
+ QTextEdit, QGroupBox, QWidget, QFrame,
10
+ )
11
+ from qtpy.QtCore import Qt
12
+ from qtpy.QtGui import QFont
13
+
14
+ from ..models.project import DataTable
15
+ from .. import stats as stat_lib
16
+ from .analysis_dialog import AnalysisDialog
17
+
18
+
19
+ class TestWizard(QDialog):
20
+ """Step-by-step guide: data type → normality → recommended test → run."""
21
+
22
+ def __init__(self, tables: list, parent=None):
23
+ super().__init__(parent)
24
+ self.setWindowTitle("What test should I use?")
25
+ self.setMinimumSize(520, 460)
26
+ self._tables = [t for t in tables if hasattr(t, "columns")]
27
+ self._analysis_result = None
28
+
29
+ outer = QVBoxLayout(self)
30
+
31
+ # Step header
32
+ self._header = QLabel()
33
+ hdr_font = QFont()
34
+ hdr_font.setBold(True)
35
+ hdr_font.setPointSize(11)
36
+ self._header.setFont(hdr_font)
37
+ outer.addWidget(self._header)
38
+
39
+ sep = QFrame(); sep.setFrameShape(QFrame.Shape.HLine)
40
+ outer.addWidget(sep)
41
+
42
+ # Pages
43
+ self._stack = QStackedWidget()
44
+ outer.addWidget(self._stack)
45
+
46
+ self._stack.addWidget(self._page_data()) # 0
47
+ self._stack.addWidget(self._page_normality()) # 1
48
+ self._stack.addWidget(self._page_result()) # 2
49
+
50
+ # Nav buttons
51
+ nav = QHBoxLayout()
52
+ self._back_btn = QPushButton("← Back")
53
+ self._next_btn = QPushButton("Next →")
54
+ self._run_btn = QPushButton("Run Test")
55
+ self._run_btn.setVisible(False)
56
+ nav.addWidget(self._back_btn)
57
+ nav.addStretch()
58
+ nav.addWidget(self._run_btn)
59
+ nav.addWidget(self._next_btn)
60
+ outer.addLayout(nav)
61
+
62
+ self._back_btn.clicked.connect(self._prev)
63
+ self._next_btn.clicked.connect(self._next)
64
+ self._run_btn.clicked.connect(self._run_recommended)
65
+
66
+ self._go_to(0)
67
+
68
+ # ------------------------------------------------------------------
69
+ # Page builders
70
+ # ------------------------------------------------------------------
71
+ def _page_data(self) -> QWidget:
72
+ w = QWidget()
73
+ layout = QFormLayout(w)
74
+
75
+ self._tbl_cb = QComboBox()
76
+ self._tbl_cb.addItems([t.name for t in self._tables])
77
+ layout.addRow("Table:", self._tbl_cb)
78
+
79
+ grp_box = QGroupBox("Number of groups to compare")
80
+ grp_lay = QVBoxLayout(grp_box)
81
+ self._grp2 = QRadioButton("2 groups")
82
+ self._grp2.setChecked(True)
83
+ self._grpN = QRadioButton("3 or more groups")
84
+ grp_lay.addWidget(self._grp2)
85
+ grp_lay.addWidget(self._grpN)
86
+ layout.addRow(grp_box)
87
+
88
+ paired_box = QGroupBox("Are the observations paired / matched?")
89
+ paired_lay = QVBoxLayout(paired_box)
90
+ self._paired_yes = QRadioButton("Yes — same subjects measured twice (or matched pairs)")
91
+ self._paired_no = QRadioButton("No — independent groups")
92
+ self._paired_no.setChecked(True)
93
+ paired_lay.addWidget(self._paired_yes)
94
+ paired_lay.addWidget(self._paired_no)
95
+ layout.addRow(paired_box)
96
+
97
+ return w
98
+
99
+ def _page_normality(self) -> QWidget:
100
+ w = QWidget()
101
+ layout = QVBoxLayout(w)
102
+ layout.addWidget(QLabel("Running Shapiro-Wilk normality test on each group…"))
103
+ self._norm_result = QTextEdit()
104
+ self._norm_result.setReadOnly(True)
105
+ mono = QFont("Courier New", 8)
106
+ mono.setStyleHint(QFont.StyleHint.Monospace)
107
+ self._norm_result.setFont(mono)
108
+ layout.addWidget(self._norm_result)
109
+ return w
110
+
111
+ def _page_result(self) -> QWidget:
112
+ w = QWidget()
113
+ layout = QVBoxLayout(w)
114
+
115
+ self._rec_label = QLabel()
116
+ rec_font = QFont()
117
+ rec_font.setPointSize(11)
118
+ self._rec_label.setFont(rec_font)
119
+ self._rec_label.setWordWrap(True)
120
+ layout.addWidget(self._rec_label)
121
+
122
+ self._reason_label = QLabel()
123
+ self._reason_label.setWordWrap(True)
124
+ self._reason_label.setStyleSheet("color: #555555;")
125
+ layout.addWidget(self._reason_label)
126
+
127
+ layout.addStretch()
128
+ return w
129
+
130
+ # ------------------------------------------------------------------
131
+ # Navigation
132
+ # ------------------------------------------------------------------
133
+ def _go_to(self, idx: int):
134
+ self._stack.setCurrentIndex(idx)
135
+ headers = [
136
+ "Step 1 of 3 — Describe your data",
137
+ "Step 2 of 3 — Normality check",
138
+ "Step 3 of 3 — Recommended test",
139
+ ]
140
+ self._header.setText(headers[idx])
141
+ self._back_btn.setEnabled(idx > 0)
142
+ last = idx == 2
143
+ self._next_btn.setVisible(not last)
144
+ self._run_btn.setVisible(last)
145
+
146
+ def _prev(self):
147
+ self._go_to(max(0, self._stack.currentIndex() - 1))
148
+
149
+ def _next(self):
150
+ idx = self._stack.currentIndex()
151
+ if idx == 0:
152
+ self._run_normality()
153
+ self._go_to(1)
154
+ elif idx == 1:
155
+ self._build_recommendation()
156
+ self._go_to(2)
157
+
158
+ # ------------------------------------------------------------------
159
+ # Logic
160
+ # ------------------------------------------------------------------
161
+ def _current_table(self) -> DataTable | None:
162
+ i = self._tbl_cb.currentIndex()
163
+ return self._tables[i] if 0 <= i < len(self._tables) else None
164
+
165
+ def _run_normality(self):
166
+ t = self._current_table()
167
+ if t is None:
168
+ self._norm_result.setPlainText("No table selected.")
169
+ return
170
+ result = stat_lib.run_normality(t)
171
+ self._norm_result.setPlainText(result.summary_text)
172
+ self._norm_details = result.details
173
+
174
+ def _all_normal(self) -> bool:
175
+ if not hasattr(self, "_norm_details"):
176
+ return True
177
+ return all(
178
+ v.get("passed", True)
179
+ for v in self._norm_details.values()
180
+ if isinstance(v, dict)
181
+ )
182
+
183
+ def _build_recommendation(self):
184
+ two_groups = self._grp2.isChecked()
185
+ paired = self._paired_yes.isChecked()
186
+ normal = self._all_normal()
187
+
188
+ if two_groups:
189
+ if paired:
190
+ if normal:
191
+ test = "Paired t-test"
192
+ reason = "Two groups, paired data, both pass normality → parametric paired test."
193
+ self._recommended = ("ttest", True, "two-sided")
194
+ else:
195
+ test = "Wilcoxon signed-rank test"
196
+ reason = "Two groups, paired data, but normality failed → non-parametric paired test."
197
+ self._recommended = ("wilcoxon", True, "two-sided")
198
+ else:
199
+ if normal:
200
+ test = "Unpaired t-test (Welch)"
201
+ reason = "Two independent groups, both pass normality → Welch's t-test (doesn't assume equal variance)."
202
+ self._recommended = ("ttest", False, "two-sided")
203
+ else:
204
+ test = "Mann-Whitney U test"
205
+ reason = "Two independent groups, normality failed → non-parametric alternative to t-test."
206
+ self._recommended = ("mann-whitney", False, "two-sided")
207
+ else:
208
+ if normal:
209
+ test = "One-way ANOVA + Tukey post-hoc"
210
+ reason = "3+ groups, all pass normality → parametric omnibus test with pairwise comparisons."
211
+ self._recommended = ("anova",)
212
+ else:
213
+ test = "Kruskal-Wallis + Dunn post-hoc"
214
+ reason = "3+ groups, normality failed → non-parametric omnibus test."
215
+ self._recommended = ("kruskal",)
216
+
217
+ self._rec_label.setText(f"✔ Recommended test: {test}")
218
+ self._reason_label.setText(reason)
219
+
220
+ def _run_recommended(self):
221
+ t = self._current_table()
222
+ if t is None or not hasattr(self, "_recommended"):
223
+ return
224
+ rec = self._recommended
225
+ groups = [c.name for c in t.columns]
226
+
227
+ try:
228
+ if rec[0] == "ttest":
229
+ if len(groups) < 2:
230
+ raise ValueError("Need at least 2 columns.")
231
+ r = stat_lib.run_ttest(t, groups[0], groups[1], paired=rec[1], alternative=rec[2])
232
+ elif rec[0] == "wilcoxon":
233
+ if len(groups) < 2:
234
+ raise ValueError("Need at least 2 columns.")
235
+ r = stat_lib.run_wilcoxon(t, groups[0], groups[1], alternative=rec[2])
236
+ elif rec[0] == "mann-whitney":
237
+ if len(groups) < 2:
238
+ raise ValueError("Need at least 2 columns.")
239
+ r = stat_lib.run_mann_whitney(t, groups[0], groups[1], alternative=rec[2])
240
+ elif rec[0] == "anova":
241
+ r = stat_lib.run_one_way_anova(t)
242
+ else:
243
+ r = stat_lib.run_kruskal_wallis(t)
244
+
245
+ self._analysis_result = r
246
+ self.accept()
247
+ except Exception as exc:
248
+ from qtpy.QtWidgets import QMessageBox
249
+ QMessageBox.critical(self, "Error", str(exc))
250
+
251
+ def get_result(self):
252
+ return self._analysis_result
@@ -0,0 +1,137 @@
1
+ """Data transform dialog — create a new table by applying a function to all columns."""
2
+
3
+ import numpy as np
4
+
5
+ from qtpy.QtWidgets import (
6
+ QDialog, QVBoxLayout, QFormLayout, QComboBox, QDoubleSpinBox,
7
+ QLineEdit, QDialogButtonBox, QLabel, QCheckBox, QGroupBox,
8
+ )
9
+ from qtpy.QtCore import Qt
10
+
11
+ from ..models.project import DataTable, Project
12
+
13
+
14
+ TRANSFORMS = {
15
+ "Log₁₀(Y)": lambda y, _k, _c: np.log10(np.where(y > 0, y, np.nan)),
16
+ "Ln(Y)": lambda y, _k, _c: np.log(np.where(y > 0, y, np.nan)),
17
+ "√Y": lambda y, _k, _c: np.sqrt(np.where(y >= 0, y, np.nan)),
18
+ "Y²": lambda y, _k, _c: y ** 2,
19
+ "1 / Y": lambda y, _k, _c: np.where(y != 0, 1.0 / y, np.nan),
20
+ "Y × k": lambda y, k, _c: y * k,
21
+ "Y + k": lambda y, k, _c: y + k,
22
+ "100 × Y / max(Y)":lambda y, _k, _c: 100.0 * y / np.nanmax(y) if np.nanmax(y) != 0 else y,
23
+ "Z-score": lambda y, _k, _c: (y - np.nanmean(y)) / np.nanstd(y, ddof=1)
24
+ if np.nanstd(y, ddof=1) > 0 else y * 0,
25
+ "% of control": None, # special-cased below
26
+ }
27
+
28
+
29
+ class TransformDialog(QDialog):
30
+ def __init__(self, tables: list, parent=None):
31
+ super().__init__(parent)
32
+ self.setWindowTitle("Transform Data")
33
+ self.setMinimumWidth(360)
34
+ self._tables = tables
35
+ self._new_table: DataTable | None = None
36
+
37
+ layout = QVBoxLayout(self)
38
+ form = QFormLayout()
39
+
40
+ self._table_cb = QComboBox()
41
+ self._table_cb.addItems([t.name for t in tables if hasattr(t, "columns")])
42
+ self._table_cb.currentIndexChanged.connect(self._refresh_controls)
43
+ form.addRow("Source table:", self._table_cb)
44
+
45
+ self._transform_cb = QComboBox()
46
+ self._transform_cb.addItems(list(TRANSFORMS.keys()))
47
+ self._transform_cb.currentTextChanged.connect(self._refresh_controls)
48
+ form.addRow("Transform:", self._transform_cb)
49
+
50
+ self._k_spin = QDoubleSpinBox()
51
+ self._k_spin.setRange(-1e9, 1e9)
52
+ self._k_spin.setValue(1.0)
53
+ self._k_spin.setDecimals(4)
54
+ self._k_label = QLabel("k:")
55
+ form.addRow(self._k_label, self._k_spin)
56
+
57
+ self._ctrl_cb = QComboBox()
58
+ self._ctrl_label = QLabel("Control column:")
59
+ form.addRow(self._ctrl_label, self._ctrl_cb)
60
+
61
+ self._out_name = QLineEdit()
62
+ form.addRow("Output table name:", self._out_name)
63
+
64
+ layout.addLayout(form)
65
+
66
+ btns = QDialogButtonBox(
67
+ QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
68
+ )
69
+ btns.accepted.connect(self._apply)
70
+ btns.rejected.connect(self.reject)
71
+ layout.addWidget(btns)
72
+
73
+ self._refresh_controls()
74
+
75
+ # ------------------------------------------------------------------
76
+ def _src_table(self) -> DataTable | None:
77
+ idx = self._table_cb.currentIndex()
78
+ col_tables = [t for t in self._tables if hasattr(t, "columns")]
79
+ return col_tables[idx] if 0 <= idx < len(col_tables) else None
80
+
81
+ def _refresh_controls(self):
82
+ transform = self._transform_cb.currentText()
83
+ needs_k = transform in ("Y × k", "Y + k")
84
+ needs_ctrl = transform == "% of control"
85
+ self._k_label.setVisible(needs_k)
86
+ self._k_spin.setVisible(needs_k)
87
+ self._ctrl_label.setVisible(needs_ctrl)
88
+ self._ctrl_cb.setVisible(needs_ctrl)
89
+
90
+ t = self._src_table()
91
+ if t:
92
+ self._ctrl_cb.clear()
93
+ self._ctrl_cb.addItems([c.name for c in t.columns])
94
+ self._out_name.setText(f"{t.name} — {transform}")
95
+
96
+ # ------------------------------------------------------------------
97
+ def _apply(self):
98
+ t = self._src_table()
99
+ if t is None:
100
+ return
101
+
102
+ transform = self._transform_cb.currentText()
103
+ k = self._k_spin.value()
104
+ ctrl_name = self._ctrl_cb.currentText()
105
+ out_name = self._out_name.text().strip() or f"{t.name} (transformed)"
106
+
107
+ new_table = DataTable(out_name)
108
+ func = TRANSFORMS.get(transform)
109
+
110
+ ctrl_mean = 1.0
111
+ if transform == "% of control":
112
+ ctrl_col = next((c for c in t.columns if c.name == ctrl_name), None)
113
+ if ctrl_col:
114
+ ctrl_mean = float(np.nanmean(ctrl_col.valid_values())) or 1.0
115
+
116
+ for col in t.columns:
117
+ arr = col.as_array()
118
+ if transform == "% of control":
119
+ transformed = 100.0 * arr / ctrl_mean
120
+ elif func is not None:
121
+ try:
122
+ transformed = func(arr, k, None)
123
+ except Exception:
124
+ transformed = arr.copy()
125
+ else:
126
+ transformed = arr.copy()
127
+
128
+ new_col = new_table.add_column(col.name)
129
+ new_col.values = [
130
+ None if np.isnan(v) else float(v) for v in transformed
131
+ ]
132
+
133
+ self._new_table = new_table
134
+ self.accept()
135
+
136
+ def get_new_table(self) -> DataTable | None:
137
+ return self._new_table
@@ -0,0 +1,86 @@
1
+ from qtpy.QtWidgets import QUndoCommand, QTableWidgetItem
2
+ from qtpy.QtCore import Qt
3
+
4
+
5
+ class SetCellCommand(QUndoCommand):
6
+ """Reversible single-cell edit on a DataTable + its widget view."""
7
+
8
+ _MERGE_ID = 0xA1
9
+
10
+ def __init__(self, widget, table, row: int, col: int, old_val, new_val):
11
+ super().__init__("Edit cell")
12
+ self._widget = widget
13
+ self._table = table
14
+ self._row = row
15
+ self._col = col
16
+ self._old = old_val
17
+ self._new = new_val
18
+ self._first = True # widget already shows new_val on first push
19
+
20
+ def _apply(self, value, skip_widget: bool = False):
21
+ self._table.set_value(self._row, self._col, value)
22
+ if not skip_widget:
23
+ self._widget._updating = True
24
+ item = self._widget.item(self._row, self._col)
25
+ if item is None:
26
+ item = QTableWidgetItem()
27
+ item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
28
+ self._widget.setItem(self._row, self._col, item)
29
+ item.setText("" if value is None else str(value))
30
+ self._widget._updating = False
31
+
32
+ def redo(self):
33
+ self._apply(self._new, skip_widget=self._first)
34
+ self._first = False
35
+
36
+ def undo(self):
37
+ self._apply(self._old)
38
+
39
+ def id(self):
40
+ return self._MERGE_ID
41
+
42
+ def mergeWith(self, other) -> bool:
43
+ if (
44
+ isinstance(other, SetCellCommand)
45
+ and other._widget is self._widget
46
+ and other._row == self._row
47
+ and other._col == self._col
48
+ ):
49
+ self._new = other._new
50
+ return True
51
+ return False
52
+
53
+
54
+ class AddColumnCommand(QUndoCommand):
55
+ def __init__(self, widget, table, name: str):
56
+ super().__init__("Add column")
57
+ self._widget = widget
58
+ self._table = table
59
+ self._name = name
60
+
61
+ def redo(self):
62
+ self._table.add_column(self._name)
63
+ self._widget._refresh()
64
+
65
+ def undo(self):
66
+ self._table.remove_column(len(self._table.columns) - 1)
67
+ self._widget._refresh()
68
+
69
+
70
+ class RemoveColumnCommand(QUndoCommand):
71
+ def __init__(self, widget, table, index: int):
72
+ super().__init__("Remove column")
73
+ self._widget = widget
74
+ self._table = table
75
+ self._index = index
76
+ # keep the column object itself: values AND exclusions (and any
77
+ # future per-column state) come back on undo
78
+ self._column = table.columns[index]
79
+
80
+ def redo(self):
81
+ self._table.remove_column(self._index)
82
+ self._widget._refresh()
83
+
84
+ def undo(self):
85
+ self._table.columns.insert(self._index, self._column)
86
+ self._widget._refresh()