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,261 @@
|
|
|
1
|
+
"""Computed-column dialog — add a column defined by a formula."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from qtpy.QtWidgets import (
|
|
7
|
+
QDialog, QVBoxLayout, QFormLayout, QComboBox, QLineEdit,
|
|
8
|
+
QPushButton, QTextEdit, QDialogButtonBox, QLabel, QHBoxLayout,
|
|
9
|
+
)
|
|
10
|
+
from qtpy.QtCore import Qt
|
|
11
|
+
from qtpy.QtGui import QFont
|
|
12
|
+
|
|
13
|
+
from ..models.project import DataTable
|
|
14
|
+
|
|
15
|
+
# Safe function namespace exposed in formulas
|
|
16
|
+
_SAFE_NS: dict = {
|
|
17
|
+
"log": np.log,
|
|
18
|
+
"log2": np.log2,
|
|
19
|
+
"log10": np.log10,
|
|
20
|
+
"ln": np.log,
|
|
21
|
+
"sqrt": np.sqrt,
|
|
22
|
+
"abs": np.abs,
|
|
23
|
+
"exp": np.exp,
|
|
24
|
+
"sin": np.sin,
|
|
25
|
+
"cos": np.cos,
|
|
26
|
+
"tan": np.tan,
|
|
27
|
+
"floor": np.floor,
|
|
28
|
+
"ceil": np.ceil,
|
|
29
|
+
"round": np.round,
|
|
30
|
+
"pi": np.pi,
|
|
31
|
+
"e": np.e,
|
|
32
|
+
"nan": np.nan,
|
|
33
|
+
"inf": np.inf,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _sanitize_name(name: str) -> str:
|
|
38
|
+
"""Turn column names into valid Python identifiers."""
|
|
39
|
+
import re
|
|
40
|
+
s = re.sub(r"[^0-9A-Za-z_]", "_", name)
|
|
41
|
+
if s and s[0].isdigit():
|
|
42
|
+
s = "_" + s
|
|
43
|
+
return s
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_CONSTANTS = {k: v for k, v in _SAFE_NS.items() if not callable(v)}
|
|
47
|
+
_FUNCTIONS = {k: v for k, v in _SAFE_NS.items() if callable(v)}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _formula_namespace(col_data: dict[str, np.ndarray]) -> tuple[dict, int]:
|
|
51
|
+
"""Columns by sanitised name (padded with NaN to a common length), plus
|
|
52
|
+
the constants. Refuses names that collide with each other or shadow a
|
|
53
|
+
function / constant, rather than silently picking one."""
|
|
54
|
+
n = max((len(a) for a in col_data.values()), default=0)
|
|
55
|
+
ns: dict = dict(_CONSTANTS)
|
|
56
|
+
origin: dict = {}
|
|
57
|
+
for raw_name, arr in col_data.items():
|
|
58
|
+
s = _sanitize_name(raw_name)
|
|
59
|
+
if not s:
|
|
60
|
+
raise ValueError(f"column name {raw_name!r} cannot be used in a formula")
|
|
61
|
+
if s in _SAFE_NS:
|
|
62
|
+
raise ValueError(f"column {raw_name!r} shadows the function/constant '{s}'; "
|
|
63
|
+
"rename the column")
|
|
64
|
+
if s in origin:
|
|
65
|
+
raise ValueError(f"columns {origin[s]!r} and {raw_name!r} both become '{s}'; "
|
|
66
|
+
"rename one of them")
|
|
67
|
+
origin[s] = raw_name
|
|
68
|
+
a = np.full(n, np.nan)
|
|
69
|
+
a[:len(arr)] = np.asarray(arr, dtype=float)
|
|
70
|
+
ns[s] = a
|
|
71
|
+
return ns, n
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
_BINOPS = {ast.Add: np.add, ast.Sub: np.subtract, ast.Mult: np.multiply,
|
|
75
|
+
ast.Div: np.true_divide, ast.Pow: np.power, ast.Mod: np.mod,
|
|
76
|
+
ast.FloorDiv: np.floor_divide}
|
|
77
|
+
_UNARY = {ast.USub: np.negative, ast.UAdd: np.positive}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _eval_node(node, ns):
|
|
81
|
+
if isinstance(node, ast.Expression):
|
|
82
|
+
return _eval_node(node.body, ns)
|
|
83
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) \
|
|
84
|
+
and not isinstance(node.value, bool):
|
|
85
|
+
return float(node.value)
|
|
86
|
+
if isinstance(node, ast.Name):
|
|
87
|
+
if node.id not in ns:
|
|
88
|
+
raise ValueError(f"unknown name '{node.id}'")
|
|
89
|
+
return ns[node.id]
|
|
90
|
+
if isinstance(node, ast.BinOp) and type(node.op) in _BINOPS:
|
|
91
|
+
return _BINOPS[type(node.op)](_eval_node(node.left, ns), _eval_node(node.right, ns))
|
|
92
|
+
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY:
|
|
93
|
+
return _UNARY[type(node.op)](_eval_node(node.operand, ns))
|
|
94
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) \
|
|
95
|
+
and node.func.id in _FUNCTIONS and not node.keywords:
|
|
96
|
+
return _FUNCTIONS[node.func.id](*[_eval_node(a, ns) for a in node.args])
|
|
97
|
+
raise ValueError(f"not allowed in a formula: {ast.unparse(node) if hasattr(ast, 'unparse') else type(node).__name__}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def eval_formula(formula: str, col_data: dict[str, np.ndarray]) -> np.ndarray:
|
|
101
|
+
"""
|
|
102
|
+
Evaluate *formula* with each column available as a numpy array (names
|
|
103
|
+
sanitised to identifiers). Only arithmetic, numbers, column names and the
|
|
104
|
+
listed functions/constants are accepted (AST allow-list — no Python eval).
|
|
105
|
+
Returns a float array with one value per table row.
|
|
106
|
+
"""
|
|
107
|
+
ns, n = _formula_namespace(col_data)
|
|
108
|
+
try:
|
|
109
|
+
tree = ast.parse(formula.strip(), mode="eval")
|
|
110
|
+
except SyntaxError as e:
|
|
111
|
+
raise ValueError(f"invalid formula: {e.msg}") from None
|
|
112
|
+
with np.errstate(all="ignore"):
|
|
113
|
+
result = np.asarray(_eval_node(tree, ns), dtype=float)
|
|
114
|
+
if result.ndim == 0:
|
|
115
|
+
result = np.full(n, float(result))
|
|
116
|
+
if result.ndim != 1 or len(result) != n:
|
|
117
|
+
raise ValueError(f"the formula must give one value per row ({n}), got shape {result.shape}")
|
|
118
|
+
return result
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class ComputedColumnDialog(QDialog):
|
|
122
|
+
"""
|
|
123
|
+
Add a new column to an existing DataTable using a numpy formula.
|
|
124
|
+
|
|
125
|
+
Examples
|
|
126
|
+
--------
|
|
127
|
+
``A / B`` divide column A by column B
|
|
128
|
+
``log2(A / B)`` log2-fold change
|
|
129
|
+
``sqrt(A)`` square root
|
|
130
|
+
``A * 100`` percentage scale
|
|
131
|
+
``(A - B) / B * 100`` % change
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def __init__(self, tables: list, parent=None):
|
|
135
|
+
super().__init__(parent)
|
|
136
|
+
self.setWindowTitle("Computed Column")
|
|
137
|
+
self.setMinimumWidth(480)
|
|
138
|
+
|
|
139
|
+
self._tables = [t for t in tables if isinstance(t, DataTable)]
|
|
140
|
+
self._new_col = None # result DataTable ref (unused — col added in place)
|
|
141
|
+
|
|
142
|
+
layout = QVBoxLayout(self)
|
|
143
|
+
|
|
144
|
+
# ── Table / column name selectors ────────────────────────────
|
|
145
|
+
form = QFormLayout()
|
|
146
|
+
|
|
147
|
+
self._table_cb = QComboBox()
|
|
148
|
+
self._table_cb.addItems([t.name for t in self._tables])
|
|
149
|
+
self._table_cb.currentIndexChanged.connect(self._refresh_hint)
|
|
150
|
+
form.addRow("Target table:", self._table_cb)
|
|
151
|
+
|
|
152
|
+
self._col_name = QLineEdit("Result")
|
|
153
|
+
form.addRow("New column name:", self._col_name)
|
|
154
|
+
|
|
155
|
+
self._formula = QLineEdit()
|
|
156
|
+
self._formula.setPlaceholderText("e.g. A / B or log2(A)")
|
|
157
|
+
self._formula.textChanged.connect(self._preview)
|
|
158
|
+
form.addRow("Formula:", self._formula)
|
|
159
|
+
layout.addLayout(form)
|
|
160
|
+
|
|
161
|
+
# ── Available columns hint ────────────────────────────────────
|
|
162
|
+
self._hint_lbl = QLabel()
|
|
163
|
+
self._hint_lbl.setStyleSheet("color: #555; font-size: 10px;")
|
|
164
|
+
self._hint_lbl.setWordWrap(True)
|
|
165
|
+
layout.addWidget(self._hint_lbl)
|
|
166
|
+
|
|
167
|
+
# ── Functions hint ────────────────────────────────────────────
|
|
168
|
+
funcs_lbl = QLabel(
|
|
169
|
+
"Functions: log, log2, log10, sqrt, abs, exp, sin, cos, tan, "
|
|
170
|
+
"floor, ceil, round\n"
|
|
171
|
+
"Constants: pi, e, nan, inf"
|
|
172
|
+
)
|
|
173
|
+
funcs_lbl.setStyleSheet("color: #777; font-size: 10px;")
|
|
174
|
+
funcs_lbl.setWordWrap(True)
|
|
175
|
+
layout.addWidget(funcs_lbl)
|
|
176
|
+
|
|
177
|
+
# ── Preview ───────────────────────────────────────────────────
|
|
178
|
+
preview_btn = QPushButton("Preview (first 8 values)")
|
|
179
|
+
preview_btn.clicked.connect(self._preview)
|
|
180
|
+
layout.addWidget(preview_btn)
|
|
181
|
+
|
|
182
|
+
self._preview_box = QTextEdit()
|
|
183
|
+
self._preview_box.setReadOnly(True)
|
|
184
|
+
mono = QFont("Courier New", 8)
|
|
185
|
+
mono.setStyleHint(QFont.StyleHint.Monospace)
|
|
186
|
+
self._preview_box.setFont(mono)
|
|
187
|
+
self._preview_box.setMaximumHeight(100)
|
|
188
|
+
layout.addWidget(self._preview_box)
|
|
189
|
+
|
|
190
|
+
# ── Buttons ───────────────────────────────────────────────────
|
|
191
|
+
btns = QDialogButtonBox(
|
|
192
|
+
QDialogButtonBox.StandardButton.Ok
|
|
193
|
+
| QDialogButtonBox.StandardButton.Cancel
|
|
194
|
+
)
|
|
195
|
+
btns.button(QDialogButtonBox.StandardButton.Ok).setText("Add Column")
|
|
196
|
+
btns.accepted.connect(self._add_column)
|
|
197
|
+
btns.rejected.connect(self.reject)
|
|
198
|
+
layout.addWidget(btns)
|
|
199
|
+
|
|
200
|
+
self._refresh_hint()
|
|
201
|
+
|
|
202
|
+
# ------------------------------------------------------------------
|
|
203
|
+
def _current_table(self) -> DataTable | None:
|
|
204
|
+
idx = self._table_cb.currentIndex()
|
|
205
|
+
return self._tables[idx] if 0 <= idx < len(self._tables) else None
|
|
206
|
+
|
|
207
|
+
def _col_data(self) -> dict[str, np.ndarray]:
|
|
208
|
+
t = self._current_table()
|
|
209
|
+
if t is None:
|
|
210
|
+
return {}
|
|
211
|
+
return {c.name: c.as_array() for c in t.columns}
|
|
212
|
+
|
|
213
|
+
def _refresh_hint(self):
|
|
214
|
+
t = self._current_table()
|
|
215
|
+
if t is None:
|
|
216
|
+
self._hint_lbl.setText("")
|
|
217
|
+
return
|
|
218
|
+
names = [c.name for c in t.columns]
|
|
219
|
+
safe = [_sanitize_name(n) for n in names]
|
|
220
|
+
pairs = " | ".join(
|
|
221
|
+
f"{raw} → {s}" if raw != s else raw
|
|
222
|
+
for raw, s in zip(names, safe)
|
|
223
|
+
)
|
|
224
|
+
self._hint_lbl.setText(f"Available columns: {pairs}")
|
|
225
|
+
|
|
226
|
+
def _preview(self):
|
|
227
|
+
formula = self._formula.text().strip()
|
|
228
|
+
if not formula:
|
|
229
|
+
self._preview_box.clear()
|
|
230
|
+
return
|
|
231
|
+
try:
|
|
232
|
+
result = eval_formula(formula, self._col_data())
|
|
233
|
+
preview = result[:8]
|
|
234
|
+
lines = [f"[{i}] {v:.6g}" for i, v in enumerate(preview)]
|
|
235
|
+
self._preview_box.setPlainText(
|
|
236
|
+
"\n".join(lines) + (f"\n… ({len(result)} values total)" if len(result) > 8 else "")
|
|
237
|
+
)
|
|
238
|
+
except Exception as exc:
|
|
239
|
+
self._preview_box.setPlainText(f"Error: {exc}")
|
|
240
|
+
|
|
241
|
+
def _add_column(self):
|
|
242
|
+
t = self._current_table()
|
|
243
|
+
if t is None:
|
|
244
|
+
return
|
|
245
|
+
formula = self._formula.text().strip()
|
|
246
|
+
col_name = self._col_name.text().strip() or "Result"
|
|
247
|
+
if not formula:
|
|
248
|
+
self._preview_box.setPlainText("Enter a formula.")
|
|
249
|
+
return
|
|
250
|
+
try:
|
|
251
|
+
result = eval_formula(formula, self._col_data())
|
|
252
|
+
except Exception as exc:
|
|
253
|
+
self._preview_box.setPlainText(f"Error: {exc}")
|
|
254
|
+
return
|
|
255
|
+
|
|
256
|
+
new_col = t.add_column(col_name)
|
|
257
|
+
new_col.values = [None if not np.isfinite(v) else float(v) for v in result]
|
|
258
|
+
self.accept()
|
|
259
|
+
|
|
260
|
+
def get_table(self) -> DataTable | None:
|
|
261
|
+
return self._current_table()
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Contingency table (r × c) data-entry widget."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from qtpy.QtWidgets import (
|
|
5
|
+
QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem,
|
|
6
|
+
QPushButton, QInputDialog, QHeaderView, QLabel,
|
|
7
|
+
)
|
|
8
|
+
from qtpy.QtCore import Qt, Signal
|
|
9
|
+
|
|
10
|
+
from ..models.project import ContingencyTable
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ContingencyTableWidget(QWidget):
|
|
14
|
+
data_changed = Signal()
|
|
15
|
+
|
|
16
|
+
def __init__(self, parent=None):
|
|
17
|
+
super().__init__(parent)
|
|
18
|
+
self._table: ContingencyTable | None = None
|
|
19
|
+
self._loading = False
|
|
20
|
+
|
|
21
|
+
layout = QVBoxLayout(self)
|
|
22
|
+
layout.setContentsMargins(4, 4, 4, 4)
|
|
23
|
+
layout.setSpacing(4)
|
|
24
|
+
|
|
25
|
+
# ── Toolbar ───────────────────────────────────────────────────
|
|
26
|
+
btn_bar = QHBoxLayout()
|
|
27
|
+
for label, slot in [
|
|
28
|
+
("+ Row", self._add_row),
|
|
29
|
+
("− Row", self._remove_row),
|
|
30
|
+
("+ Col", self._add_col),
|
|
31
|
+
("− Col", self._remove_col),
|
|
32
|
+
]:
|
|
33
|
+
btn = QPushButton(label)
|
|
34
|
+
btn.setFixedWidth(64)
|
|
35
|
+
btn.clicked.connect(slot)
|
|
36
|
+
btn_bar.addWidget(btn)
|
|
37
|
+
btn_bar.addStretch()
|
|
38
|
+
layout.addLayout(btn_bar)
|
|
39
|
+
|
|
40
|
+
# ── Table ─────────────────────────────────────────────────────
|
|
41
|
+
self._tw = QTableWidget()
|
|
42
|
+
self._tw.setAlternatingRowColors(True)
|
|
43
|
+
self._tw.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
|
|
44
|
+
self._tw.itemChanged.connect(self._on_cell_changed)
|
|
45
|
+
self._tw.setStyleSheet("""
|
|
46
|
+
QTableWidget { gridline-color: #ddd; border: none; }
|
|
47
|
+
QHeaderView::section {
|
|
48
|
+
background-color: #2d5fa6; color: white;
|
|
49
|
+
padding: 4px; border: 1px solid #1a4a8f; font-weight: bold;
|
|
50
|
+
}
|
|
51
|
+
""")
|
|
52
|
+
layout.addWidget(self._tw)
|
|
53
|
+
layout.addWidget(QLabel(
|
|
54
|
+
"Enter integer counts; double-click a header to rename it."
|
|
55
|
+
))
|
|
56
|
+
|
|
57
|
+
# Allow header renaming
|
|
58
|
+
self._tw.horizontalHeader().sectionDoubleClicked.connect(self._rename_col)
|
|
59
|
+
self._tw.verticalHeader().sectionDoubleClicked.connect(self._rename_row)
|
|
60
|
+
|
|
61
|
+
# ------------------------------------------------------------------
|
|
62
|
+
def load_table(self, table: ContingencyTable):
|
|
63
|
+
self._table = table
|
|
64
|
+
self._reload()
|
|
65
|
+
|
|
66
|
+
def _reload(self):
|
|
67
|
+
if self._table is None:
|
|
68
|
+
return
|
|
69
|
+
t = self._table
|
|
70
|
+
t._ensure_shape()
|
|
71
|
+
nrows, ncols = len(t.row_labels), len(t.col_labels)
|
|
72
|
+
|
|
73
|
+
self._loading = True
|
|
74
|
+
self._tw.blockSignals(True)
|
|
75
|
+
self._tw.setRowCount(nrows)
|
|
76
|
+
self._tw.setColumnCount(ncols)
|
|
77
|
+
self._tw.setHorizontalHeaderLabels(t.col_labels)
|
|
78
|
+
self._tw.setVerticalHeaderLabels(t.row_labels)
|
|
79
|
+
|
|
80
|
+
for r, rl in enumerate(t.row_labels):
|
|
81
|
+
for c, cl in enumerate(t.col_labels):
|
|
82
|
+
val = t.get_count(rl, cl)
|
|
83
|
+
item = QTableWidgetItem(str(val))
|
|
84
|
+
item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
|
85
|
+
self._tw.setItem(r, c, item)
|
|
86
|
+
|
|
87
|
+
self._tw.blockSignals(False)
|
|
88
|
+
self._loading = False
|
|
89
|
+
|
|
90
|
+
# ------------------------------------------------------------------
|
|
91
|
+
def _on_cell_changed(self, item: QTableWidgetItem):
|
|
92
|
+
if self._loading or self._table is None:
|
|
93
|
+
return
|
|
94
|
+
r, c = item.row(), item.column()
|
|
95
|
+
t = self._table
|
|
96
|
+
if r >= len(t.row_labels) or c >= len(t.col_labels):
|
|
97
|
+
return
|
|
98
|
+
try:
|
|
99
|
+
val = int(item.text())
|
|
100
|
+
except ValueError:
|
|
101
|
+
val = 0
|
|
102
|
+
t.set_count(t.row_labels[r], t.col_labels[c], val)
|
|
103
|
+
self.data_changed.emit()
|
|
104
|
+
|
|
105
|
+
# ------------------------------------------------------------------
|
|
106
|
+
def _add_row(self):
|
|
107
|
+
if self._table is None:
|
|
108
|
+
return
|
|
109
|
+
n = len(self._table.row_labels) + 1
|
|
110
|
+
name, ok = QInputDialog.getText(self, "Add Row", "Row label:", text=f"Row {n}")
|
|
111
|
+
if ok and name.strip():
|
|
112
|
+
self._table.add_row(name.strip())
|
|
113
|
+
self._reload()
|
|
114
|
+
|
|
115
|
+
def _remove_row(self):
|
|
116
|
+
if self._table is None:
|
|
117
|
+
return
|
|
118
|
+
r = self._tw.currentRow()
|
|
119
|
+
if 0 <= r < len(self._table.row_labels):
|
|
120
|
+
self._table.remove_row(self._table.row_labels[r])
|
|
121
|
+
self._reload()
|
|
122
|
+
|
|
123
|
+
def _add_col(self):
|
|
124
|
+
if self._table is None:
|
|
125
|
+
return
|
|
126
|
+
n = len(self._table.col_labels) + 1
|
|
127
|
+
name, ok = QInputDialog.getText(self, "Add Column", "Column label:", text=f"Col {n}")
|
|
128
|
+
if ok and name.strip():
|
|
129
|
+
self._table.add_col(name.strip())
|
|
130
|
+
self._reload()
|
|
131
|
+
|
|
132
|
+
def _remove_col(self):
|
|
133
|
+
if self._table is None:
|
|
134
|
+
return
|
|
135
|
+
c = self._tw.currentColumn()
|
|
136
|
+
if 0 <= c < len(self._table.col_labels):
|
|
137
|
+
self._table.remove_col(self._table.col_labels[c])
|
|
138
|
+
self._reload()
|
|
139
|
+
|
|
140
|
+
def _rename_row(self, idx: int):
|
|
141
|
+
if self._table is None or idx >= len(self._table.row_labels):
|
|
142
|
+
return
|
|
143
|
+
old = self._table.row_labels[idx]
|
|
144
|
+
name, ok = QInputDialog.getText(self, "Rename Row", "Label:", text=old)
|
|
145
|
+
if ok and name.strip() and name.strip() != old:
|
|
146
|
+
self._table.row_labels[idx] = name.strip()
|
|
147
|
+
if old in self._table.counts:
|
|
148
|
+
self._table.counts[name.strip()] = self._table.counts.pop(old)
|
|
149
|
+
self._reload()
|
|
150
|
+
|
|
151
|
+
def _rename_col(self, idx: int):
|
|
152
|
+
if self._table is None or idx >= len(self._table.col_labels):
|
|
153
|
+
return
|
|
154
|
+
old = self._table.col_labels[idx]
|
|
155
|
+
name, ok = QInputDialog.getText(self, "Rename Column", "Label:", text=old)
|
|
156
|
+
if ok and name.strip() and name.strip() != old:
|
|
157
|
+
self._table.col_labels[idx] = name.strip()
|
|
158
|
+
self._reload()
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import io
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from qtpy.QtWidgets import (
|
|
6
|
+
QTableWidget, QTableWidgetItem, QAbstractItemView,
|
|
7
|
+
QMenu, QHeaderView, QInputDialog, QApplication, QMessageBox,
|
|
8
|
+
)
|
|
9
|
+
from qtpy.QtCore import Qt, Signal
|
|
10
|
+
from qtpy.QtGui import QColor, QFont, QKeySequence
|
|
11
|
+
|
|
12
|
+
from ..models.project import DataTable
|
|
13
|
+
from .undo_commands import SetCellCommand, AddColumnCommand, RemoveColumnCommand
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DataTableWidget(QTableWidget):
|
|
17
|
+
"""Spreadsheet-like editor bound to a DataTable model."""
|
|
18
|
+
|
|
19
|
+
data_changed = Signal()
|
|
20
|
+
|
|
21
|
+
_HEADER_BG = QColor("#2d5fa6")
|
|
22
|
+
_HEADER_FG = QColor("white")
|
|
23
|
+
_EMPTY_ROWS = 24
|
|
24
|
+
|
|
25
|
+
def __init__(self, parent=None):
|
|
26
|
+
super().__init__(parent)
|
|
27
|
+
self._table: DataTable | None = None
|
|
28
|
+
self._updating = False
|
|
29
|
+
self._undo_stack = None # set by MainWindow after creation
|
|
30
|
+
|
|
31
|
+
self.setAlternatingRowColors(True)
|
|
32
|
+
self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectItems)
|
|
33
|
+
self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
|
34
|
+
self.horizontalHeader().setDefaultSectionSize(110)
|
|
35
|
+
self.verticalHeader().setDefaultSectionSize(22)
|
|
36
|
+
self.verticalHeader().setVisible(True)
|
|
37
|
+
|
|
38
|
+
bold_h = QFont()
|
|
39
|
+
bold_h.setBold(True)
|
|
40
|
+
self.horizontalHeader().setFont(bold_h)
|
|
41
|
+
|
|
42
|
+
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
|
43
|
+
self.customContextMenuRequested.connect(self._show_context_menu)
|
|
44
|
+
self.itemChanged.connect(self._on_item_changed)
|
|
45
|
+
self.horizontalHeader().sectionDoubleClicked.connect(self._rename_column)
|
|
46
|
+
|
|
47
|
+
self.setStyleSheet("""
|
|
48
|
+
QTableWidget { gridline-color: #e0e0e0; border: none; }
|
|
49
|
+
QHeaderView::section {
|
|
50
|
+
background-color: #2d5fa6; color: white;
|
|
51
|
+
padding: 4px; border: 1px solid #1a4a8f; font-weight: bold;
|
|
52
|
+
}
|
|
53
|
+
""")
|
|
54
|
+
|
|
55
|
+
# ------------------------------------------------------------------
|
|
56
|
+
def load_table(self, table: DataTable):
|
|
57
|
+
self._table = table
|
|
58
|
+
self._refresh()
|
|
59
|
+
|
|
60
|
+
_EXCLUDED_BG = QColor("#ffe0e0") # light red background for excluded cells
|
|
61
|
+
|
|
62
|
+
def _refresh(self):
|
|
63
|
+
if self._table is None:
|
|
64
|
+
return
|
|
65
|
+
self._updating = True
|
|
66
|
+
n_cols = len(self._table.columns)
|
|
67
|
+
n_rows = max(self._table.num_rows() + self._EMPTY_ROWS, self._EMPTY_ROWS)
|
|
68
|
+
|
|
69
|
+
self.setColumnCount(n_cols)
|
|
70
|
+
self.setRowCount(n_rows)
|
|
71
|
+
self.setHorizontalHeaderLabels([c.name for c in self._table.columns])
|
|
72
|
+
|
|
73
|
+
for col_idx, col in enumerate(self._table.columns):
|
|
74
|
+
for row_idx, val in enumerate(col.values):
|
|
75
|
+
text = "" if val is None or (isinstance(val, float) and np.isnan(val)) else str(val)
|
|
76
|
+
item = QTableWidgetItem(text)
|
|
77
|
+
item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
|
|
78
|
+
if row_idx in col.excluded:
|
|
79
|
+
item.setBackground(self._EXCLUDED_BG)
|
|
80
|
+
item.setForeground(QColor("#aa0000"))
|
|
81
|
+
self.setItem(row_idx, col_idx, item)
|
|
82
|
+
|
|
83
|
+
self._updating = False
|
|
84
|
+
|
|
85
|
+
# ------------------------------------------------------------------
|
|
86
|
+
def _on_item_changed(self, item: QTableWidgetItem):
|
|
87
|
+
if self._updating or self._table is None:
|
|
88
|
+
return
|
|
89
|
+
row, col_idx = item.row(), item.column()
|
|
90
|
+
text = item.text().strip()
|
|
91
|
+
new_val: float | None
|
|
92
|
+
if text == "":
|
|
93
|
+
new_val = None
|
|
94
|
+
else:
|
|
95
|
+
try:
|
|
96
|
+
new_val = float(text)
|
|
97
|
+
except ValueError:
|
|
98
|
+
item.setText("")
|
|
99
|
+
return
|
|
100
|
+
|
|
101
|
+
# Read old value from model before modifying
|
|
102
|
+
old_val = None
|
|
103
|
+
if col_idx < len(self._table.columns):
|
|
104
|
+
col = self._table.columns[col_idx]
|
|
105
|
+
if row < len(col.values):
|
|
106
|
+
old_val = col.values[row]
|
|
107
|
+
|
|
108
|
+
if old_val == new_val:
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
if self._undo_stack is not None:
|
|
112
|
+
cmd = SetCellCommand(self, self._table, row, col_idx, old_val, new_val)
|
|
113
|
+
self._undo_stack.push(cmd)
|
|
114
|
+
else:
|
|
115
|
+
self._table.set_value(row, col_idx, new_val)
|
|
116
|
+
self.data_changed.emit()
|
|
117
|
+
|
|
118
|
+
def _rename_column(self, index: int):
|
|
119
|
+
if self._table is None or index >= len(self._table.columns):
|
|
120
|
+
return
|
|
121
|
+
old_name = self._table.columns[index].name
|
|
122
|
+
new_name, ok = QInputDialog.getText(self, "Rename Column", "Column name:", text=old_name)
|
|
123
|
+
if ok and new_name.strip() and new_name.strip() != old_name:
|
|
124
|
+
try:
|
|
125
|
+
self._table.rename_column(index, new_name.strip())
|
|
126
|
+
except ValueError as exc:
|
|
127
|
+
QMessageBox.warning(self, "Rename Column", str(exc))
|
|
128
|
+
return
|
|
129
|
+
self.setHorizontalHeaderItem(index, QTableWidgetItem(new_name.strip()))
|
|
130
|
+
self.data_changed.emit()
|
|
131
|
+
|
|
132
|
+
# ------------------------------------------------------------------
|
|
133
|
+
def add_column(self):
|
|
134
|
+
if self._table is None:
|
|
135
|
+
return
|
|
136
|
+
if self._undo_stack is not None:
|
|
137
|
+
self._undo_stack.push(AddColumnCommand(self, self._table, None))
|
|
138
|
+
else:
|
|
139
|
+
self._table.add_column()
|
|
140
|
+
self._refresh()
|
|
141
|
+
|
|
142
|
+
def remove_selected_column(self):
|
|
143
|
+
if self._table is None:
|
|
144
|
+
return
|
|
145
|
+
cols = sorted({i.column() for i in self.selectedItems()}, reverse=True)
|
|
146
|
+
for col_idx in cols:
|
|
147
|
+
if self._undo_stack is not None:
|
|
148
|
+
self._undo_stack.push(RemoveColumnCommand(self, self._table, col_idx))
|
|
149
|
+
else:
|
|
150
|
+
self._table.remove_column(col_idx)
|
|
151
|
+
if not self._undo_stack:
|
|
152
|
+
self._refresh()
|
|
153
|
+
|
|
154
|
+
# ------------------------------------------------------------------
|
|
155
|
+
def _show_context_menu(self, pos):
|
|
156
|
+
menu = QMenu(self)
|
|
157
|
+
menu.addAction("Add Column", self.add_column)
|
|
158
|
+
menu.addAction("Remove Column", self.remove_selected_column)
|
|
159
|
+
menu.addSeparator()
|
|
160
|
+
menu.addAction("Paste from Clipboard", self.paste_from_clipboard)
|
|
161
|
+
menu.addSeparator()
|
|
162
|
+
# Exclude / include selected rows
|
|
163
|
+
rows = sorted({i.row() for i in self.selectedItems()})
|
|
164
|
+
if rows and self._table:
|
|
165
|
+
# Check if any selected rows in any column are currently excluded
|
|
166
|
+
any_excluded = any(
|
|
167
|
+
row in col.excluded
|
|
168
|
+
for row in rows
|
|
169
|
+
for col in self._table.columns
|
|
170
|
+
)
|
|
171
|
+
label = "Include selected rows" if any_excluded else "Exclude selected rows"
|
|
172
|
+
menu.addAction(label, lambda r=rows: self._toggle_exclude_rows(r))
|
|
173
|
+
menu.exec(self.viewport().mapToGlobal(pos))
|
|
174
|
+
|
|
175
|
+
def _toggle_exclude_rows(self, rows: list[int]):
|
|
176
|
+
if self._table is None:
|
|
177
|
+
return
|
|
178
|
+
for row in rows:
|
|
179
|
+
for col in self._table.columns:
|
|
180
|
+
col.toggle_excluded(row)
|
|
181
|
+
self._refresh()
|
|
182
|
+
self.data_changed.emit()
|
|
183
|
+
|
|
184
|
+
# ------------------------------------------------------------------
|
|
185
|
+
@staticmethod
|
|
186
|
+
def _can_float(s: str) -> bool:
|
|
187
|
+
"""Return True if s parses as a float or is empty/whitespace."""
|
|
188
|
+
s = s.strip()
|
|
189
|
+
if s == "":
|
|
190
|
+
return True
|
|
191
|
+
try:
|
|
192
|
+
float(s)
|
|
193
|
+
return True
|
|
194
|
+
except ValueError:
|
|
195
|
+
return False
|
|
196
|
+
|
|
197
|
+
def paste_from_clipboard(self):
|
|
198
|
+
if self._table is None:
|
|
199
|
+
return
|
|
200
|
+
text = QApplication.clipboard().text()
|
|
201
|
+
if not text.strip():
|
|
202
|
+
return
|
|
203
|
+
|
|
204
|
+
# Handle both tab-separated (Excel) and comma-separated (CSV) pasting
|
|
205
|
+
first_line = text.splitlines()[0] if text.strip() else ""
|
|
206
|
+
delimiter = "\t" if "\t" in first_line else ","
|
|
207
|
+
reader = csv.reader(io.StringIO(text), delimiter=delimiter)
|
|
208
|
+
raw_rows = [r for r in reader if any(c.strip() for c in r)]
|
|
209
|
+
if not raw_rows:
|
|
210
|
+
return
|
|
211
|
+
|
|
212
|
+
# ── Header detection ─────────────────────────────────────────
|
|
213
|
+
# A row is treated as a header if ANY non-empty cell is non-numeric
|
|
214
|
+
first_row = raw_rows[0]
|
|
215
|
+
is_header = any(
|
|
216
|
+
c.strip() and not self._can_float(c)
|
|
217
|
+
for c in first_row
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
if is_header:
|
|
221
|
+
headers = [h.strip() for h in first_row]
|
|
222
|
+
data_rows = raw_rows[1:]
|
|
223
|
+
# Map header name → column index, adding new columns as needed
|
|
224
|
+
name_to_idx = {col.name: idx for idx, col in enumerate(self._table.columns)}
|
|
225
|
+
col_mapping: list[int] = []
|
|
226
|
+
for h in headers:
|
|
227
|
+
if not h:
|
|
228
|
+
col_mapping.append(-1) # skip blank header cells
|
|
229
|
+
continue
|
|
230
|
+
if h not in name_to_idx:
|
|
231
|
+
new_idx = len(self._table.columns)
|
|
232
|
+
self._table.add_column(h)
|
|
233
|
+
name_to_idx[h] = new_idx
|
|
234
|
+
col_mapping.append(name_to_idx[h])
|
|
235
|
+
|
|
236
|
+
for r, row_data in enumerate(data_rows):
|
|
237
|
+
for c_idx, cell in enumerate(row_data):
|
|
238
|
+
if c_idx >= len(col_mapping):
|
|
239
|
+
break
|
|
240
|
+
col_idx = col_mapping[c_idx]
|
|
241
|
+
if col_idx < 0:
|
|
242
|
+
continue
|
|
243
|
+
try:
|
|
244
|
+
val = float(cell.strip()) if cell.strip() else None
|
|
245
|
+
except ValueError:
|
|
246
|
+
val = None
|
|
247
|
+
self._table.set_value(r, col_idx, val)
|
|
248
|
+
else:
|
|
249
|
+
# No headers: paste at the current cursor/selection position
|
|
250
|
+
start_row = min((i.row() for i in self.selectedItems()), default=0)
|
|
251
|
+
start_col = min((i.column() for i in self.selectedItems()), default=0)
|
|
252
|
+
for r, row_data in enumerate(raw_rows):
|
|
253
|
+
for c, cell in enumerate(row_data):
|
|
254
|
+
col_idx = start_col + c
|
|
255
|
+
while col_idx >= len(self._table.columns):
|
|
256
|
+
self._table.add_column()
|
|
257
|
+
try:
|
|
258
|
+
val = float(cell.strip()) if cell.strip() else None
|
|
259
|
+
except ValueError:
|
|
260
|
+
val = None
|
|
261
|
+
self._table.set_value(start_row + r, col_idx, val)
|
|
262
|
+
|
|
263
|
+
self._refresh()
|
|
264
|
+
self.data_changed.emit()
|
|
265
|
+
|
|
266
|
+
# ------------------------------------------------------------------
|
|
267
|
+
def keyPressEvent(self, event):
|
|
268
|
+
if event.matches(QKeySequence.StandardKey.Paste):
|
|
269
|
+
self.paste_from_clipboard()
|
|
270
|
+
elif event.key() == Qt.Key.Key_Delete:
|
|
271
|
+
for item in self.selectedItems():
|
|
272
|
+
row, col_idx = item.row(), item.column()
|
|
273
|
+
if self._table:
|
|
274
|
+
self._table.set_value(row, col_idx, None)
|
|
275
|
+
item.setText("")
|
|
276
|
+
else:
|
|
277
|
+
super().keyPressEvent(event)
|