statstudio 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.
- statstudio/__init__.py +9 -0
- statstudio/__main__.py +3 -0
- statstudio/app.py +83 -0
- statstudio/cli.py +116 -0
- statstudio/core/__init__.py +3 -0
- statstudio/core/archive.py +27 -0
- statstudio/core/commands.py +67 -0
- statstudio/core/formula_catalog.py +74 -0
- statstudio/core/formulas.py +605 -0
- statstudio/core/joins.py +123 -0
- statstudio/core/project.py +358 -0
- statstudio/core/runtime.py +321 -0
- statstudio/core/scripting.py +594 -0
- statstudio/core/table.py +796 -0
- statstudio/core/transform.py +450 -0
- statstudio/feature_help.py +595 -0
- statstudio/io/__init__.py +3 -0
- statstudio/io/docx.py +201 -0
- statstudio/io/export.py +99 -0
- statstudio/io/file_import.py +199 -0
- statstudio/io/odbc.py +334 -0
- statstudio/io/sample_data.py +164 -0
- statstudio/io/table_io.py +118 -0
- statstudio/plots/__init__.py +19 -0
- statstudio/plots/advanced.py +651 -0
- statstudio/plots/basic.py +957 -0
- statstudio/plots/bayesian_plots.py +94 -0
- statstudio/plots/common.py +334 -0
- statstudio/plots/diagnostics.py +214 -0
- statstudio/plots/doe_plots.py +235 -0
- statstudio/plots/plotly_builders.py +719 -0
- statstudio/plots/predictive_plots.py +72 -0
- statstudio/plots/registry.py +251 -0
- statstudio/plugins.py +111 -0
- statstudio/resources/help_topics.json +13195 -0
- statstudio/resources/logo.ico +0 -0
- statstudio/resources/logo.png +0 -0
- statstudio/resources/statstudio.svg +8 -0
- statstudio/stats/__init__.py +42 -0
- statstudio/stats/bayesian.py +1094 -0
- statstudio/stats/bayesian_optimization.py +590 -0
- statstudio/stats/common.py +140 -0
- statstudio/stats/correlation.py +135 -0
- statstudio/stats/custom_doe.py +1714 -0
- statstudio/stats/descriptive.py +200 -0
- statstudio/stats/desirability.py +132 -0
- statstudio/stats/distributions.py +331 -0
- statstudio/stats/doe.py +1070 -0
- statstudio/stats/hypothesis.py +1305 -0
- statstudio/stats/multivariate.py +307 -0
- statstudio/stats/optimal_doe.py +264 -0
- statstudio/stats/power.py +194 -0
- statstudio/stats/predictive.py +605 -0
- statstudio/stats/profiler.py +379 -0
- statstudio/stats/quality.py +1218 -0
- statstudio/stats/regression.py +1600 -0
- statstudio/stats/results.py +235 -0
- statstudio/stats/simulator.py +95 -0
- statstudio/stats/survival.py +637 -0
- statstudio/stats/timeseries.py +643 -0
- statstudio/stats/tolerance.py +154 -0
- statstudio/ui/__init__.py +0 -0
- statstudio/ui/analysis_hub.py +271 -0
- statstudio/ui/command_catalog.py +460 -0
- statstudio/ui/command_palette.py +55 -0
- statstudio/ui/console.py +239 -0
- statstudio/ui/dialogs/__init__.py +0 -0
- statstudio/ui/dialogs/advanced_dialogs.py +392 -0
- statstudio/ui/dialogs/base.py +537 -0
- statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
- statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
- statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
- statstudio/ui/dialogs/doe_dialogs.py +220 -0
- statstudio/ui/dialogs/extended_dialogs.py +665 -0
- statstudio/ui/dialogs/graph_builder.py +139 -0
- statstudio/ui/dialogs/help_dialog.py +207 -0
- statstudio/ui/dialogs/help_topics.py +280 -0
- statstudio/ui/dialogs/lazy.py +184 -0
- statstudio/ui/dialogs/odbc_dialog.py +311 -0
- statstudio/ui/dialogs/plot_dialog.py +1385 -0
- statstudio/ui/dialogs/report_composer.py +218 -0
- statstudio/ui/dialogs/script_dialogs.py +267 -0
- statstudio/ui/dialogs/stats_dialogs.py +1688 -0
- statstudio/ui/dialogs/table_dialogs.py +997 -0
- statstudio/ui/dialogs/window.py +58 -0
- statstudio/ui/docks/__init__.py +0 -0
- statstudio/ui/formula_editor.py +121 -0
- statstudio/ui/icons.py +257 -0
- statstudio/ui/jobs.py +179 -0
- statstudio/ui/main_window.py +3934 -0
- statstudio/ui/plot_interaction.py +178 -0
- statstudio/ui/profiler_widget.py +437 -0
- statstudio/ui/recent.py +82 -0
- statstudio/ui/reports/__init__.py +0 -0
- statstudio/ui/reports/report_view.py +1632 -0
- statstudio/ui/script_jobs.py +35 -0
- statstudio/ui/scripts_panel.py +271 -0
- statstudio/ui/table_document.py +233 -0
- statstudio/ui/table_model.py +285 -0
- statstudio/ui/table_view.py +285 -0
- statstudio/ui/theme.py +645 -0
- statstudio/ui/welcome.py +453 -0
- statstudio/ui/window_controls.py +53 -0
- statstudio/ui/workers.py +53 -0
- statstudio-0.1.0.dist-info/METADATA +261 -0
- statstudio-0.1.0.dist-info/RECORD +110 -0
- statstudio-0.1.0.dist-info/WHEEL +5 -0
- statstudio-0.1.0.dist-info/entry_points.txt +5 -0
- statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
- statstudio-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,3934 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from PySide6.QtCore import QEvent, QObject, QSettings, QSize, QTimer, Qt, Signal
|
|
8
|
+
from PySide6.QtGui import QAction, QActionGroup, QColor, QFont, QMouseEvent, QPainter, QPen
|
|
9
|
+
from PySide6.QtWidgets import (
|
|
10
|
+
QApplication,
|
|
11
|
+
QDialog,
|
|
12
|
+
QDockWidget,
|
|
13
|
+
QFileDialog,
|
|
14
|
+
QInputDialog,
|
|
15
|
+
QLabel,
|
|
16
|
+
QMainWindow,
|
|
17
|
+
QMdiArea,
|
|
18
|
+
QMdiSubWindow,
|
|
19
|
+
QMenu,
|
|
20
|
+
QMessageBox,
|
|
21
|
+
QPlainTextEdit,
|
|
22
|
+
QStackedWidget,
|
|
23
|
+
QToolBar,
|
|
24
|
+
QToolButton,
|
|
25
|
+
QTreeWidget,
|
|
26
|
+
QTreeWidgetItem,
|
|
27
|
+
QVBoxLayout,
|
|
28
|
+
QWidget,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from statstudio import __author__, __copyright__, __license__, __version__
|
|
32
|
+
from statstudio.core.commands import CommandStack
|
|
33
|
+
from statstudio.core import scripting
|
|
34
|
+
from statstudio.core.project import JournalEntry, Project, ReportRecord, PROJECT_SUFFIX
|
|
35
|
+
from statstudio.core.table import DataTable, TableScript, add_rows, restore_table
|
|
36
|
+
from statstudio.core.transform import (
|
|
37
|
+
add_empty_column,
|
|
38
|
+
add_formula_column,
|
|
39
|
+
bin_column,
|
|
40
|
+
boxcox_column,
|
|
41
|
+
rank_column,
|
|
42
|
+
recode_column,
|
|
43
|
+
text_to_columns,
|
|
44
|
+
delete_rows,
|
|
45
|
+
duplicate_rows,
|
|
46
|
+
find_replace,
|
|
47
|
+
move_column,
|
|
48
|
+
standardize_columns,
|
|
49
|
+
transpose_table,
|
|
50
|
+
unhide_all_columns,
|
|
51
|
+
)
|
|
52
|
+
from statstudio.io.export import export_table
|
|
53
|
+
from statstudio.io.file_import import excel_sheet_names, read_clipboard, read_file
|
|
54
|
+
from statstudio.io.sample_data import load_sample, sample_names
|
|
55
|
+
from statstudio.io.table_io import TABLE_SUFFIX, load_table, save_table
|
|
56
|
+
from statstudio import stats as stats_pkg
|
|
57
|
+
from statstudio.stats.results import AnalysisResult, PlotSpec
|
|
58
|
+
from statstudio.ui import icons, recent, theme
|
|
59
|
+
from statstudio.ui.analysis_hub import AnalysisHubDialog
|
|
60
|
+
from statstudio.ui.command_catalog import HubCommand, build_catalog
|
|
61
|
+
from statstudio.ui.command_palette import CommandPaletteDialog
|
|
62
|
+
from statstudio.ui.console import PythonConsole
|
|
63
|
+
from statstudio.ui.dialogs.lazy import (
|
|
64
|
+
ANOVADialog,
|
|
65
|
+
AppendDialog,
|
|
66
|
+
BayesianANOVADialog,
|
|
67
|
+
BayesianLinearRegressionDialog,
|
|
68
|
+
BayesianLogisticRegressionDialog,
|
|
69
|
+
BayesianOptimizationDialog,
|
|
70
|
+
BayesianTwoSampleDialog,
|
|
71
|
+
CSVOptionsDialog,
|
|
72
|
+
ChiSquareDialog,
|
|
73
|
+
ColumnManagerDialog,
|
|
74
|
+
ColumnPropertiesDialog,
|
|
75
|
+
ColumnSwitcherDialog,
|
|
76
|
+
CompetingRiskDialog,
|
|
77
|
+
ContingencyDialog,
|
|
78
|
+
CorrelationDialog,
|
|
79
|
+
CovarianceDialog,
|
|
80
|
+
CustomDesignDialog,
|
|
81
|
+
DOEAnalysisDialog,
|
|
82
|
+
DOEDesignDialog,
|
|
83
|
+
DescriptiveDialog,
|
|
84
|
+
DistributionDialog,
|
|
85
|
+
DistributionIDDialog,
|
|
86
|
+
DistributionSummaryDialog,
|
|
87
|
+
DuplicateTableDialog,
|
|
88
|
+
EquivalentTestDialog,
|
|
89
|
+
FilterDialog,
|
|
90
|
+
FindReplaceDialog,
|
|
91
|
+
FitYByXDialog,
|
|
92
|
+
ForecastDialog,
|
|
93
|
+
FormulaDialog,
|
|
94
|
+
FrequencyDialog,
|
|
95
|
+
FriedmanDialog,
|
|
96
|
+
GroupSummaryDialog,
|
|
97
|
+
ImportPreviewDialog,
|
|
98
|
+
JoinDialog,
|
|
99
|
+
MannWhitneyDialog,
|
|
100
|
+
MissingDialog,
|
|
101
|
+
MoodMedianDialog,
|
|
102
|
+
MultiResponseDialog,
|
|
103
|
+
MultivariateDialog,
|
|
104
|
+
NewColumnDialog,
|
|
105
|
+
NewTableDialog,
|
|
106
|
+
NormalityDialog,
|
|
107
|
+
ODBCDialog,
|
|
108
|
+
PasteDialog,
|
|
109
|
+
PlotDialog,
|
|
110
|
+
PostHocDialog,
|
|
111
|
+
PowerDialog,
|
|
112
|
+
PredictiveDialog,
|
|
113
|
+
ProcessScreeningDialog,
|
|
114
|
+
ProfilerDialog,
|
|
115
|
+
ProportionDialog,
|
|
116
|
+
QualityDialog,
|
|
117
|
+
RecodeDialog,
|
|
118
|
+
RegressionDialog,
|
|
119
|
+
RegressionMultiResponseDialog,
|
|
120
|
+
RegressionProfilerDialog,
|
|
121
|
+
ReliabilityDialog,
|
|
122
|
+
RenameTableDialog,
|
|
123
|
+
ReportComposerDialog,
|
|
124
|
+
RunsTestDialog,
|
|
125
|
+
STLDialog,
|
|
126
|
+
SignTestDialog,
|
|
127
|
+
SimulationDialog,
|
|
128
|
+
SortDialog,
|
|
129
|
+
SplitDialog,
|
|
130
|
+
StackDialog,
|
|
131
|
+
StandardizeDialog,
|
|
132
|
+
SubsetColumnsDialog,
|
|
133
|
+
SurvivalDialog,
|
|
134
|
+
TTestDialog,
|
|
135
|
+
TimeSeriesDialog,
|
|
136
|
+
ToleranceDialog,
|
|
137
|
+
TwoWayANOVADialog,
|
|
138
|
+
UnstackDialog,
|
|
139
|
+
WilcoxonDialog,
|
|
140
|
+
WilcoxonOneDialog,
|
|
141
|
+
ZeroFailureReliabilityDialog,
|
|
142
|
+
)
|
|
143
|
+
from statstudio.ui.plot_interaction import filtered_plot_data
|
|
144
|
+
from statstudio.ui.scripts_panel import ScriptsPanel
|
|
145
|
+
from statstudio.ui.table_document import TableDocument
|
|
146
|
+
from statstudio.ui.table_view import DataTableView
|
|
147
|
+
from statstudio.ui.welcome import WelcomePage
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class DocumentSubWindow(QMdiSubWindow):
|
|
151
|
+
state_changed = Signal()
|
|
152
|
+
|
|
153
|
+
def changeEvent(self, event) -> None:
|
|
154
|
+
if event.type() == QEvent.Type.WindowStateChange:
|
|
155
|
+
self.state_changed.emit()
|
|
156
|
+
super().changeEvent(event)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _qt_alive(obj) -> bool:
|
|
160
|
+
if obj is None:
|
|
161
|
+
return False
|
|
162
|
+
try:
|
|
163
|
+
from shiboken6 import isValid
|
|
164
|
+
|
|
165
|
+
return bool(isValid(obj))
|
|
166
|
+
except Exception:
|
|
167
|
+
return True
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class _DocumentDragFilter(QObject):
|
|
171
|
+
def __init__(self, sub: QMdiSubWindow) -> None:
|
|
172
|
+
super().__init__(sub)
|
|
173
|
+
self.sub = sub
|
|
174
|
+
self._press_global = None
|
|
175
|
+
self._press_pos = None
|
|
176
|
+
self._dragging = False
|
|
177
|
+
|
|
178
|
+
def eventFilter(self, obj, event) -> bool:
|
|
179
|
+
if not _qt_alive(self.sub):
|
|
180
|
+
return False
|
|
181
|
+
try:
|
|
182
|
+
if self.sub.windowState() & Qt.WindowState.WindowMaximized:
|
|
183
|
+
return False
|
|
184
|
+
event_type = event.type()
|
|
185
|
+
if event_type == QEvent.Type.MouseButtonPress and isinstance(event, QMouseEvent):
|
|
186
|
+
if event.button() == Qt.MouseButton.LeftButton:
|
|
187
|
+
self._press_global = event.globalPosition().toPoint()
|
|
188
|
+
self._press_pos = self.sub.pos()
|
|
189
|
+
self._dragging = False
|
|
190
|
+
return False
|
|
191
|
+
if event_type == QEvent.Type.MouseMove and isinstance(event, QMouseEvent):
|
|
192
|
+
if self._press_global is None or not (event.buttons() & Qt.MouseButton.LeftButton):
|
|
193
|
+
return False
|
|
194
|
+
delta = event.globalPosition().toPoint() - self._press_global
|
|
195
|
+
if not self._dragging and delta.manhattanLength() < 4:
|
|
196
|
+
return False
|
|
197
|
+
self._dragging = True
|
|
198
|
+
new_pos = self._press_pos + delta
|
|
199
|
+
area = self.sub.mdiArea()
|
|
200
|
+
if area is not None:
|
|
201
|
+
max_x = max(0, area.width() - self.sub.width())
|
|
202
|
+
max_y = max(0, area.height() - self.sub.height())
|
|
203
|
+
new_pos.setX(max(0, min(new_pos.x(), max_x)))
|
|
204
|
+
new_pos.setY(max(0, min(new_pos.y(), max_y)))
|
|
205
|
+
self.sub.move(new_pos)
|
|
206
|
+
return True
|
|
207
|
+
if event_type == QEvent.Type.MouseButtonRelease:
|
|
208
|
+
self._press_global = None
|
|
209
|
+
self._press_pos = None
|
|
210
|
+
self._dragging = False
|
|
211
|
+
except RuntimeError:
|
|
212
|
+
return False
|
|
213
|
+
return False
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class _DocumentResizeGrip(QWidget):
|
|
217
|
+
def __init__(self, parent: QWidget, sub: QMdiSubWindow) -> None:
|
|
218
|
+
super().__init__(parent)
|
|
219
|
+
self.sub = sub
|
|
220
|
+
self._start_global = None
|
|
221
|
+
self._start_size = None
|
|
222
|
+
self.setFixedSize(16, 16)
|
|
223
|
+
self.setCursor(Qt.CursorShape.SizeFDiagCursor)
|
|
224
|
+
self.setToolTip("Resize document")
|
|
225
|
+
parent.installEventFilter(self)
|
|
226
|
+
self._reposition()
|
|
227
|
+
|
|
228
|
+
def _reposition(self) -> None:
|
|
229
|
+
parent = self.parentWidget()
|
|
230
|
+
if parent is not None and _qt_alive(parent):
|
|
231
|
+
try:
|
|
232
|
+
self.move(parent.width() - self.width(), parent.height() - self.height())
|
|
233
|
+
self.raise_()
|
|
234
|
+
except RuntimeError:
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
def eventFilter(self, obj, event) -> bool:
|
|
238
|
+
if obj is self.parentWidget() and event.type() == QEvent.Type.Resize:
|
|
239
|
+
self._reposition()
|
|
240
|
+
return False
|
|
241
|
+
|
|
242
|
+
def mousePressEvent(self, event: QMouseEvent) -> None: # type: ignore[override]
|
|
243
|
+
if event.button() == Qt.MouseButton.LeftButton and _qt_alive(self.sub):
|
|
244
|
+
try:
|
|
245
|
+
self._start_global = event.globalPosition().toPoint()
|
|
246
|
+
self._start_size = self.sub.size()
|
|
247
|
+
except RuntimeError:
|
|
248
|
+
return
|
|
249
|
+
event.accept()
|
|
250
|
+
return
|
|
251
|
+
super().mousePressEvent(event)
|
|
252
|
+
|
|
253
|
+
def mouseMoveEvent(self, event: QMouseEvent) -> None: # type: ignore[override]
|
|
254
|
+
if (
|
|
255
|
+
self._start_global is not None
|
|
256
|
+
and self._start_size is not None
|
|
257
|
+
and _qt_alive(self.sub)
|
|
258
|
+
and event.buttons() & Qt.MouseButton.LeftButton
|
|
259
|
+
):
|
|
260
|
+
try:
|
|
261
|
+
delta = event.globalPosition().toPoint() - self._start_global
|
|
262
|
+
self.sub.resize(
|
|
263
|
+
max(360, self._start_size.width() + delta.x()),
|
|
264
|
+
max(240, self._start_size.height() + delta.y()),
|
|
265
|
+
)
|
|
266
|
+
except RuntimeError:
|
|
267
|
+
return
|
|
268
|
+
event.accept()
|
|
269
|
+
return
|
|
270
|
+
super().mouseMoveEvent(event)
|
|
271
|
+
|
|
272
|
+
def mouseReleaseEvent(self, event: QMouseEvent) -> None: # type: ignore[override]
|
|
273
|
+
self._start_global = None
|
|
274
|
+
self._start_size = None
|
|
275
|
+
super().mouseReleaseEvent(event)
|
|
276
|
+
|
|
277
|
+
def paintEvent(self, event) -> None: # type: ignore[override]
|
|
278
|
+
painter = QPainter(self)
|
|
279
|
+
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
|
|
280
|
+
pen = QPen(QColor(theme.theme_colors().text_subtle))
|
|
281
|
+
pen.setWidth(1)
|
|
282
|
+
painter.setPen(pen)
|
|
283
|
+
for offset in (3, 7, 11):
|
|
284
|
+
painter.drawLine(offset, 15, 15, offset)
|
|
285
|
+
painter.end()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class MainWindow(QMainWindow):
|
|
289
|
+
def __init__(self, project: Project | None = None) -> None:
|
|
290
|
+
super().__init__()
|
|
291
|
+
self.project = project or Project()
|
|
292
|
+
self.command_stack = CommandStack()
|
|
293
|
+
self.table_views: dict[DataTable, DataTableView] = {}
|
|
294
|
+
self.report_views: list[QWidget] = []
|
|
295
|
+
self._plot_records: dict[object, ReportRecord] = {}
|
|
296
|
+
self._windows: dict[QWidget, QMdiSubWindow] = {}
|
|
297
|
+
self._table_windows: dict[DataTable, QMdiSubWindow] = {}
|
|
298
|
+
self._table_documents: dict[DataTable, TableDocument] = {}
|
|
299
|
+
self._project_dirty: bool = False
|
|
300
|
+
self._hash_cache: dict[int, str] = {}
|
|
301
|
+
self._last_table_view: DataTableView | None = None
|
|
302
|
+
self._selection_state: tuple[str, list] | None = None
|
|
303
|
+
self._help_dialog: QDialog | None = None
|
|
304
|
+
self.commands: dict[str, HubCommand] = {}
|
|
305
|
+
self._light_action: QAction | None = None
|
|
306
|
+
self._dark_action: QAction | None = None
|
|
307
|
+
self._theme_toggle_action: QAction | None = None
|
|
308
|
+
self._theme_button: QToolButton | None = None
|
|
309
|
+
self._job_timer: QTimer | None = None
|
|
310
|
+
self._document_chrome_refs: list[QObject] = []
|
|
311
|
+
self._home_dock_state: dict[QDockWidget, bool] | None = None
|
|
312
|
+
self.setWindowTitle("StatStudio")
|
|
313
|
+
self.resize(1400, 900)
|
|
314
|
+
self.setAcceptDrops(True)
|
|
315
|
+
self._build_ui()
|
|
316
|
+
self._build_menus()
|
|
317
|
+
self._build_commands()
|
|
318
|
+
self._build_toolbars()
|
|
319
|
+
self._build_status_bar()
|
|
320
|
+
self._restore_window_state()
|
|
321
|
+
self._load_project_into_ui(self.project)
|
|
322
|
+
self._update_undo_actions()
|
|
323
|
+
|
|
324
|
+
# ------------------------------------------------------------------ UI
|
|
325
|
+
def _build_ui(self) -> None:
|
|
326
|
+
self.mdi = QMdiArea()
|
|
327
|
+
self.mdi.setViewMode(QMdiArea.ViewMode.SubWindowView)
|
|
328
|
+
self.mdi.subWindowActivated.connect(self._on_subwindow_activated)
|
|
329
|
+
self.workspace = QWidget()
|
|
330
|
+
workspace_layout = QVBoxLayout(self.workspace)
|
|
331
|
+
workspace_layout.setContentsMargins(0, 0, 0, 0)
|
|
332
|
+
workspace_layout.setSpacing(0)
|
|
333
|
+
workspace_layout.addWidget(self.mdi, 1)
|
|
334
|
+
self.mdi.viewport().installEventFilter(self)
|
|
335
|
+
|
|
336
|
+
self.home = WelcomePage()
|
|
337
|
+
self.home.open_project_requested.connect(self._open_project)
|
|
338
|
+
self.home.new_project_requested.connect(self._new_project)
|
|
339
|
+
self.home.import_requested.connect(self._import_file)
|
|
340
|
+
self.home.new_table_requested.connect(self._new_data_table)
|
|
341
|
+
self.home.sample_requested.connect(self._load_sample)
|
|
342
|
+
self.home.recent_project_requested.connect(self._open_recent_project)
|
|
343
|
+
self.home.search_requested.connect(self._show_analysis_hub)
|
|
344
|
+
self.home.command_requested.connect(self._run_command)
|
|
345
|
+
self.home.files_dropped.connect(self._import_paths)
|
|
346
|
+
self.central_stack = QStackedWidget()
|
|
347
|
+
self.central_stack.addWidget(self.home)
|
|
348
|
+
self.central_stack.addWidget(self.workspace)
|
|
349
|
+
self.setCentralWidget(self.central_stack)
|
|
350
|
+
|
|
351
|
+
self.project_tree = QTreeWidget()
|
|
352
|
+
self.project_tree.setHeaderLabels(["Project"])
|
|
353
|
+
self.project_tree.setMinimumWidth(250)
|
|
354
|
+
self.project_tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
|
355
|
+
self.project_tree.customContextMenuRequested.connect(self._project_tree_context_menu)
|
|
356
|
+
self.project_tree.itemDoubleClicked.connect(self._tree_double_clicked)
|
|
357
|
+
self.project_dock = QDockWidget("Project", self)
|
|
358
|
+
self.project_dock.setObjectName("project_dock")
|
|
359
|
+
self.project_dock.setWidget(self.project_tree)
|
|
360
|
+
self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, self.project_dock)
|
|
361
|
+
|
|
362
|
+
self.console = PythonConsole(self.project, self)
|
|
363
|
+
self.console_dock = QDockWidget("Python Console", self)
|
|
364
|
+
self.console_dock.setObjectName("console_dock")
|
|
365
|
+
self.console_dock.setWidget(self.console)
|
|
366
|
+
self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, self.console_dock)
|
|
367
|
+
|
|
368
|
+
self.log_view = QPlainTextEdit()
|
|
369
|
+
self.log_view.setReadOnly(True)
|
|
370
|
+
self.log_view.setFont(QFont("monospace", 9))
|
|
371
|
+
self.log_view.setMaximumBlockCount(2000)
|
|
372
|
+
self.log_dock = QDockWidget("Log", self)
|
|
373
|
+
self.log_dock.setObjectName("log_dock")
|
|
374
|
+
self.log_dock.setWidget(self.log_view)
|
|
375
|
+
self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, self.log_dock)
|
|
376
|
+
self.tabifyDockWidget(self.console_dock, self.log_dock)
|
|
377
|
+
self.console_dock.raise_()
|
|
378
|
+
|
|
379
|
+
self.scripts_panel = ScriptsPanel(self.project, self.console)
|
|
380
|
+
self.scripts_panel.project_changed.connect(self._mark_project_dirty)
|
|
381
|
+
self.scripts_dock = QDockWidget("Scripts", self)
|
|
382
|
+
self.scripts_dock.setObjectName("scripts_dock")
|
|
383
|
+
self.scripts_dock.setWidget(self.scripts_panel)
|
|
384
|
+
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.scripts_dock)
|
|
385
|
+
self.resizeDocks([self.project_dock], [270], Qt.Orientation.Horizontal)
|
|
386
|
+
self.resizeDocks([self.console_dock], [170], Qt.Orientation.Vertical)
|
|
387
|
+
|
|
388
|
+
self.statusBar().showMessage("Ready")
|
|
389
|
+
|
|
390
|
+
def _build_menus(self) -> None:
|
|
391
|
+
menu_bar = self.menuBar()
|
|
392
|
+
|
|
393
|
+
file_menu = menu_bar.addMenu("&File")
|
|
394
|
+
self.undo_action = QAction("Undo", self)
|
|
395
|
+
self.undo_action.setShortcut("Ctrl+Z")
|
|
396
|
+
self.undo_action.triggered.connect(self._undo)
|
|
397
|
+
self.redo_action = QAction("Redo", self)
|
|
398
|
+
self.redo_action.setShortcut("Ctrl+Y")
|
|
399
|
+
self.redo_action.triggered.connect(self._redo)
|
|
400
|
+
|
|
401
|
+
self._add_action(file_menu, "New Project", self._new_project, "Ctrl+N")
|
|
402
|
+
self._add_action(file_menu, "New Data Table...", self._new_data_table, "Ctrl+T")
|
|
403
|
+
self._add_action(file_menu, "Open Project...", self._open_project, "Ctrl+O")
|
|
404
|
+
self.recent_projects_menu = file_menu.addMenu("Recent Projects")
|
|
405
|
+
self._add_action(file_menu, "Save Project", self._save_project, "Ctrl+S")
|
|
406
|
+
self._add_action(file_menu, "Save Project As...", self._save_project_as)
|
|
407
|
+
file_menu.addSeparator()
|
|
408
|
+
self._add_action(file_menu, "Open Table...", self._open_table_file)
|
|
409
|
+
self._add_action(file_menu, "Import File...", self._import_file, "Ctrl+I")
|
|
410
|
+
self._add_action(file_menu, "Import from ODBC...", self._import_odbc)
|
|
411
|
+
self._add_action(file_menu, "Import Clipboard", self._import_clipboard)
|
|
412
|
+
sample_menu = file_menu.addMenu("Open Sample Data")
|
|
413
|
+
for name in sample_names():
|
|
414
|
+
sample_menu.addAction(name, lambda n=name: self._load_sample(n))
|
|
415
|
+
file_menu.addSeparator()
|
|
416
|
+
self._add_action(file_menu, "Save Table As...", self._save_table_as)
|
|
417
|
+
self._add_action(file_menu, "Export Current Table...", self._export_table, "Ctrl+E")
|
|
418
|
+
self._add_action(file_menu, "Close Window", self._close_current_tab, "Ctrl+W")
|
|
419
|
+
file_menu.addSeparator()
|
|
420
|
+
self._add_action(file_menu, "Exit", self.close, "Ctrl+Q")
|
|
421
|
+
|
|
422
|
+
edit_menu = menu_bar.addMenu("&Edit")
|
|
423
|
+
edit_menu.addAction(self.undo_action)
|
|
424
|
+
edit_menu.addAction(self.redo_action)
|
|
425
|
+
edit_menu.addSeparator()
|
|
426
|
+
self._add_action(edit_menu, "Paste...", lambda: self._paste_into_table(False), "Ctrl+V")
|
|
427
|
+
self._add_action(edit_menu, "Paste with Column Names...", lambda: self._paste_into_table(True), "Ctrl+Shift+V")
|
|
428
|
+
self._add_action(edit_menu, "Find and Replace...", self._find_replace, "Ctrl+H")
|
|
429
|
+
edit_menu.addSeparator()
|
|
430
|
+
edit_columns_menu = edit_menu.addMenu("Columns")
|
|
431
|
+
self._add_action(edit_columns_menu, "Rename Column...", self._rename_column)
|
|
432
|
+
self._add_action(edit_columns_menu, "Column Properties...", self._column_properties_current)
|
|
433
|
+
self._add_action(edit_columns_menu, "Column Manager...", self._column_manager)
|
|
434
|
+
self._add_action(edit_columns_menu, "Hide Column...", self._hide_column)
|
|
435
|
+
self._add_action(edit_columns_menu, "Delete Column...", self._delete_column)
|
|
436
|
+
self._add_action(edit_columns_menu, "Unhide All Columns", self._unhide_columns)
|
|
437
|
+
edit_rows_menu = edit_menu.addMenu("Rows")
|
|
438
|
+
self._add_action(edit_rows_menu, "Duplicate Selected Rows", lambda: self._duplicate_selected_rows())
|
|
439
|
+
self._add_action(edit_rows_menu, "Delete Selected Rows", lambda: self._delete_selected_rows())
|
|
440
|
+
edit_rows_menu.addSeparator()
|
|
441
|
+
self._add_action(edit_rows_menu, "Hide Selected Rows", self._hide_selected)
|
|
442
|
+
self._add_action(edit_rows_menu, "Exclude Selected Rows", self._exclude_selected)
|
|
443
|
+
self._add_action(edit_rows_menu, "Clear Exclusions", self._clear_exclusions)
|
|
444
|
+
edit_menu.addSeparator()
|
|
445
|
+
self._add_action(edit_menu, "Filter Rows...", self._filter_rows, "Ctrl+L")
|
|
446
|
+
self._add_action(edit_menu, "Clear Filter", self._clear_filter)
|
|
447
|
+
self._add_action(edit_menu, "Multi-Column Sort...", self._sort_columns)
|
|
448
|
+
|
|
449
|
+
tables_menu = menu_bar.addMenu("&Tables")
|
|
450
|
+
self._add_action(tables_menu, "Rename Table...", self._rename_table)
|
|
451
|
+
self._add_action(tables_menu, "Duplicate Table...", self._duplicate_table)
|
|
452
|
+
self._add_action(tables_menu, "Delete Table", self._delete_table)
|
|
453
|
+
tables_menu.addSeparator()
|
|
454
|
+
table_rows_menu = tables_menu.addMenu("Rows")
|
|
455
|
+
self._add_action(table_rows_menu, "Add Rows...", self._add_rows)
|
|
456
|
+
self._add_action(table_rows_menu, "Create Subset from Selected Rows", self._create_subset_from_selection)
|
|
457
|
+
table_columns_menu = tables_menu.addMenu("Columns")
|
|
458
|
+
self._add_action(table_columns_menu, "Add Column...", self._new_column)
|
|
459
|
+
self._add_action(table_columns_menu, "New Formula Column...", self._formula_column)
|
|
460
|
+
self._add_action(table_columns_menu, "Recode Column...", self._recode_column)
|
|
461
|
+
self._add_action(table_columns_menu, "Replace Missing Values...", self._replace_missing)
|
|
462
|
+
self._add_action(table_columns_menu, "Standardize Columns...", self._standardize_columns)
|
|
463
|
+
self._add_action(table_columns_menu, "Box-Cox Transform...", self._boxcox_column)
|
|
464
|
+
self._add_action(table_columns_menu, "Rank Column...", self._rank_column)
|
|
465
|
+
self._add_action(table_columns_menu, "Bin Column...", self._bin_column)
|
|
466
|
+
self._add_action(table_columns_menu, "Text to Columns...", self._text_to_columns)
|
|
467
|
+
self._add_action(table_columns_menu, "Subset Columns...", self._subset_columns)
|
|
468
|
+
table_combine_menu = tables_menu.addMenu("Combine / Reshape")
|
|
469
|
+
self._add_action(table_combine_menu, "Merge / Join...", self._join_tables)
|
|
470
|
+
self._add_action(table_combine_menu, "Append Tables...", self._append_tables)
|
|
471
|
+
table_combine_menu.addSeparator()
|
|
472
|
+
self._add_action(table_combine_menu, "Split Table...", self._split_table)
|
|
473
|
+
self._add_action(table_combine_menu, "Stack Columns...", self._stack_table)
|
|
474
|
+
self._add_action(table_combine_menu, "Unstack Column...", self._unstack_table)
|
|
475
|
+
self._add_action(table_combine_menu, "Transpose Table", self._transpose_table)
|
|
476
|
+
tables_menu.addSeparator()
|
|
477
|
+
self._add_action(tables_menu, "Linked Scripts...", self._show_table_scripts)
|
|
478
|
+
|
|
479
|
+
analyze_menu = menu_bar.addMenu("&Analyze")
|
|
480
|
+
self.analysis_hub_action = self._add_action(
|
|
481
|
+
analyze_menu,
|
|
482
|
+
"Analysis Hub...",
|
|
483
|
+
self._show_analysis_hub,
|
|
484
|
+
"Ctrl+Shift+A",
|
|
485
|
+
)
|
|
486
|
+
analyze_menu.addSeparator()
|
|
487
|
+
|
|
488
|
+
summary_menu = analyze_menu.addMenu("Summary && Distributions")
|
|
489
|
+
basic_summary = summary_menu.addMenu("Summary")
|
|
490
|
+
self._add_action(basic_summary, "Descriptive Statistics...", lambda: self._open_stats(DescriptiveDialog))
|
|
491
|
+
self._add_action(basic_summary, "Grouped Summary...", lambda: self._open_stats(GroupSummaryDialog))
|
|
492
|
+
self._add_action(basic_summary, "Frequency Distribution...", lambda: self._open_stats(FrequencyDialog))
|
|
493
|
+
distribution_menu = summary_menu.addMenu("Distribution")
|
|
494
|
+
self._add_action(distribution_menu, "Distribution Fit...", lambda: self._open_stats(DistributionDialog))
|
|
495
|
+
self._add_action(distribution_menu, "Distribution Identification...", lambda: self._open_stats(DistributionIDDialog))
|
|
496
|
+
self._add_action(distribution_menu, "Distribution Summary...", lambda: self._open_stats(DistributionSummaryDialog))
|
|
497
|
+
self._add_action(distribution_menu, "Tolerance Interval...", lambda: self._open_stats(ToleranceDialog))
|
|
498
|
+
self._add_action(distribution_menu, "Normality Test...", lambda: self._open_stats(NormalityDialog))
|
|
499
|
+
summary_menu.addSeparator()
|
|
500
|
+
self._add_action(summary_menu, "Correlation...", lambda: self._open_stats(CorrelationDialog))
|
|
501
|
+
|
|
502
|
+
compare_menu = analyze_menu.addMenu("Compare Means")
|
|
503
|
+
parametric_menu = compare_menu.addMenu("Parametric")
|
|
504
|
+
self._add_action(parametric_menu, "t Test...", lambda: self._open_stats(TTestDialog))
|
|
505
|
+
self._add_action(parametric_menu, "ANOVA / Kruskal-Wallis...", lambda: self._open_stats(ANOVADialog))
|
|
506
|
+
self._add_action(parametric_menu, "Two-Way ANOVA...", lambda: self._open_stats(TwoWayANOVADialog))
|
|
507
|
+
self._add_action(parametric_menu, "Post-Hoc Comparisons...", lambda: self._open_stats(PostHocDialog))
|
|
508
|
+
nonparametric_menu = compare_menu.addMenu("Nonparametric")
|
|
509
|
+
self._add_action(nonparametric_menu, "Mann-Whitney Test...", lambda: self._open_stats(MannWhitneyDialog))
|
|
510
|
+
self._add_action(nonparametric_menu, "Wilcoxon Signed-Rank...", lambda: self._open_stats(WilcoxonDialog))
|
|
511
|
+
self._add_action(nonparametric_menu, "Sign Test...", lambda: self._open_stats(SignTestDialog))
|
|
512
|
+
self._add_action(nonparametric_menu, "One-Sample Wilcoxon...", lambda: self._open_stats(WilcoxonOneDialog))
|
|
513
|
+
self._add_action(nonparametric_menu, "Mood's Median Test...", lambda: self._open_stats(MoodMedianDialog))
|
|
514
|
+
self._add_action(nonparametric_menu, "Friedman Test...", lambda: self._open_stats(FriedmanDialog))
|
|
515
|
+
self._add_action(nonparametric_menu, "Runs Test...", lambda: self._open_stats(RunsTestDialog))
|
|
516
|
+
compare_menu.addSeparator()
|
|
517
|
+
self._add_action(compare_menu, "Equivalence Test...", lambda: self._open_stats(EquivalentTestDialog))
|
|
518
|
+
|
|
519
|
+
contingency_menu = analyze_menu.addMenu("Contingency")
|
|
520
|
+
self._add_action(contingency_menu, "Contingency Analysis...", lambda: self._open_stats(ContingencyDialog))
|
|
521
|
+
self._add_action(contingency_menu, "Chi-Square Test...", lambda: self._open_stats(ChiSquareDialog))
|
|
522
|
+
self._add_action(contingency_menu, "Proportion Test...", lambda: self._open_stats(ProportionDialog))
|
|
523
|
+
|
|
524
|
+
modeling_menu = analyze_menu.addMenu("Regression && Multivariate")
|
|
525
|
+
linear_regression_menu = modeling_menu.addMenu("Linear Regression")
|
|
526
|
+
self._add_action(linear_regression_menu, "Simple...", lambda: self._open_stats(FitYByXDialog))
|
|
527
|
+
self._add_action(linear_regression_menu, "Multi Linear...", lambda: self._open_stats(RegressionDialog))
|
|
528
|
+
self._add_action(linear_regression_menu, "Prediction Profiler...", lambda: self._open_stats(RegressionProfilerDialog))
|
|
529
|
+
self._add_action(
|
|
530
|
+
linear_regression_menu,
|
|
531
|
+
"Multi-Response Optimization...",
|
|
532
|
+
lambda: self._open_stats(RegressionMultiResponseDialog),
|
|
533
|
+
)
|
|
534
|
+
self._add_action(modeling_menu, "Predictive Modeling...", lambda: self._open_stats(PredictiveDialog))
|
|
535
|
+
self._add_action(modeling_menu, "Multivariate...", lambda: self._open_stats(MultivariateDialog))
|
|
536
|
+
bayesian_menu = modeling_menu.addMenu("Bayesian")
|
|
537
|
+
self._add_action(bayesian_menu, "Linear Regression...", lambda: self._open_stats(BayesianLinearRegressionDialog))
|
|
538
|
+
self._add_action(bayesian_menu, "Logistic Regression...", lambda: self._open_stats(BayesianLogisticRegressionDialog))
|
|
539
|
+
self._add_action(bayesian_menu, "Two-Sample Comparison...", lambda: self._open_stats(BayesianTwoSampleDialog))
|
|
540
|
+
self._add_action(bayesian_menu, "One-Way ANOVA...", lambda: self._open_stats(BayesianANOVADialog))
|
|
541
|
+
|
|
542
|
+
ts_menu = analyze_menu.addMenu("Time Series")
|
|
543
|
+
self._add_action(ts_menu, "Time Series...", lambda: self._open_stats(TimeSeriesDialog))
|
|
544
|
+
self._add_action(ts_menu, "Forecast...", lambda: self._open_stats(ForecastDialog))
|
|
545
|
+
self._add_action(ts_menu, "STL Decomposition...", lambda: self._open_stats(STLDialog))
|
|
546
|
+
|
|
547
|
+
reliability_menu = analyze_menu.addMenu("Survival && Reliability")
|
|
548
|
+
self._add_action(reliability_menu, "Survival...", lambda: self._open_stats(SurvivalDialog))
|
|
549
|
+
self._add_action(reliability_menu, "Competing Risks...", lambda: self._open_stats(CompetingRiskDialog))
|
|
550
|
+
self._add_action(reliability_menu, "Reliability / Weibull...", lambda: self._open_stats(ReliabilityDialog))
|
|
551
|
+
|
|
552
|
+
quality_menu = analyze_menu.addMenu("Quality && SPC")
|
|
553
|
+
self._add_action(quality_menu, "Quality / SPC...", lambda: self._open_stats(QualityDialog))
|
|
554
|
+
self._add_action(quality_menu, "Process Screening...", lambda: self._open_stats(ProcessScreeningDialog))
|
|
555
|
+
self._add_action(quality_menu, "Power and Sample Size...", lambda: self._open_stats(PowerDialog))
|
|
556
|
+
|
|
557
|
+
doe_menu = menu_bar.addMenu("&DOE")
|
|
558
|
+
self._add_action(doe_menu, "Custom Design...", self._create_custom_doe)
|
|
559
|
+
self._add_action(doe_menu, "Full Factorial Design...", lambda: self._create_doe("Full Factorial"))
|
|
560
|
+
self._add_action(doe_menu, "3-Level Factorial Design...", lambda: self._create_doe("3-Level Factorial"))
|
|
561
|
+
self._add_action(doe_menu, "Fractional Factorial Design...", lambda: self._create_doe("Fractional Factorial"))
|
|
562
|
+
self._add_action(doe_menu, "Plackett-Burman Screening...", lambda: self._create_doe("Plackett-Burman Screening"))
|
|
563
|
+
self._add_action(doe_menu, "Central Composite Design...", lambda: self._create_doe("Central Composite"))
|
|
564
|
+
self._add_action(doe_menu, "Box-Behnken Design...", lambda: self._create_doe("Box-Behnken"))
|
|
565
|
+
doe_menu.addSeparator()
|
|
566
|
+
self._add_action(doe_menu, "Analyze Design...", lambda: self._open_stats(DOEAnalysisDialog))
|
|
567
|
+
self._add_action(doe_menu, "Design Diagnostics...", self._design_diagnostics)
|
|
568
|
+
self._add_action(doe_menu, "Prediction Profiler...", self._open_prediction_profiler)
|
|
569
|
+
self._add_action(doe_menu, "Response Simulation...", lambda: self._open_stats(SimulationDialog))
|
|
570
|
+
self._add_action(doe_menu, "Multi-Response Optimization...", self._open_multi_response_optimization)
|
|
571
|
+
self._add_action(doe_menu, "Bayesian Optimization...", lambda: self._open_stats(BayesianOptimizationDialog))
|
|
572
|
+
self._add_action(doe_menu, "Assign Blocks...", self._assign_blocks)
|
|
573
|
+
self._add_action(doe_menu, "Fold Over Design", self._fold_over_design)
|
|
574
|
+
self._add_action(doe_menu, "Fold One Factor...", self._fold_one_factor)
|
|
575
|
+
self._add_action(doe_menu, "Replicate Design...", self._replicate_design)
|
|
576
|
+
self._add_action(doe_menu, "Add Axial Points...", self._add_axial_points)
|
|
577
|
+
|
|
578
|
+
graph_menu = menu_bar.addMenu("&Graph")
|
|
579
|
+
self._add_action(graph_menu, "Graph Builder...", self._open_plot)
|
|
580
|
+
self._add_action(graph_menu, "Column Switcher...", self._column_switcher)
|
|
581
|
+
graph_menu.addSeparator()
|
|
582
|
+
basic_menu = graph_menu.addMenu("Basic")
|
|
583
|
+
self._add_action(basic_menu, "Histogram...", lambda: self._open_plot_kind("histogram"))
|
|
584
|
+
self._add_action(basic_menu, "Density...", lambda: self._open_plot_kind("density"))
|
|
585
|
+
self._add_action(basic_menu, "Box Plot...", lambda: self._open_plot_kind("box"))
|
|
586
|
+
self._add_action(basic_menu, "Violin Plot...", lambda: self._open_plot_kind("violin"))
|
|
587
|
+
self._add_action(basic_menu, "Strip Plot...", lambda: self._open_plot_kind("strip"))
|
|
588
|
+
self._add_action(basic_menu, "Variability Chart...", lambda: self._open_plot_kind("variability"))
|
|
589
|
+
self._add_action(basic_menu, "Dot Plot...", lambda: self._open_plot_kind("dotplot"))
|
|
590
|
+
self._add_action(basic_menu, "Bar Chart...", lambda: self._open_plot_kind("bar"))
|
|
591
|
+
self._add_action(basic_menu, "Pie Chart...", lambda: self._open_plot_kind("pie"))
|
|
592
|
+
|
|
593
|
+
xy_menu = graph_menu.addMenu("XY && Time")
|
|
594
|
+
self._add_action(xy_menu, "Scatter Plot...", lambda: self._open_plot_kind("scatter"))
|
|
595
|
+
self._add_action(xy_menu, "Bubble Plot...", lambda: self._open_plot_kind("bubble"))
|
|
596
|
+
self._add_action(xy_menu, "3D Scatter Plot...", lambda: self._open_plot_kind("scatter3d"))
|
|
597
|
+
self._add_action(xy_menu, "Line Chart...", lambda: self._open_plot_kind("line"))
|
|
598
|
+
self._add_action(xy_menu, "3D Line Plot...", lambda: self._open_plot_kind("line3d"))
|
|
599
|
+
self._add_action(xy_menu, "Area Chart...", lambda: self._open_plot_kind("area"))
|
|
600
|
+
|
|
601
|
+
matrix_menu = graph_menu.addMenu("Multivariate")
|
|
602
|
+
self._add_action(matrix_menu, "Correlation Heatmap...", lambda: self._open_plot_kind("correlation_heatmap"))
|
|
603
|
+
self._add_action(matrix_menu, "Heatmap...", lambda: self._open_plot_kind("heatmap"))
|
|
604
|
+
self._add_action(matrix_menu, "Scatterplot Matrix...", lambda: self._open_plot_kind("pairplot"))
|
|
605
|
+
self._add_action(matrix_menu, "Parallel Coordinates...", lambda: self._open_plot_kind("parallel_coordinates"))
|
|
606
|
+
self._add_action(matrix_menu, "Contour Plot...", lambda: self._open_plot_kind("contour"))
|
|
607
|
+
self._add_action(matrix_menu, "Surface Plot...", lambda: self._open_plot_kind("surface"))
|
|
608
|
+
self._add_action(matrix_menu, "Mosaic Plot...", lambda: self._open_plot_kind("mosaic"))
|
|
609
|
+
self._add_action(matrix_menu, "Pareto Chart...", lambda: self._open_plot_kind("pareto"))
|
|
610
|
+
|
|
611
|
+
self.view_menu = menu_bar.addMenu("&View")
|
|
612
|
+
self.home_action = self._add_action(self.view_menu, "Home", self._show_home, "Ctrl+Shift+H")
|
|
613
|
+
self._add_action(self.view_menu, "Refresh", self._refresh_all, "F5")
|
|
614
|
+
self._add_action(self.view_menu, "Command Palette...", self._show_command_palette, "Ctrl+/")
|
|
615
|
+
self.view_menu.addSeparator()
|
|
616
|
+
self.appearance_menu = self.view_menu.addMenu("Appearance")
|
|
617
|
+
self.theme_group = QActionGroup(self)
|
|
618
|
+
self.theme_group.setExclusive(True)
|
|
619
|
+
self._light_action = QAction("Light", self)
|
|
620
|
+
self._light_action.setCheckable(True)
|
|
621
|
+
self._light_action.triggered.connect(lambda: self._set_theme("light"))
|
|
622
|
+
self.theme_group.addAction(self._light_action)
|
|
623
|
+
self.appearance_menu.addAction(self._light_action)
|
|
624
|
+
self._dark_action = QAction("Dark", self)
|
|
625
|
+
self._dark_action.setCheckable(True)
|
|
626
|
+
self._dark_action.triggered.connect(lambda: self._set_theme("dark"))
|
|
627
|
+
self.theme_group.addAction(self._dark_action)
|
|
628
|
+
self.appearance_menu.addAction(self._dark_action)
|
|
629
|
+
self.appearance_menu.addSeparator()
|
|
630
|
+
self._theme_toggle_action = QAction("Switch to Dark Theme", self)
|
|
631
|
+
self._theme_toggle_action.triggered.connect(self._toggle_theme)
|
|
632
|
+
self.appearance_menu.addAction(self._theme_toggle_action)
|
|
633
|
+
if theme.current_theme() == "dark":
|
|
634
|
+
self._dark_action.setChecked(True)
|
|
635
|
+
else:
|
|
636
|
+
self._light_action.setChecked(True)
|
|
637
|
+
self.toolbars_menu = self.view_menu.addMenu("Toolbars")
|
|
638
|
+
self.view_menu.addSeparator()
|
|
639
|
+
self.view_menu.addAction(self.project_dock.toggleViewAction())
|
|
640
|
+
self.view_menu.addAction(self.console_dock.toggleViewAction())
|
|
641
|
+
self.view_menu.addAction(self.log_dock.toggleViewAction())
|
|
642
|
+
self.view_menu.addAction(self.scripts_dock.toggleViewAction())
|
|
643
|
+
|
|
644
|
+
window_menu = menu_bar.addMenu("&Window")
|
|
645
|
+
self._add_action(window_menu, "Close All Views", self._close_all_views)
|
|
646
|
+
self._add_action(window_menu, "Cascade", self.mdi.cascadeSubWindows)
|
|
647
|
+
self._add_action(window_menu, "Tile", self.mdi.tileSubWindows)
|
|
648
|
+
|
|
649
|
+
tools_menu = menu_bar.addMenu("&Tools")
|
|
650
|
+
self._add_action(tools_menu, "Python Console", lambda: (self.console_dock.show(), self.console_dock.raise_()))
|
|
651
|
+
self._add_action(tools_menu, "Scripts", lambda: (self.scripts_dock.show(), self.scripts_dock.raise_()))
|
|
652
|
+
self._add_action(tools_menu, "Report Composer...", self._report_composer)
|
|
653
|
+
self._add_action(tools_menu, "Re-run Stale Reports...", self._rerun_all_stale)
|
|
654
|
+
self._add_action(tools_menu, "Analysis Journal...", self._show_journal)
|
|
655
|
+
self._add_action(tools_menu, "ODBC Drivers / DSNs", self._show_odbc_info)
|
|
656
|
+
|
|
657
|
+
help_menu = menu_bar.addMenu("&Help")
|
|
658
|
+
self._add_action(help_menu, "StatStudio Help...", lambda: self._statstudio_help(), "F1")
|
|
659
|
+
self._add_action(help_menu, "About StatStudio", self._about)
|
|
660
|
+
|
|
661
|
+
self._refresh_recent_projects_menu()
|
|
662
|
+
|
|
663
|
+
def _make_action(self, text: str, slot, shortcut: str | None = None) -> QAction:
|
|
664
|
+
action = QAction(text, self)
|
|
665
|
+
action.triggered.connect(slot)
|
|
666
|
+
if shortcut:
|
|
667
|
+
action.setShortcut(shortcut)
|
|
668
|
+
return action
|
|
669
|
+
|
|
670
|
+
def _add_action(self, menu, text: str, slot, shortcut: str | None = None) -> QAction:
|
|
671
|
+
action = self._make_action(text, slot, shortcut)
|
|
672
|
+
menu.addAction(action)
|
|
673
|
+
return action
|
|
674
|
+
|
|
675
|
+
# ---------------------------------------------------------- commands/UI
|
|
676
|
+
def _retain_menu_wrappers(self) -> None:
|
|
677
|
+
self._menu_action_refs: list[QAction] = []
|
|
678
|
+
self._menu_refs: list[QMenu] = []
|
|
679
|
+
|
|
680
|
+
def retain(menu: QMenu) -> None:
|
|
681
|
+
self._menu_refs.append(menu)
|
|
682
|
+
for action in menu.actions():
|
|
683
|
+
self._menu_action_refs.append(action)
|
|
684
|
+
submenu = action.menu()
|
|
685
|
+
if submenu is not None:
|
|
686
|
+
retain(submenu)
|
|
687
|
+
|
|
688
|
+
for action in self.menuBar().actions():
|
|
689
|
+
self._menu_action_refs.append(action)
|
|
690
|
+
menu = action.menu()
|
|
691
|
+
if menu is not None:
|
|
692
|
+
retain(menu)
|
|
693
|
+
|
|
694
|
+
def _build_commands(self) -> None:
|
|
695
|
+
self._retain_menu_wrappers()
|
|
696
|
+
self.commands = build_catalog(self.menuBar())
|
|
697
|
+
self.commands = {
|
|
698
|
+
command_id: command
|
|
699
|
+
for command_id, command in self.commands.items()
|
|
700
|
+
if command.action is not self.analysis_hub_action
|
|
701
|
+
}
|
|
702
|
+
category_icons = {
|
|
703
|
+
"Data": "table",
|
|
704
|
+
"Compare": "analyze",
|
|
705
|
+
"Model": "graph",
|
|
706
|
+
"Quality": "quality",
|
|
707
|
+
"DOE": "doe",
|
|
708
|
+
"Graphs": "graph",
|
|
709
|
+
"Reports": "report",
|
|
710
|
+
"Scripting": "script",
|
|
711
|
+
"Workspace": "home",
|
|
712
|
+
}
|
|
713
|
+
for command in self.commands.values():
|
|
714
|
+
command.action.setIcon(
|
|
715
|
+
icons.action_icon(category_icons.get(command.category, "command"))
|
|
716
|
+
)
|
|
717
|
+
command.action.setStatusTip(command.description)
|
|
718
|
+
command.action.setToolTip(f"{command.title}\n{command.description}")
|
|
719
|
+
self.home_action.setIcon(icons.action_icon("home"))
|
|
720
|
+
self.home_action.setStatusTip("Show the Home dashboard.")
|
|
721
|
+
self.analysis_hub_action.setIcon(icons.action_icon("analyze"))
|
|
722
|
+
self.analysis_hub_action.setStatusTip("Find and open an analysis, graph, report, or command.")
|
|
723
|
+
self.analysis_hub_action.setToolTip("Analysis Hub (Ctrl+Shift+A)")
|
|
724
|
+
|
|
725
|
+
def _command_action(self, command_id: str) -> QAction | None:
|
|
726
|
+
command = self.commands.get(command_id)
|
|
727
|
+
return command.action if command is not None else None
|
|
728
|
+
|
|
729
|
+
def _build_toolbars(self) -> None:
|
|
730
|
+
self.quick_toolbar = QToolBar("Quick Access", self)
|
|
731
|
+
self.quick_toolbar.setObjectName("quick_access_toolbar")
|
|
732
|
+
self.quick_toolbar.setMovable(False)
|
|
733
|
+
self.quick_toolbar.setFloatable(False)
|
|
734
|
+
self.quick_toolbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
|
|
735
|
+
self.quick_toolbar.setIconSize(QSize(18, 18))
|
|
736
|
+
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.quick_toolbar)
|
|
737
|
+
|
|
738
|
+
self.quick_toolbar.addAction(self.home_action)
|
|
739
|
+
for command_id in ("file.open-project", "file.new-table", "file.import"):
|
|
740
|
+
action = self._command_action(command_id)
|
|
741
|
+
if action is not None:
|
|
742
|
+
self.quick_toolbar.addAction(action)
|
|
743
|
+
self.quick_toolbar.addSeparator()
|
|
744
|
+
for command_id in ("graph.builder", "tools.report-composer", "view.command-palette"):
|
|
745
|
+
action = self._command_action(command_id)
|
|
746
|
+
if action is not None:
|
|
747
|
+
self.quick_toolbar.addAction(action)
|
|
748
|
+
self.quick_toolbar.addAction(self.analysis_hub_action)
|
|
749
|
+
|
|
750
|
+
self.analysis_toolbar = QToolBar("Quick Analyses", self)
|
|
751
|
+
self.analysis_toolbar.setObjectName("quick_analysis_toolbar")
|
|
752
|
+
self.analysis_toolbar.setMovable(False)
|
|
753
|
+
self.analysis_toolbar.setFloatable(False)
|
|
754
|
+
self.analysis_toolbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
|
|
755
|
+
self.analysis_toolbar.setIconSize(QSize(18, 18))
|
|
756
|
+
self.addToolBarBreak(Qt.ToolBarArea.TopToolBarArea)
|
|
757
|
+
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.analysis_toolbar)
|
|
758
|
+
for command_id in (
|
|
759
|
+
"analyze.descriptive",
|
|
760
|
+
"analyze.ttest",
|
|
761
|
+
"analyze.anova",
|
|
762
|
+
"analyze.regression",
|
|
763
|
+
"analyze.quality",
|
|
764
|
+
"doe.custom",
|
|
765
|
+
):
|
|
766
|
+
action = self._command_action(command_id)
|
|
767
|
+
if action is not None:
|
|
768
|
+
self.analysis_toolbar.addAction(action)
|
|
769
|
+
|
|
770
|
+
for toolbar in (self.quick_toolbar, self.analysis_toolbar):
|
|
771
|
+
toggle = toolbar.toggleViewAction()
|
|
772
|
+
toggle.setText(toolbar.windowTitle())
|
|
773
|
+
self.toolbars_menu.addAction(toggle)
|
|
774
|
+
|
|
775
|
+
def _build_status_bar(self) -> None:
|
|
776
|
+
self.document_status = QLabel("Home")
|
|
777
|
+
self.document_status.setObjectName("documentStatus")
|
|
778
|
+
self.document_status.setMinimumWidth(220)
|
|
779
|
+
self.selection_status = QLabel("")
|
|
780
|
+
self.selection_status.setObjectName("selectionStatus")
|
|
781
|
+
self.jobs_status = QLabel("")
|
|
782
|
+
self.jobs_status.setObjectName("jobsStatus")
|
|
783
|
+
self.statusBar().addPermanentWidget(self.document_status)
|
|
784
|
+
self.statusBar().addPermanentWidget(self.selection_status)
|
|
785
|
+
self.statusBar().addPermanentWidget(self.jobs_status)
|
|
786
|
+
self._theme_button = QToolButton()
|
|
787
|
+
self._theme_button.setToolTip("Toggle light and dark theme")
|
|
788
|
+
self._theme_button.setProperty("windowControl", "true")
|
|
789
|
+
self._theme_button.clicked.connect(self._toggle_theme)
|
|
790
|
+
self.statusBar().addPermanentWidget(self._theme_button)
|
|
791
|
+
console_button = QToolButton()
|
|
792
|
+
icons.set_button_icon(console_button, "console")
|
|
793
|
+
console_button.setToolTip("Show Python Console")
|
|
794
|
+
console_button.setProperty("windowControl", "true")
|
|
795
|
+
console_button.clicked.connect(lambda: (self.console_dock.show(), self.console_dock.raise_()))
|
|
796
|
+
self.statusBar().addPermanentWidget(console_button)
|
|
797
|
+
log_button = QToolButton()
|
|
798
|
+
icons.set_button_icon(log_button, "log")
|
|
799
|
+
log_button.setToolTip("Show Log")
|
|
800
|
+
log_button.setProperty("windowControl", "true")
|
|
801
|
+
log_button.clicked.connect(lambda: (self.log_dock.show(), self.log_dock.raise_()))
|
|
802
|
+
self.statusBar().addPermanentWidget(log_button)
|
|
803
|
+
self._job_timer = QTimer(self)
|
|
804
|
+
self._job_timer.setInterval(1000)
|
|
805
|
+
self._job_timer.timeout.connect(self._update_job_status)
|
|
806
|
+
self._job_timer.start()
|
|
807
|
+
self._update_job_status()
|
|
808
|
+
self._sync_theme_controls()
|
|
809
|
+
|
|
810
|
+
def _toggle_theme(self) -> None:
|
|
811
|
+
self._set_theme("light" if theme.current_theme() == "dark" else "dark")
|
|
812
|
+
|
|
813
|
+
def _sync_theme_controls(self) -> None:
|
|
814
|
+
dark = theme.current_theme() == "dark"
|
|
815
|
+
icon_name = "sun" if dark else "moon"
|
|
816
|
+
label = "Switch to Light Theme" if dark else "Switch to Dark Theme"
|
|
817
|
+
if self._theme_toggle_action is not None:
|
|
818
|
+
self._theme_toggle_action.setText(label)
|
|
819
|
+
self._theme_toggle_action.setIcon(icons.action_icon(icon_name))
|
|
820
|
+
if self._theme_button is not None:
|
|
821
|
+
self._theme_button.setIcon(icons.action_icon(icon_name))
|
|
822
|
+
self._theme_button.setToolTip(label)
|
|
823
|
+
|
|
824
|
+
def _refresh_chrome_icons(self) -> None:
|
|
825
|
+
self._document_chrome_refs = [
|
|
826
|
+
ref for ref in self._document_chrome_refs if _qt_alive(ref)
|
|
827
|
+
]
|
|
828
|
+
for ref in self._document_chrome_refs:
|
|
829
|
+
if isinstance(ref, _DocumentResizeGrip):
|
|
830
|
+
ref.update()
|
|
831
|
+
|
|
832
|
+
def _set_theme(self, name: str) -> None:
|
|
833
|
+
app = QApplication.instance()
|
|
834
|
+
if app is not None:
|
|
835
|
+
theme.apply_theme(app, name)
|
|
836
|
+
theme.save_theme(name)
|
|
837
|
+
if self._light_action is not None:
|
|
838
|
+
self._light_action.setChecked(name == "light")
|
|
839
|
+
if self._dark_action is not None:
|
|
840
|
+
self._dark_action.setChecked(name == "dark")
|
|
841
|
+
self._refresh_command_icons()
|
|
842
|
+
self._sync_theme_controls()
|
|
843
|
+
icons.refresh_button_icons(self)
|
|
844
|
+
self.home.refresh_icons()
|
|
845
|
+
self._refresh_chrome_icons()
|
|
846
|
+
self._refresh_project_tree()
|
|
847
|
+
self._refresh_home()
|
|
848
|
+
|
|
849
|
+
def _refresh_command_icons(self) -> None:
|
|
850
|
+
category_icons = {
|
|
851
|
+
"Data": "table",
|
|
852
|
+
"Compare": "analyze",
|
|
853
|
+
"Model": "graph",
|
|
854
|
+
"Quality": "quality",
|
|
855
|
+
"DOE": "doe",
|
|
856
|
+
"Graphs": "graph",
|
|
857
|
+
"Reports": "report",
|
|
858
|
+
"Scripting": "script",
|
|
859
|
+
"Workspace": "home",
|
|
860
|
+
}
|
|
861
|
+
for command in self.commands.values():
|
|
862
|
+
command.action.setIcon(
|
|
863
|
+
icons.action_icon(category_icons.get(command.category, "command"))
|
|
864
|
+
)
|
|
865
|
+
self.home_action.setIcon(icons.action_icon("home"))
|
|
866
|
+
self.analysis_hub_action.setIcon(icons.action_icon("analyze"))
|
|
867
|
+
|
|
868
|
+
def _show_home(self) -> None:
|
|
869
|
+
if self._home_dock_state is None:
|
|
870
|
+
docks = (self.project_dock, self.console_dock, self.log_dock, self.scripts_dock)
|
|
871
|
+
if self.isVisible():
|
|
872
|
+
self._home_dock_state = {dock: not dock.isHidden() for dock in docks}
|
|
873
|
+
else:
|
|
874
|
+
self._home_dock_state = {dock: True for dock in docks}
|
|
875
|
+
for dock in (self.project_dock, self.console_dock, self.log_dock, self.scripts_dock):
|
|
876
|
+
dock.hide()
|
|
877
|
+
self.central_stack.setCurrentWidget(self.home)
|
|
878
|
+
self.home.refresh()
|
|
879
|
+
self._refresh_home()
|
|
880
|
+
self._update_status_context()
|
|
881
|
+
|
|
882
|
+
def _show_workspace(self) -> None:
|
|
883
|
+
if self._home_dock_state is not None:
|
|
884
|
+
for dock, visible in self._home_dock_state.items():
|
|
885
|
+
dock.setVisible(visible)
|
|
886
|
+
self._home_dock_state = None
|
|
887
|
+
self.central_stack.setCurrentWidget(self.workspace)
|
|
888
|
+
|
|
889
|
+
def _refresh_home(self) -> None:
|
|
890
|
+
self.home.refresh()
|
|
891
|
+
titles = []
|
|
892
|
+
for command_id in recent.recent_commands():
|
|
893
|
+
command = self.commands.get(command_id)
|
|
894
|
+
if command is not None:
|
|
895
|
+
titles.append((command_id, command.title))
|
|
896
|
+
self.home.set_recent_commands(titles)
|
|
897
|
+
self._refresh_recent_projects_menu()
|
|
898
|
+
|
|
899
|
+
def _refresh_recent_projects_menu(self) -> None:
|
|
900
|
+
menu = getattr(self, "recent_projects_menu", None)
|
|
901
|
+
if menu is None:
|
|
902
|
+
return
|
|
903
|
+
menu.clear()
|
|
904
|
+
self._recent_project_actions: list[QAction] = []
|
|
905
|
+
paths = recent.recent_projects()
|
|
906
|
+
if not paths:
|
|
907
|
+
empty = menu.addAction("No Recent Projects")
|
|
908
|
+
empty.setEnabled(False)
|
|
909
|
+
return
|
|
910
|
+
for path in paths:
|
|
911
|
+
project_path = Path(path)
|
|
912
|
+
label = project_path.name or path
|
|
913
|
+
action = QAction(label, self)
|
|
914
|
+
action.setToolTip(path)
|
|
915
|
+
action.setStatusTip(path)
|
|
916
|
+
if not project_path.exists():
|
|
917
|
+
action.setText(f"{label} (missing)")
|
|
918
|
+
action.triggered.connect(lambda _checked=False, value=path: self._open_recent_project(value))
|
|
919
|
+
menu.addAction(action)
|
|
920
|
+
self._recent_project_actions.append(action)
|
|
921
|
+
|
|
922
|
+
def _show_analysis_hub(self, initial_query: str | bool = "") -> None:
|
|
923
|
+
query = initial_query if isinstance(initial_query, str) else ""
|
|
924
|
+
dialog = AnalysisHubDialog(self.commands, self, initial_query=query)
|
|
925
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.chosen_id:
|
|
926
|
+
self._run_command(dialog.chosen_id)
|
|
927
|
+
|
|
928
|
+
def _run_command(self, command_id: str) -> None:
|
|
929
|
+
command = self.commands.get(command_id)
|
|
930
|
+
if command is None:
|
|
931
|
+
return
|
|
932
|
+
recent.remember_command(command_id)
|
|
933
|
+
self._refresh_home()
|
|
934
|
+
command.action.trigger()
|
|
935
|
+
|
|
936
|
+
def _update_status_context(self) -> None:
|
|
937
|
+
if not hasattr(self, "document_status"):
|
|
938
|
+
return
|
|
939
|
+
try:
|
|
940
|
+
from shiboken6 import isValid
|
|
941
|
+
|
|
942
|
+
if not isValid(self.central_stack):
|
|
943
|
+
return
|
|
944
|
+
except Exception:
|
|
945
|
+
return
|
|
946
|
+
if self.central_stack.currentWidget() is self.home:
|
|
947
|
+
self.document_status.setText("Home")
|
|
948
|
+
self.selection_status.setText("")
|
|
949
|
+
return
|
|
950
|
+
widget = self._active_document()
|
|
951
|
+
if widget is None:
|
|
952
|
+
self.document_status.setText("No open documents")
|
|
953
|
+
self.selection_status.setText("")
|
|
954
|
+
return
|
|
955
|
+
if isinstance(widget, TableDocument):
|
|
956
|
+
table = widget.table
|
|
957
|
+
self.document_status.setText(f"Table {table.name}")
|
|
958
|
+
self.selection_status.setText(f"{len(table)} rows x {len(table.columns)} columns")
|
|
959
|
+
else:
|
|
960
|
+
title = getattr(widget, "windowTitle", lambda: "")() or "Report"
|
|
961
|
+
self.document_status.setText(title)
|
|
962
|
+
self.selection_status.setText("")
|
|
963
|
+
|
|
964
|
+
def _update_selection_status(self, table: DataTable, rows) -> None:
|
|
965
|
+
if not hasattr(self, "selection_status"):
|
|
966
|
+
return
|
|
967
|
+
view = self._active_table_view()
|
|
968
|
+
if view is None or view.table is not table:
|
|
969
|
+
return
|
|
970
|
+
count = len(rows or [])
|
|
971
|
+
if count:
|
|
972
|
+
self.selection_status.setText(
|
|
973
|
+
f"{count} selected | {len(table)} rows x {len(table.columns)} columns"
|
|
974
|
+
)
|
|
975
|
+
else:
|
|
976
|
+
self.selection_status.setText(f"{len(table)} rows x {len(table.columns)} columns")
|
|
977
|
+
|
|
978
|
+
def _update_job_status(self) -> None:
|
|
979
|
+
if not hasattr(self, "jobs_status"):
|
|
980
|
+
return
|
|
981
|
+
from statstudio.ui.jobs import active_job_count
|
|
982
|
+
|
|
983
|
+
count = active_job_count()
|
|
984
|
+
self.jobs_status.setText(f"{count} running" if count else "")
|
|
985
|
+
self.jobs_status.setVisible(bool(count))
|
|
986
|
+
|
|
987
|
+
# ------------------------------------------------------------- project
|
|
988
|
+
def _load_project_into_ui(self, project: Project, *, live_reports: bool = True) -> None:
|
|
989
|
+
self._close_all_tabs()
|
|
990
|
+
self.project = project
|
|
991
|
+
self._project_dirty = False
|
|
992
|
+
self._hash_cache.clear()
|
|
993
|
+
for table in project.tables:
|
|
994
|
+
table.modified = False
|
|
995
|
+
self.console.set_project(project)
|
|
996
|
+
self.scripts_panel.set_project(project)
|
|
997
|
+
for table in project.tables:
|
|
998
|
+
self.open_table_view(table, refresh_tree=False)
|
|
999
|
+
for report in project.reports:
|
|
1000
|
+
self._open_saved_report(report, live=live_reports)
|
|
1001
|
+
self._refresh_project_tree()
|
|
1002
|
+
self._update_title()
|
|
1003
|
+
if project.path is not None:
|
|
1004
|
+
recent.remember_project(project.path)
|
|
1005
|
+
self._log(f"Project loaded: {project.name}")
|
|
1006
|
+
self._update_undo_actions()
|
|
1007
|
+
self._refresh_home()
|
|
1008
|
+
if not self.mdi.subWindowList():
|
|
1009
|
+
self._show_home()
|
|
1010
|
+
|
|
1011
|
+
def _table_hash(self, table: DataTable) -> str:
|
|
1012
|
+
import hashlib
|
|
1013
|
+
import json
|
|
1014
|
+
|
|
1015
|
+
cache_key = id(table)
|
|
1016
|
+
cache = getattr(self, "_hash_cache", None)
|
|
1017
|
+
if cache is not None:
|
|
1018
|
+
cached = cache.get(cache_key)
|
|
1019
|
+
if cached is not None:
|
|
1020
|
+
return cached
|
|
1021
|
+
payload = {
|
|
1022
|
+
"data": hashlib.sha1(
|
|
1023
|
+
pd.util.hash_pandas_object(table.data, index=True).to_numpy().tobytes()
|
|
1024
|
+
).hexdigest(),
|
|
1025
|
+
"filter": table.row_filter or "",
|
|
1026
|
+
"sort": [list(spec) for spec in table.sort_spec],
|
|
1027
|
+
"excluded": sorted(str(row) for row in table.excluded_rows),
|
|
1028
|
+
"hidden": sorted(str(row) for row in table.hidden_rows),
|
|
1029
|
+
"modeling": {name: spec.modeling_type for name, spec in table.specs.items()},
|
|
1030
|
+
"types": {name: spec.data_type for name, spec in table.specs.items()},
|
|
1031
|
+
}
|
|
1032
|
+
digest = hashlib.sha1(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
|
|
1033
|
+
if cache is not None:
|
|
1034
|
+
cache[cache_key] = digest
|
|
1035
|
+
return digest
|
|
1036
|
+
|
|
1037
|
+
def _report_is_stale(self, record: ReportRecord) -> bool:
|
|
1038
|
+
table = self.project.find_table(record.source_table) if record.source_table else None
|
|
1039
|
+
return bool(record.data_hash and table is not None and self._table_hash(table) != record.data_hash)
|
|
1040
|
+
|
|
1041
|
+
def _restore_window_state(self) -> None:
|
|
1042
|
+
settings = QSettings("StatStudio", "StatStudio")
|
|
1043
|
+
geometry = settings.value("geometry_v2")
|
|
1044
|
+
state = settings.value("windowState_v2")
|
|
1045
|
+
if geometry is not None:
|
|
1046
|
+
self.restoreGeometry(geometry)
|
|
1047
|
+
if state is not None:
|
|
1048
|
+
self.restoreState(state)
|
|
1049
|
+
|
|
1050
|
+
def _show_command_palette(self) -> None:
|
|
1051
|
+
actions: list[QAction] = []
|
|
1052
|
+
|
|
1053
|
+
def collect(menu, path: tuple[str, ...]) -> None:
|
|
1054
|
+
for action in menu.actions():
|
|
1055
|
+
if action.isSeparator() or not action.text():
|
|
1056
|
+
continue
|
|
1057
|
+
self._palette_action_refs.append(action)
|
|
1058
|
+
label = action.text().replace("&&", "\0").replace("&", "").replace("\0", "&")
|
|
1059
|
+
submenu = action.menu()
|
|
1060
|
+
if submenu is not None:
|
|
1061
|
+
self._palette_menu_refs.append(submenu)
|
|
1062
|
+
collect(submenu, path + (label,))
|
|
1063
|
+
else:
|
|
1064
|
+
action.setProperty("menu_path", " > ".join(path + (label,)))
|
|
1065
|
+
actions.append(action)
|
|
1066
|
+
|
|
1067
|
+
self._palette_action_refs: list[QAction] = []
|
|
1068
|
+
self._palette_menu_refs: list[QMenu] = []
|
|
1069
|
+
for menu_action in self.menuBar().actions():
|
|
1070
|
+
self._palette_action_refs.append(menu_action)
|
|
1071
|
+
menu = menu_action.menu()
|
|
1072
|
+
if menu is not None:
|
|
1073
|
+
label = menu_action.text().replace("&&", "\0").replace("&", "").replace("\0", "&")
|
|
1074
|
+
collect(menu, (label,))
|
|
1075
|
+
CommandPaletteDialog(actions, self).exec()
|
|
1076
|
+
|
|
1077
|
+
def _has_unsaved_changes(self) -> bool:
|
|
1078
|
+
return self._project_dirty or any(table.modified for table in self.project.tables)
|
|
1079
|
+
|
|
1080
|
+
def _update_title(self) -> None:
|
|
1081
|
+
suffix = f" - {self.project.path}" if self.project.path else ""
|
|
1082
|
+
dirty = " *" if self._has_unsaved_changes() else ""
|
|
1083
|
+
self.setWindowTitle(f"StatStudio - {self.project.name}{suffix}{dirty}")
|
|
1084
|
+
|
|
1085
|
+
def _refresh_project_tree(self) -> None:
|
|
1086
|
+
self.project_tree.clear()
|
|
1087
|
+
root = QTreeWidgetItem([self.project.name])
|
|
1088
|
+
root.setIcon(0, icons.action_icon("home"))
|
|
1089
|
+
root.setExpanded(True)
|
|
1090
|
+
self.project_tree.addTopLevelItem(root)
|
|
1091
|
+
tables_item = QTreeWidgetItem(["Data Tables"])
|
|
1092
|
+
tables_item.setIcon(0, icons.action_icon("table"))
|
|
1093
|
+
tables_item.setExpanded(True)
|
|
1094
|
+
root.addChild(tables_item)
|
|
1095
|
+
for table in self.project.tables:
|
|
1096
|
+
item = QTreeWidgetItem([f"{table.name} ({len(table)} x {len(table.columns)})"])
|
|
1097
|
+
item.setIcon(0, icons.action_icon("table"))
|
|
1098
|
+
item.setData(0, Qt.ItemDataRole.UserRole, ("table", table))
|
|
1099
|
+
item.setToolTip(0, f"{table.name}: {len(table)} rows x {len(table.columns)} columns")
|
|
1100
|
+
tables_item.addChild(item)
|
|
1101
|
+
reports_item = QTreeWidgetItem(["Reports"])
|
|
1102
|
+
reports_item.setIcon(0, icons.action_icon("report"))
|
|
1103
|
+
reports_item.setExpanded(True)
|
|
1104
|
+
root.addChild(reports_item)
|
|
1105
|
+
for index, report in enumerate(self.project.reports):
|
|
1106
|
+
suffix = " [stale]" if self._report_is_stale(report) else ""
|
|
1107
|
+
item = QTreeWidgetItem([f"{report.title}{suffix}"])
|
|
1108
|
+
item.setIcon(0, icons.action_icon("report"))
|
|
1109
|
+
item.setData(0, Qt.ItemDataRole.UserRole, ("report", index))
|
|
1110
|
+
item.setToolTip(0, report.title)
|
|
1111
|
+
reports_item.addChild(item)
|
|
1112
|
+
self.project_tree.expandAll()
|
|
1113
|
+
|
|
1114
|
+
def _tree_double_clicked(self, item: QTreeWidgetItem, column: int) -> None:
|
|
1115
|
+
data = item.data(0, Qt.ItemDataRole.UserRole)
|
|
1116
|
+
if not data:
|
|
1117
|
+
return
|
|
1118
|
+
kind, payload = data
|
|
1119
|
+
if kind == "table":
|
|
1120
|
+
self.open_table_view(payload)
|
|
1121
|
+
elif kind == "report":
|
|
1122
|
+
try:
|
|
1123
|
+
record = self.project.reports[int(payload)]
|
|
1124
|
+
except Exception:
|
|
1125
|
+
return
|
|
1126
|
+
self._open_saved_report(record, live=False)
|
|
1127
|
+
|
|
1128
|
+
def _project_tree_context_menu(self, position) -> None:
|
|
1129
|
+
item = self.project_tree.itemAt(position)
|
|
1130
|
+
if item is None:
|
|
1131
|
+
return
|
|
1132
|
+
data = item.data(0, Qt.ItemDataRole.UserRole)
|
|
1133
|
+
if not data:
|
|
1134
|
+
return
|
|
1135
|
+
kind, payload = data
|
|
1136
|
+
menu = QMenu(self)
|
|
1137
|
+
if kind == "table":
|
|
1138
|
+
table = payload
|
|
1139
|
+
open_action = menu.addAction(icons.action_icon("table"), "Open Table")
|
|
1140
|
+
open_action.triggered.connect(lambda: self.open_table_view(table))
|
|
1141
|
+
analyze_action = menu.addAction(icons.action_icon("analyze"), "Analyze...")
|
|
1142
|
+
analyze_action.triggered.connect(lambda: (self.open_table_view(table), self._show_analysis_hub()))
|
|
1143
|
+
rename_action = menu.addAction("Rename Table...")
|
|
1144
|
+
rename_action.triggered.connect(lambda: self._rename_table_from_tree(table))
|
|
1145
|
+
duplicate_action = menu.addAction("Duplicate Table...")
|
|
1146
|
+
duplicate_action.triggered.connect(lambda: (self.open_table_view(table), self._duplicate_table()))
|
|
1147
|
+
export_action = menu.addAction(icons.action_icon("export"), "Export Table...")
|
|
1148
|
+
export_action.triggered.connect(lambda: (self.open_table_view(table), self._export_table()))
|
|
1149
|
+
menu.addSeparator()
|
|
1150
|
+
delete_action = menu.addAction(icons.action_icon("trash"), "Delete Table")
|
|
1151
|
+
delete_action.triggered.connect(lambda: self._delete_table_now(table))
|
|
1152
|
+
elif kind == "report":
|
|
1153
|
+
try:
|
|
1154
|
+
record = self.project.reports[int(payload)]
|
|
1155
|
+
except Exception:
|
|
1156
|
+
return
|
|
1157
|
+
open_action = menu.addAction(icons.action_icon("report"), "Open Report")
|
|
1158
|
+
open_action.triggered.connect(lambda: self._open_saved_report(record, live=False))
|
|
1159
|
+
delete_action = menu.addAction(icons.action_icon("trash"), "Delete Report")
|
|
1160
|
+
delete_action.triggered.connect(lambda: self._delete_report(record))
|
|
1161
|
+
else:
|
|
1162
|
+
return
|
|
1163
|
+
menu.exec(self.project_tree.viewport().mapToGlobal(position))
|
|
1164
|
+
|
|
1165
|
+
def _rename_table_from_tree(self, table: DataTable) -> None:
|
|
1166
|
+
dialog = RenameTableDialog(table.name, self)
|
|
1167
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
1168
|
+
return
|
|
1169
|
+
self._rename_table_to(table, dialog.result)
|
|
1170
|
+
|
|
1171
|
+
def _open_saved_report(self, record: ReportRecord, *, live: bool = True) -> None:
|
|
1172
|
+
from statstudio.ui.reports.report_view import SavedReportView
|
|
1173
|
+
|
|
1174
|
+
for view in list(self.report_views):
|
|
1175
|
+
if getattr(view, "report_record", None) is record:
|
|
1176
|
+
self._activate_document(view)
|
|
1177
|
+
return
|
|
1178
|
+
if record.kind == "plot_page":
|
|
1179
|
+
if self._restore_plot_page(record):
|
|
1180
|
+
return
|
|
1181
|
+
elif live and self._restore_analysis_report(record):
|
|
1182
|
+
return
|
|
1183
|
+
rerun = None
|
|
1184
|
+
if record.params and record.kind:
|
|
1185
|
+
def rerun() -> None:
|
|
1186
|
+
self._rerun_saved_report(record)
|
|
1187
|
+
title = f"{record.title} [stale]" if self._report_is_stale(record) else record.title
|
|
1188
|
+
view = SavedReportView(title, self._report_html(record), rerun=rerun, code=record.code, table_name=record.source_table)
|
|
1189
|
+
view.report_record = record
|
|
1190
|
+
self._add_document(view, title)
|
|
1191
|
+
self.report_views.append(view)
|
|
1192
|
+
|
|
1193
|
+
def _restore_analysis_report(self, record: ReportRecord) -> bool:
|
|
1194
|
+
from statstudio.ui.reports.report_view import ReportView
|
|
1195
|
+
|
|
1196
|
+
table = self.project.find_table(record.source_table) if record.source_table else None
|
|
1197
|
+
if table is None:
|
|
1198
|
+
return False
|
|
1199
|
+
try:
|
|
1200
|
+
result = self._recompute_record(record)
|
|
1201
|
+
except Exception as exc:
|
|
1202
|
+
self._log(f"Could not reopen report {record.title}: {exc}")
|
|
1203
|
+
return False
|
|
1204
|
+
if result is None:
|
|
1205
|
+
return False
|
|
1206
|
+
self._apply_recomputed_record(record, result)
|
|
1207
|
+
|
|
1208
|
+
def linked(rows, t=table):
|
|
1209
|
+
self._linked_selection(t.name, rows)
|
|
1210
|
+
|
|
1211
|
+
report_timer = QTimer(self)
|
|
1212
|
+
report_timer.setSingleShot(True)
|
|
1213
|
+
report_timer.setInterval(200)
|
|
1214
|
+
|
|
1215
|
+
def flush_report_change() -> None:
|
|
1216
|
+
record.html = result.to_html(include_plots=True)
|
|
1217
|
+
self._persist_report_state(record, result)
|
|
1218
|
+
record.code = scripting.analysis_code(result, "table") if table is not None else ""
|
|
1219
|
+
|
|
1220
|
+
def report_changed() -> None:
|
|
1221
|
+
self._persist_report_state(record, result)
|
|
1222
|
+
report_timer.start()
|
|
1223
|
+
|
|
1224
|
+
report_timer.timeout.connect(flush_report_change)
|
|
1225
|
+
|
|
1226
|
+
def rerun() -> None:
|
|
1227
|
+
self._rerun_saved_report(record)
|
|
1228
|
+
|
|
1229
|
+
title = f"{record.title} [stale]" if self._report_is_stale(record) else record.title
|
|
1230
|
+
view = ReportView(
|
|
1231
|
+
result,
|
|
1232
|
+
rerun=rerun,
|
|
1233
|
+
linked_selection=linked,
|
|
1234
|
+
code=record.code,
|
|
1235
|
+
table=table,
|
|
1236
|
+
report_changed=report_changed,
|
|
1237
|
+
create_subset=self._create_subset_from_selection,
|
|
1238
|
+
)
|
|
1239
|
+
view.title_label.setText(title)
|
|
1240
|
+
view.report_record = record
|
|
1241
|
+
self._add_document(view, title)
|
|
1242
|
+
self.report_views.append(view)
|
|
1243
|
+
return True
|
|
1244
|
+
|
|
1245
|
+
def _persist_report_state(self, record: ReportRecord, result: AnalysisResult) -> None:
|
|
1246
|
+
record.params["plot_params"] = self._plot_params_for(result)
|
|
1247
|
+
self._store_report_ui(result, record.params)
|
|
1248
|
+
self._mark_project_dirty()
|
|
1249
|
+
|
|
1250
|
+
@staticmethod
|
|
1251
|
+
def _plot_params_for(result: AnalysisResult) -> list[dict]:
|
|
1252
|
+
return [
|
|
1253
|
+
{
|
|
1254
|
+
"kind": plot.kind,
|
|
1255
|
+
"title": plot.title,
|
|
1256
|
+
"params": dict(plot.params),
|
|
1257
|
+
"include_in_report": plot.include_in_report,
|
|
1258
|
+
}
|
|
1259
|
+
for plot in result.plots
|
|
1260
|
+
]
|
|
1261
|
+
|
|
1262
|
+
@staticmethod
|
|
1263
|
+
def _store_report_ui(result: AnalysisResult, params: dict) -> None:
|
|
1264
|
+
report_ui = result.params.get("report_ui") if isinstance(result.params, dict) else None
|
|
1265
|
+
if isinstance(report_ui, dict):
|
|
1266
|
+
params["report_ui"] = dict(report_ui)
|
|
1267
|
+
else:
|
|
1268
|
+
params.pop("report_ui", None)
|
|
1269
|
+
|
|
1270
|
+
def _remember_table_selection(self, table: DataTable, rows) -> None:
|
|
1271
|
+
self._selection_state = (table.name, list(rows or []))
|
|
1272
|
+
|
|
1273
|
+
def _linked_selection(self, table_name: str, rows) -> None:
|
|
1274
|
+
self._selection_state = (table_name, list(rows or []))
|
|
1275
|
+
if not rows:
|
|
1276
|
+
return
|
|
1277
|
+
table = self.project.find_table(table_name) if table_name else None
|
|
1278
|
+
if table is not None:
|
|
1279
|
+
view = self.table_views.get(table)
|
|
1280
|
+
if view is not None:
|
|
1281
|
+
view.select_rows_by_id(rows)
|
|
1282
|
+
for report in list(self.report_views):
|
|
1283
|
+
apply_selection = getattr(report, "apply_selection", None)
|
|
1284
|
+
if apply_selection is not None:
|
|
1285
|
+
try:
|
|
1286
|
+
apply_selection(table_name, rows)
|
|
1287
|
+
except Exception:
|
|
1288
|
+
pass
|
|
1289
|
+
|
|
1290
|
+
def _page_table(self, page) -> DataTable | None:
|
|
1291
|
+
table = getattr(page, "table", None)
|
|
1292
|
+
if table is not None:
|
|
1293
|
+
return table
|
|
1294
|
+
source = getattr(getattr(page, "result", None), "source_table", "") or ""
|
|
1295
|
+
return self.project.find_table(source) if source else None
|
|
1296
|
+
|
|
1297
|
+
def _plot_pages_for_table(self, table: DataTable | None):
|
|
1298
|
+
if table is None:
|
|
1299
|
+
return []
|
|
1300
|
+
return [page for page in self._plot_records if self._page_table(page) is table]
|
|
1301
|
+
|
|
1302
|
+
def _plot_page_for_table(self, table: DataTable | None):
|
|
1303
|
+
pages = self._plot_pages_for_table(table)
|
|
1304
|
+
return pages[-1] if pages else None
|
|
1305
|
+
|
|
1306
|
+
def _next_plot_page_title(self, table: DataTable) -> str:
|
|
1307
|
+
base = f"Graph \u2014 {table.name}"
|
|
1308
|
+
used = {
|
|
1309
|
+
record.title
|
|
1310
|
+
for record in self.project.reports
|
|
1311
|
+
if record.kind == "plot_page" and record.source_table == table.name
|
|
1312
|
+
}
|
|
1313
|
+
if base not in used:
|
|
1314
|
+
return base
|
|
1315
|
+
index = 2
|
|
1316
|
+
while f"{base} ({index})" in used:
|
|
1317
|
+
index += 1
|
|
1318
|
+
return f"{base} ({index})"
|
|
1319
|
+
|
|
1320
|
+
def _plot_page_result(self, record: ReportRecord) -> tuple[AnalysisResult | None, DataTable | None]:
|
|
1321
|
+
table = self.project.find_table(record.source_table) if record.source_table else None
|
|
1322
|
+
specs = (record.params or {}).get("specs")
|
|
1323
|
+
if table is None or not specs:
|
|
1324
|
+
return None, None
|
|
1325
|
+
page_result = AnalysisResult(
|
|
1326
|
+
title=record.title,
|
|
1327
|
+
analysis_type="plot_page",
|
|
1328
|
+
source_table=table.name,
|
|
1329
|
+
summary=f"Graphs of {table.name}.",
|
|
1330
|
+
params=dict(record.params or {}),
|
|
1331
|
+
)
|
|
1332
|
+
data = table.plot_df()
|
|
1333
|
+
for spec in specs:
|
|
1334
|
+
if not isinstance(spec, dict):
|
|
1335
|
+
continue
|
|
1336
|
+
row_ids = spec.get("row_ids")
|
|
1337
|
+
chunk = data
|
|
1338
|
+
if row_ids:
|
|
1339
|
+
valid = [row_id for row_id in row_ids if row_id in data.index]
|
|
1340
|
+
if valid:
|
|
1341
|
+
chunk = data.loc[valid]
|
|
1342
|
+
page_result.plots.append(
|
|
1343
|
+
PlotSpec(
|
|
1344
|
+
kind=spec.get("kind", "histogram"),
|
|
1345
|
+
params=dict(spec.get("params") or {}),
|
|
1346
|
+
title=spec.get("title", ""),
|
|
1347
|
+
data=chunk,
|
|
1348
|
+
row_ids=list(chunk.index),
|
|
1349
|
+
include_in_report=bool(spec.get("include_in_report", True)),
|
|
1350
|
+
row_styles={row_id: table.row_state(row_id) for row_id in chunk.index},
|
|
1351
|
+
)
|
|
1352
|
+
)
|
|
1353
|
+
return page_result, table
|
|
1354
|
+
|
|
1355
|
+
def _restore_plot_page(self, record: ReportRecord) -> bool:
|
|
1356
|
+
from statstudio.ui.reports.report_view import ReportView
|
|
1357
|
+
|
|
1358
|
+
page_result, table = self._plot_page_result(record)
|
|
1359
|
+
if page_result is None or table is None:
|
|
1360
|
+
return False
|
|
1361
|
+
def linked(rows, t=table):
|
|
1362
|
+
self._linked_selection(t.name, rows)
|
|
1363
|
+
|
|
1364
|
+
holder: dict = {}
|
|
1365
|
+
|
|
1366
|
+
def report_changed():
|
|
1367
|
+
page = holder.get("page")
|
|
1368
|
+
if page is not None:
|
|
1369
|
+
self._update_plot_report(page)
|
|
1370
|
+
|
|
1371
|
+
def switch_columns():
|
|
1372
|
+
page = holder.get("page")
|
|
1373
|
+
if page is not None:
|
|
1374
|
+
self._open_column_switcher(page)
|
|
1375
|
+
|
|
1376
|
+
local_filter = (record.params or {}).get("local_filter", "") or ""
|
|
1377
|
+
page = ReportView(
|
|
1378
|
+
page_result,
|
|
1379
|
+
linked_selection=linked,
|
|
1380
|
+
table=table,
|
|
1381
|
+
report_changed=report_changed,
|
|
1382
|
+
column_switcher=switch_columns,
|
|
1383
|
+
local_filter=local_filter,
|
|
1384
|
+
create_subset=self._create_subset_from_selection,
|
|
1385
|
+
defer_plots=len(page_result.plots) > 1,
|
|
1386
|
+
)
|
|
1387
|
+
holder["page"] = page
|
|
1388
|
+
page.report_record = record
|
|
1389
|
+
self._add_document(page, page_result.title)
|
|
1390
|
+
self.report_views.append(page)
|
|
1391
|
+
self._plot_records[page] = record
|
|
1392
|
+
return True
|
|
1393
|
+
|
|
1394
|
+
def _dialog_for_analysis(self, kind: str):
|
|
1395
|
+
from statstudio.ui.dialogs.lazy import LazyDialog
|
|
1396
|
+
|
|
1397
|
+
dialog = {
|
|
1398
|
+
"descriptive": DescriptiveDialog,
|
|
1399
|
+
"plot": PlotDialog,
|
|
1400
|
+
"frequency": FrequencyDialog,
|
|
1401
|
+
"grouped_summary": GroupSummaryDialog,
|
|
1402
|
+
"distribution_fit": DistributionDialog,
|
|
1403
|
+
"distribution_summary": DistributionSummaryDialog,
|
|
1404
|
+
"t_test_one": TTestDialog,
|
|
1405
|
+
"t_test_two": TTestDialog,
|
|
1406
|
+
"t_test_paired": TTestDialog,
|
|
1407
|
+
"anova": ANOVADialog,
|
|
1408
|
+
"kruskal": ANOVADialog,
|
|
1409
|
+
"two_way_anova": TwoWayANOVADialog,
|
|
1410
|
+
"posthoc": PostHocDialog,
|
|
1411
|
+
"fit_y_by_x": FitYByXDialog,
|
|
1412
|
+
"contingency": ContingencyDialog,
|
|
1413
|
+
"chi_square": ChiSquareDialog,
|
|
1414
|
+
"proportion": ProportionDialog,
|
|
1415
|
+
"normality": NormalityDialog,
|
|
1416
|
+
"mann_whitney": MannWhitneyDialog,
|
|
1417
|
+
"wilcoxon": WilcoxonDialog,
|
|
1418
|
+
"sign_test": SignTestDialog,
|
|
1419
|
+
"one_sample_wilcoxon": WilcoxonOneDialog,
|
|
1420
|
+
"mood_median": MoodMedianDialog,
|
|
1421
|
+
"friedman": FriedmanDialog,
|
|
1422
|
+
"runs_test": RunsTestDialog,
|
|
1423
|
+
"equivalence": EquivalentTestDialog,
|
|
1424
|
+
"distribution_id": DistributionIDDialog,
|
|
1425
|
+
"tolerance_interval": ToleranceDialog,
|
|
1426
|
+
"process_screening": ProcessScreeningDialog,
|
|
1427
|
+
"prediction_profiler": ProfilerDialog,
|
|
1428
|
+
"custom_prediction_profiler": ProfilerDialog,
|
|
1429
|
+
"regression_prediction_profiler": RegressionProfilerDialog,
|
|
1430
|
+
"response_simulation": SimulationDialog,
|
|
1431
|
+
"custom_response_simulation": SimulationDialog,
|
|
1432
|
+
"multi_response_optimization": MultiResponseDialog,
|
|
1433
|
+
"regression_multi_response_optimization": RegressionMultiResponseDialog,
|
|
1434
|
+
"correlation": CorrelationDialog,
|
|
1435
|
+
"covariance": CovarianceDialog,
|
|
1436
|
+
"linear_regression": RegressionDialog,
|
|
1437
|
+
"polynomial_regression": RegressionDialog,
|
|
1438
|
+
"glm": RegressionDialog,
|
|
1439
|
+
"mixed_model": RegressionDialog,
|
|
1440
|
+
"gee": RegressionDialog,
|
|
1441
|
+
"stepwise_regression": RegressionDialog,
|
|
1442
|
+
"multivariate": MultivariateDialog,
|
|
1443
|
+
"pca": MultivariateDialog,
|
|
1444
|
+
"kmeans": MultivariateDialog,
|
|
1445
|
+
"hierarchical_clustering": MultivariateDialog,
|
|
1446
|
+
"factor_analysis": MultivariateDialog,
|
|
1447
|
+
"manova": MultivariateDialog,
|
|
1448
|
+
"discriminant": MultivariateDialog,
|
|
1449
|
+
"canonical_correlation": MultivariateDialog,
|
|
1450
|
+
"predictive": PredictiveDialog,
|
|
1451
|
+
"cart": PredictiveDialog,
|
|
1452
|
+
"random_forest": PredictiveDialog,
|
|
1453
|
+
"neural": PredictiveDialog,
|
|
1454
|
+
"xgboost": PredictiveDialog,
|
|
1455
|
+
"svm": PredictiveDialog,
|
|
1456
|
+
"naive_bayes": PredictiveDialog,
|
|
1457
|
+
"automl": PredictiveDialog,
|
|
1458
|
+
"time_series": TimeSeriesDialog,
|
|
1459
|
+
"ts_summary": TimeSeriesDialog,
|
|
1460
|
+
"acf_pacf": TimeSeriesDialog,
|
|
1461
|
+
"stationarity": TimeSeriesDialog,
|
|
1462
|
+
"decomposition": TimeSeriesDialog,
|
|
1463
|
+
"stl": TimeSeriesDialog,
|
|
1464
|
+
"arima": TimeSeriesDialog,
|
|
1465
|
+
"exponential_smoothing": TimeSeriesDialog,
|
|
1466
|
+
"survival": SurvivalDialog,
|
|
1467
|
+
"competing_risk": CompetingRiskDialog,
|
|
1468
|
+
"cumulative_incidence": CompetingRiskDialog,
|
|
1469
|
+
"reliability": ReliabilityDialog,
|
|
1470
|
+
"forecast": ForecastDialog,
|
|
1471
|
+
"control_chart": QualityDialog,
|
|
1472
|
+
"capability": QualityDialog,
|
|
1473
|
+
"gage_rr": QualityDialog,
|
|
1474
|
+
"attribute_agreement": QualityDialog,
|
|
1475
|
+
"pareto": QualityDialog,
|
|
1476
|
+
"power_t": PowerDialog,
|
|
1477
|
+
"power_t_sample_size": PowerDialog,
|
|
1478
|
+
"power_proportion": PowerDialog,
|
|
1479
|
+
"power_anova": PowerDialog,
|
|
1480
|
+
"power_paired_t": PowerDialog,
|
|
1481
|
+
"power_equivalence": PowerDialog,
|
|
1482
|
+
"power_variance": PowerDialog,
|
|
1483
|
+
"power_curve": PowerDialog,
|
|
1484
|
+
"doe_analysis": DOEAnalysisDialog,
|
|
1485
|
+
"doe_diagnostics": DOEAnalysisDialog,
|
|
1486
|
+
"custom_doe_analysis": DOEAnalysisDialog,
|
|
1487
|
+
"mixture_analysis": DOEAnalysisDialog,
|
|
1488
|
+
"regression": RegressionDialog,
|
|
1489
|
+
"logistic_regression": RegressionDialog,
|
|
1490
|
+
"poisson_regression": RegressionDialog,
|
|
1491
|
+
"negative_binomial_regression": RegressionDialog,
|
|
1492
|
+
"kaplan_meier": SurvivalDialog,
|
|
1493
|
+
"logrank": SurvivalDialog,
|
|
1494
|
+
"cox": SurvivalDialog,
|
|
1495
|
+
"cox_regression": SurvivalDialog,
|
|
1496
|
+
"weibull_aft": SurvivalDialog,
|
|
1497
|
+
"interval_censored_weibull": SurvivalDialog,
|
|
1498
|
+
"reliability_zero_failures": ZeroFailureReliabilityDialog,
|
|
1499
|
+
"bayesian_linear_regression": BayesianLinearRegressionDialog,
|
|
1500
|
+
"bayesian_logistic_regression": BayesianLogisticRegressionDialog,
|
|
1501
|
+
"bayesian_two_sample": BayesianTwoSampleDialog,
|
|
1502
|
+
"bayesian_anova": BayesianANOVADialog,
|
|
1503
|
+
"bayesian_optimization": BayesianOptimizationDialog,
|
|
1504
|
+
}.get(kind)
|
|
1505
|
+
return dialog.load() if isinstance(dialog, LazyDialog) else dialog
|
|
1506
|
+
|
|
1507
|
+
def _rerun_saved_report(self, record: ReportRecord) -> None:
|
|
1508
|
+
table = self.project.find_table(record.source_table) if record.source_table else None
|
|
1509
|
+
dialog_class = self._dialog_for_analysis(record.kind)
|
|
1510
|
+
if table is None or dialog_class is None:
|
|
1511
|
+
QMessageBox.information(self, "Re-run Report", "This saved report cannot be re-run because its source table or analysis type is unavailable.")
|
|
1512
|
+
return
|
|
1513
|
+
self._open_stats_for(table, dialog_class, record.params, record.kind)
|
|
1514
|
+
|
|
1515
|
+
def _rerun_all_stale(self) -> None:
|
|
1516
|
+
stale = [record for record in self.project.reports if self._report_is_stale(record)]
|
|
1517
|
+
if not stale:
|
|
1518
|
+
QMessageBox.information(self, "Re-run Stale Reports", "No stale reports were found.")
|
|
1519
|
+
return
|
|
1520
|
+
|
|
1521
|
+
def recompute_all(is_cancelled):
|
|
1522
|
+
outcomes = []
|
|
1523
|
+
for record in stale:
|
|
1524
|
+
if is_cancelled():
|
|
1525
|
+
break
|
|
1526
|
+
try:
|
|
1527
|
+
outcomes.append((record, self._recompute_record(record), ""))
|
|
1528
|
+
except Exception as exc:
|
|
1529
|
+
outcomes.append((record, None, str(exc)))
|
|
1530
|
+
return outcomes
|
|
1531
|
+
|
|
1532
|
+
from statstudio.ui.jobs import start_job
|
|
1533
|
+
|
|
1534
|
+
def completed(outcomes) -> None:
|
|
1535
|
+
updated = 0
|
|
1536
|
+
failures: list[tuple[str, str]] = []
|
|
1537
|
+
for record, result, failure in outcomes:
|
|
1538
|
+
if failure:
|
|
1539
|
+
failures.append((record.title, failure))
|
|
1540
|
+
continue
|
|
1541
|
+
if result is None:
|
|
1542
|
+
failures.append((record.title, "No headless replay is available for this analysis."))
|
|
1543
|
+
continue
|
|
1544
|
+
self._apply_recomputed_record(record, result)
|
|
1545
|
+
updated += 1
|
|
1546
|
+
self._mark_project_dirty()
|
|
1547
|
+
self._refresh_project_tree()
|
|
1548
|
+
message = f"Recomputed {updated} of {len(stale)} stale report(s) without opening dialogs."
|
|
1549
|
+
if failures:
|
|
1550
|
+
message += "\n\nCould not recompute:\n" + "\n".join(f"• {title}: {reason}" for title, reason in failures[:12])
|
|
1551
|
+
QMessageBox.information(self, "Re-run Stale Reports", message)
|
|
1552
|
+
self._log(message.splitlines()[0])
|
|
1553
|
+
|
|
1554
|
+
start_job(
|
|
1555
|
+
self,
|
|
1556
|
+
"Re-running Stale Reports",
|
|
1557
|
+
lambda token, progress: recompute_all(token.is_cancelled),
|
|
1558
|
+
on_result=completed,
|
|
1559
|
+
on_error=lambda message, details: QMessageBox.critical(self, "Re-run Stale Reports", f"{message}\n\n{details}".strip()),
|
|
1560
|
+
)
|
|
1561
|
+
|
|
1562
|
+
def _recompute_record(self, record: ReportRecord) -> AnalysisResult | None:
|
|
1563
|
+
table = self.project.find_table(record.source_table) if record.source_table else None
|
|
1564
|
+
if table is None:
|
|
1565
|
+
return None
|
|
1566
|
+
if record.kind == "plot_page":
|
|
1567
|
+
return self._rebuild_plot_page(table, record)
|
|
1568
|
+
import statstudio.stats as stats_package
|
|
1569
|
+
|
|
1570
|
+
class _Shim:
|
|
1571
|
+
def __init__(self, analysis_type: str, params: dict) -> None:
|
|
1572
|
+
self.analysis_type = analysis_type
|
|
1573
|
+
self.params = params
|
|
1574
|
+
|
|
1575
|
+
code = scripting.analysis_code(_Shim(record.kind, dict(record.params)), "table")
|
|
1576
|
+
if not code.startswith("result ="):
|
|
1577
|
+
return None
|
|
1578
|
+
namespace: dict = {
|
|
1579
|
+
"table": table,
|
|
1580
|
+
"stats": stats_package,
|
|
1581
|
+
"pd": pd,
|
|
1582
|
+
"np": np,
|
|
1583
|
+
}
|
|
1584
|
+
exec(code, namespace)
|
|
1585
|
+
result = namespace.get("result")
|
|
1586
|
+
return result if isinstance(result, AnalysisResult) else None
|
|
1587
|
+
|
|
1588
|
+
def _rebuild_plot_page(self, table: DataTable, record: ReportRecord) -> AnalysisResult | None:
|
|
1589
|
+
specs = (record.params or {}).get("specs") or []
|
|
1590
|
+
if not specs:
|
|
1591
|
+
return None
|
|
1592
|
+
result = AnalysisResult(
|
|
1593
|
+
title=record.title or f"Graph — {table.name}",
|
|
1594
|
+
analysis_type="plot_page",
|
|
1595
|
+
source_table=table.name,
|
|
1596
|
+
summary=f"Graphs of {table.name}.",
|
|
1597
|
+
params=dict(record.params or {}),
|
|
1598
|
+
)
|
|
1599
|
+
plot_df = table.plot_df()
|
|
1600
|
+
for item in specs:
|
|
1601
|
+
try:
|
|
1602
|
+
data = plot_df
|
|
1603
|
+
row_ids = item.get("row_ids")
|
|
1604
|
+
if row_ids:
|
|
1605
|
+
data = plot_df.loc[plot_df.index.isin(list(row_ids))]
|
|
1606
|
+
result.plots.append(
|
|
1607
|
+
PlotSpec(
|
|
1608
|
+
kind=item.get("kind", "histogram"),
|
|
1609
|
+
params=dict(item.get("params") or {}),
|
|
1610
|
+
title=item.get("title", ""),
|
|
1611
|
+
data=data,
|
|
1612
|
+
row_ids=list(data.index),
|
|
1613
|
+
include_in_report=bool(item.get("include_in_report", True)),
|
|
1614
|
+
row_styles={row_id: table.row_state(row_id) for row_id in data.index},
|
|
1615
|
+
)
|
|
1616
|
+
)
|
|
1617
|
+
except Exception:
|
|
1618
|
+
continue
|
|
1619
|
+
local_filter = (record.params or {}).get("local_filter", "") or ""
|
|
1620
|
+
if local_filter:
|
|
1621
|
+
for plot in result.plots:
|
|
1622
|
+
try:
|
|
1623
|
+
data, ids = filtered_plot_data(plot.data, plot.row_ids, local_filter)
|
|
1624
|
+
plot.data = data
|
|
1625
|
+
plot.row_ids = ids
|
|
1626
|
+
except Exception:
|
|
1627
|
+
continue
|
|
1628
|
+
return result
|
|
1629
|
+
|
|
1630
|
+
def _apply_recomputed_record(self, record: ReportRecord, result: AnalysisResult) -> None:
|
|
1631
|
+
table = self.project.find_table(record.source_table) if record.source_table else None
|
|
1632
|
+
record.title = result.title or record.title
|
|
1633
|
+
report_ui = (record.params or {}).get("report_ui")
|
|
1634
|
+
if isinstance(report_ui, dict):
|
|
1635
|
+
result.params["report_ui"] = dict(report_ui)
|
|
1636
|
+
stored_plot_params = (record.params or {}).get("plot_params") or []
|
|
1637
|
+
if result.analysis_type != "plot_page" and stored_plot_params:
|
|
1638
|
+
remaining = list(result.plots)
|
|
1639
|
+
ordered = []
|
|
1640
|
+
for item in stored_plot_params:
|
|
1641
|
+
if not isinstance(item, dict):
|
|
1642
|
+
continue
|
|
1643
|
+
key = (item.get("kind"), item.get("title"))
|
|
1644
|
+
match = next((plot for plot in remaining if (plot.kind, plot.title) == key), None)
|
|
1645
|
+
if match is None:
|
|
1646
|
+
match = next((plot for plot in remaining if plot.kind == item.get("kind")), None)
|
|
1647
|
+
if match is None:
|
|
1648
|
+
continue
|
|
1649
|
+
match.params = dict(item.get("params") or {})
|
|
1650
|
+
if item.get("title"):
|
|
1651
|
+
match.title = str(item["title"])
|
|
1652
|
+
match.include_in_report = bool(item.get("include_in_report", True))
|
|
1653
|
+
ordered.append(match)
|
|
1654
|
+
remaining.remove(match)
|
|
1655
|
+
if ordered:
|
|
1656
|
+
result.plots = ordered
|
|
1657
|
+
result.deferred_plots = remaining
|
|
1658
|
+
else:
|
|
1659
|
+
result.defer_extra_plots(
|
|
1660
|
+
self._primary_plot_kinds(result.analysis_type),
|
|
1661
|
+
self._profiler_keep_kinds(result.analysis_type),
|
|
1662
|
+
)
|
|
1663
|
+
elif result.analysis_type != "plot_page":
|
|
1664
|
+
result.defer_extra_plots(
|
|
1665
|
+
self._primary_plot_kinds(result.analysis_type),
|
|
1666
|
+
self._profiler_keep_kinds(result.analysis_type),
|
|
1667
|
+
)
|
|
1668
|
+
if result.analysis_type != "plot_page":
|
|
1669
|
+
record.html = result.to_html(include_plots=True)
|
|
1670
|
+
record.params = dict(result.params)
|
|
1671
|
+
if stored_plot_params:
|
|
1672
|
+
record.params["plot_params"] = stored_plot_params
|
|
1673
|
+
record.code = scripting.analysis_code(result, "table") if table is not None else ""
|
|
1674
|
+
else:
|
|
1675
|
+
record.html = ""
|
|
1676
|
+
local_filter = (record.params or {}).get("local_filter", "") or ""
|
|
1677
|
+
record.params = {
|
|
1678
|
+
"plots": len(result.plots),
|
|
1679
|
+
"local_filter": local_filter,
|
|
1680
|
+
"specs": [
|
|
1681
|
+
{
|
|
1682
|
+
"kind": plot.kind,
|
|
1683
|
+
"params": dict(plot.params),
|
|
1684
|
+
"title": plot.title,
|
|
1685
|
+
"row_ids": list(plot.row_ids) if plot.row_ids is not None else None,
|
|
1686
|
+
"include_in_report": plot.include_in_report,
|
|
1687
|
+
}
|
|
1688
|
+
for plot in result.plots
|
|
1689
|
+
],
|
|
1690
|
+
}
|
|
1691
|
+
self._store_report_ui(result, record.params)
|
|
1692
|
+
record.data_hash = self._table_hash(table) if table is not None else record.data_hash
|
|
1693
|
+
|
|
1694
|
+
def _add_document(self, widget: QWidget, title: str, table: DataTable | None = None) -> QMdiSubWindow:
|
|
1695
|
+
sub = DocumentSubWindow()
|
|
1696
|
+
sub.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
|
|
1697
|
+
sub.setWindowFlags(
|
|
1698
|
+
sub.windowFlags()
|
|
1699
|
+
& ~Qt.WindowType.WindowMinMaxButtonsHint
|
|
1700
|
+
& ~Qt.WindowType.WindowCloseButtonHint
|
|
1701
|
+
| Qt.WindowType.FramelessWindowHint
|
|
1702
|
+
)
|
|
1703
|
+
sub.setWidget(widget)
|
|
1704
|
+
sub.setWindowTitle(title)
|
|
1705
|
+
viewport = self.mdi.viewport().size()
|
|
1706
|
+
width = min(940, max(480, viewport.width() - 36))
|
|
1707
|
+
height = min(620, max(360, viewport.height() - 36))
|
|
1708
|
+
sub.resize(width, height)
|
|
1709
|
+
self._connect_window_controls(widget)
|
|
1710
|
+
drag_filter = _DocumentDragFilter(sub)
|
|
1711
|
+
for target in (
|
|
1712
|
+
getattr(widget, "header", None),
|
|
1713
|
+
getattr(widget, "title_label", None),
|
|
1714
|
+
getattr(widget, "meta_label", None),
|
|
1715
|
+
):
|
|
1716
|
+
if target is not None:
|
|
1717
|
+
target.installEventFilter(drag_filter)
|
|
1718
|
+
grip = _DocumentResizeGrip(widget, sub)
|
|
1719
|
+
self._document_chrome_refs.extend([drag_filter, grip])
|
|
1720
|
+
self._windows[widget] = sub
|
|
1721
|
+
if table is not None:
|
|
1722
|
+
self._table_windows[table] = sub
|
|
1723
|
+
self.mdi.addSubWindow(sub)
|
|
1724
|
+
sub.state_changed.connect(lambda s=sub: self._sync_window_controls(s))
|
|
1725
|
+
sub.show()
|
|
1726
|
+
self._show_workspace()
|
|
1727
|
+
self.mdi.setActiveSubWindow(sub)
|
|
1728
|
+
self._sync_window_controls(sub)
|
|
1729
|
+
sub.destroyed.connect(lambda *_, w=widget, t=table: self._cleanup_document(w, t))
|
|
1730
|
+
QTimer.singleShot(0, lambda s=sub: self._fit_subwindow(s))
|
|
1731
|
+
self._update_status_context()
|
|
1732
|
+
return sub
|
|
1733
|
+
|
|
1734
|
+
def _fit_subwindow(self, sub: QMdiSubWindow) -> None:
|
|
1735
|
+
try:
|
|
1736
|
+
from shiboken6 import isValid
|
|
1737
|
+
|
|
1738
|
+
if not isValid(sub) or sub.windowState() & Qt.WindowState.WindowMaximized:
|
|
1739
|
+
return
|
|
1740
|
+
except Exception:
|
|
1741
|
+
return
|
|
1742
|
+
viewport = self.mdi.viewport().size()
|
|
1743
|
+
width = min(940, max(480, viewport.width() - 36))
|
|
1744
|
+
height = min(620, max(360, viewport.height() - 36))
|
|
1745
|
+
sub.resize(width, height)
|
|
1746
|
+
area = self.mdi.viewport().rect()
|
|
1747
|
+
sub.move(
|
|
1748
|
+
max(0, (area.width() - width) // 2),
|
|
1749
|
+
max(0, (area.height() - height) // 2),
|
|
1750
|
+
)
|
|
1751
|
+
|
|
1752
|
+
def _connect_window_controls(self, widget: QWidget) -> None:
|
|
1753
|
+
minimize = getattr(widget, "minimize_requested", None)
|
|
1754
|
+
maximize = getattr(widget, "maximize_requested", None)
|
|
1755
|
+
delete = getattr(widget, "delete_requested", None)
|
|
1756
|
+
if minimize is not None:
|
|
1757
|
+
minimize.connect(lambda w=widget: self._close_document(w))
|
|
1758
|
+
if maximize is not None:
|
|
1759
|
+
maximize.connect(lambda w=widget: self._toggle_maximize_document(w))
|
|
1760
|
+
if delete is not None:
|
|
1761
|
+
delete.connect(lambda w=widget: self._delete_document(w))
|
|
1762
|
+
|
|
1763
|
+
def _toggle_maximize_document(self, widget: QWidget) -> None:
|
|
1764
|
+
sub = self._windows.get(widget)
|
|
1765
|
+
if sub is None or not _qt_alive(sub):
|
|
1766
|
+
return
|
|
1767
|
+
try:
|
|
1768
|
+
if sub.windowState() & Qt.WindowState.WindowMaximized:
|
|
1769
|
+
sub.showNormal()
|
|
1770
|
+
else:
|
|
1771
|
+
sub.showMaximized()
|
|
1772
|
+
except RuntimeError:
|
|
1773
|
+
return
|
|
1774
|
+
self._sync_window_controls(sub)
|
|
1775
|
+
|
|
1776
|
+
def _sync_window_controls(self, sub: QMdiSubWindow) -> None:
|
|
1777
|
+
if not _qt_alive(sub):
|
|
1778
|
+
return
|
|
1779
|
+
try:
|
|
1780
|
+
widget = sub.widget()
|
|
1781
|
+
controls = getattr(widget, "window_controls", None)
|
|
1782
|
+
if controls is not None:
|
|
1783
|
+
controls.set_maximized(bool(sub.windowState() & Qt.WindowState.WindowMaximized))
|
|
1784
|
+
except RuntimeError:
|
|
1785
|
+
return
|
|
1786
|
+
|
|
1787
|
+
def _cleanup_document(self, widget: QWidget | None, table: DataTable | None = None) -> None:
|
|
1788
|
+
if widget is None:
|
|
1789
|
+
return
|
|
1790
|
+
self._windows.pop(widget, None)
|
|
1791
|
+
if table is not None:
|
|
1792
|
+
self.table_views.pop(table, None)
|
|
1793
|
+
self._table_windows.pop(table, None)
|
|
1794
|
+
document = self._table_documents.pop(table, None)
|
|
1795
|
+
try:
|
|
1796
|
+
if document is not None and _qt_alive(document) and self._last_table_view is document.view:
|
|
1797
|
+
self._last_table_view = None
|
|
1798
|
+
except RuntimeError:
|
|
1799
|
+
self._last_table_view = None
|
|
1800
|
+
else:
|
|
1801
|
+
try:
|
|
1802
|
+
if isinstance(widget, TableDocument) and self._last_table_view is widget.view:
|
|
1803
|
+
self._last_table_view = None
|
|
1804
|
+
except (RuntimeError, SystemError):
|
|
1805
|
+
pass
|
|
1806
|
+
self._plot_records.pop(widget, None)
|
|
1807
|
+
try:
|
|
1808
|
+
if widget in self.report_views:
|
|
1809
|
+
self.report_views.remove(widget)
|
|
1810
|
+
except RuntimeError:
|
|
1811
|
+
pass
|
|
1812
|
+
self._document_chrome_refs = [
|
|
1813
|
+
ref for ref in self._document_chrome_refs if _qt_alive(ref)
|
|
1814
|
+
]
|
|
1815
|
+
try:
|
|
1816
|
+
from shiboken6 import isValid
|
|
1817
|
+
|
|
1818
|
+
if (
|
|
1819
|
+
hasattr(self, "central_stack")
|
|
1820
|
+
and isValid(self.central_stack)
|
|
1821
|
+
and self.central_stack.currentWidget() is self.workspace
|
|
1822
|
+
and not self.mdi.subWindowList()
|
|
1823
|
+
):
|
|
1824
|
+
self._show_home()
|
|
1825
|
+
except Exception:
|
|
1826
|
+
pass
|
|
1827
|
+
|
|
1828
|
+
def _activate_document(self, widget: QWidget) -> None:
|
|
1829
|
+
sub = self._windows.get(widget)
|
|
1830
|
+
if sub is None or not _qt_alive(sub):
|
|
1831
|
+
return
|
|
1832
|
+
self.mdi.setActiveSubWindow(sub)
|
|
1833
|
+
sub.raise_()
|
|
1834
|
+
|
|
1835
|
+
def _close_document(self, widget: QWidget | None = None) -> None:
|
|
1836
|
+
widget = widget or self._active_document()
|
|
1837
|
+
if widget is None:
|
|
1838
|
+
return
|
|
1839
|
+
table = None
|
|
1840
|
+
try:
|
|
1841
|
+
if isinstance(widget, TableDocument):
|
|
1842
|
+
for candidate, document in list(self._table_documents.items()):
|
|
1843
|
+
if document is widget:
|
|
1844
|
+
table = candidate
|
|
1845
|
+
break
|
|
1846
|
+
except (RuntimeError, SystemError):
|
|
1847
|
+
return
|
|
1848
|
+
sub = self._windows.get(widget)
|
|
1849
|
+
if sub is not None and _qt_alive(sub):
|
|
1850
|
+
sub.close()
|
|
1851
|
+
self._cleanup_document(widget, table)
|
|
1852
|
+
|
|
1853
|
+
def _close_current_document(self) -> None:
|
|
1854
|
+
self._close_document(self._active_document())
|
|
1855
|
+
|
|
1856
|
+
def _close_all_views(self) -> None:
|
|
1857
|
+
for widget in list(self._windows):
|
|
1858
|
+
self._close_document(widget)
|
|
1859
|
+
|
|
1860
|
+
def _close_all_tabs(self) -> None:
|
|
1861
|
+
for sub in list(self.mdi.subWindowList()):
|
|
1862
|
+
sub.close()
|
|
1863
|
+
self.table_views.clear()
|
|
1864
|
+
self.report_views.clear()
|
|
1865
|
+
self._windows.clear()
|
|
1866
|
+
self._table_windows.clear()
|
|
1867
|
+
self._table_documents.clear()
|
|
1868
|
+
self._plot_records.clear()
|
|
1869
|
+
self._last_table_view = None
|
|
1870
|
+
|
|
1871
|
+
def _on_subwindow_activated(self, sub: QMdiSubWindow | None) -> None:
|
|
1872
|
+
if sub is not None:
|
|
1873
|
+
widget = sub.widget()
|
|
1874
|
+
if isinstance(widget, TableDocument):
|
|
1875
|
+
self._last_table_view = widget.view
|
|
1876
|
+
elif isinstance(widget, DataTableView):
|
|
1877
|
+
self._last_table_view = widget
|
|
1878
|
+
self._show_workspace()
|
|
1879
|
+
self._update_undo_actions()
|
|
1880
|
+
self._update_status_context()
|
|
1881
|
+
|
|
1882
|
+
def _active_document(self) -> QWidget | None:
|
|
1883
|
+
sub = self.mdi.activeSubWindow()
|
|
1884
|
+
return sub.widget() if sub is not None else None
|
|
1885
|
+
|
|
1886
|
+
def _active_table_view(self) -> DataTableView | None:
|
|
1887
|
+
widget = self._active_document()
|
|
1888
|
+
if isinstance(widget, TableDocument):
|
|
1889
|
+
self._last_table_view = widget.view
|
|
1890
|
+
return widget.view
|
|
1891
|
+
if isinstance(widget, DataTableView):
|
|
1892
|
+
self._last_table_view = widget
|
|
1893
|
+
return widget
|
|
1894
|
+
table = getattr(widget, "table", None)
|
|
1895
|
+
if isinstance(table, DataTable):
|
|
1896
|
+
view = self.table_views.get(table)
|
|
1897
|
+
if view is not None:
|
|
1898
|
+
self._last_table_view = view
|
|
1899
|
+
return view
|
|
1900
|
+
return self._last_table_view
|
|
1901
|
+
|
|
1902
|
+
def open_table_view(self, table: DataTable, *, refresh_tree: bool = True) -> DataTableView:
|
|
1903
|
+
if table in self.table_views:
|
|
1904
|
+
view = self.table_views[table]
|
|
1905
|
+
self._activate_document(self._table_documents[table])
|
|
1906
|
+
return view
|
|
1907
|
+
view = DataTableView(table)
|
|
1908
|
+
view.column_properties_requested.connect(lambda column, t=table: self._column_properties(t, column))
|
|
1909
|
+
view.rename_column_requested.connect(lambda column, t=table: self._rename_column_for(t, column))
|
|
1910
|
+
view.delete_column_requested.connect(lambda column, t=table: self._delete_column_for(t, column))
|
|
1911
|
+
view.hide_column_requested.connect(lambda column, t=table: self._hide_column_for(t, column))
|
|
1912
|
+
view.exclude_rows_requested.connect(lambda rows, t=table: self._set_excluded(t, rows, True))
|
|
1913
|
+
view.include_rows_requested.connect(lambda rows, t=table: self._set_excluded(t, rows, False))
|
|
1914
|
+
view.clear_exclusions_requested.connect(lambda t=table: self._clear_exclusions_for(t))
|
|
1915
|
+
view.hide_rows_requested.connect(
|
|
1916
|
+
lambda rows, t=table: self._mutate_table(
|
|
1917
|
+
t,
|
|
1918
|
+
"Hide rows",
|
|
1919
|
+
lambda: t.set_hidden(rows, True),
|
|
1920
|
+
operation="hide_rows",
|
|
1921
|
+
journal_params={"rows": list(rows)},
|
|
1922
|
+
)
|
|
1923
|
+
)
|
|
1924
|
+
view.unhide_rows_requested.connect(
|
|
1925
|
+
lambda rows, t=table: self._mutate_table(
|
|
1926
|
+
t,
|
|
1927
|
+
"Unhide rows",
|
|
1928
|
+
lambda: t.set_hidden(rows, False),
|
|
1929
|
+
operation="unhide_rows",
|
|
1930
|
+
journal_params={"rows": list(rows)},
|
|
1931
|
+
)
|
|
1932
|
+
)
|
|
1933
|
+
view.label_rows_requested.connect(lambda rows, t=table: self._label_rows(t, rows))
|
|
1934
|
+
view.color_rows_requested.connect(lambda rows, value, t=table: self._mutate_table(t, "Color rows", lambda: t.set_colors(rows, value)))
|
|
1935
|
+
view.marker_rows_requested.connect(lambda rows, value, t=table: self._mutate_table(t, "Marker rows", lambda: t.set_markers(rows, value)))
|
|
1936
|
+
view.clear_row_states_requested.connect(lambda t=table: self._mutate_table(t, "Clear row states", t.clear_row_states))
|
|
1937
|
+
view.duplicate_rows_requested.connect(lambda rows, t=table: self._duplicate_rows(t, rows))
|
|
1938
|
+
view.delete_rows_requested.connect(lambda rows, t=table: self._delete_rows_for(t, rows))
|
|
1939
|
+
view.create_subset_requested.connect(self._create_subset_from_selection)
|
|
1940
|
+
view.selection_changed.connect(lambda rows, t=table: self._remember_table_selection(t, rows))
|
|
1941
|
+
view.selection_changed.connect(lambda rows, t=table: self._update_selection_status(t, rows))
|
|
1942
|
+
view.move_column_requested.connect(lambda column, offset, t=table: self._move_column(t, column, offset))
|
|
1943
|
+
view.unhide_columns_requested.connect(lambda t=table: self._mutate_table(t, "Unhide columns", lambda: unhide_all_columns(t)))
|
|
1944
|
+
view.find_replace_requested.connect(lambda t=table: self._find_replace_for(t))
|
|
1945
|
+
view.sort_changed.connect(lambda old, new, t=table: self._record_sort(t, old, new))
|
|
1946
|
+
view.cell_edited.connect(lambda row_id, column, old, new, t=table: self._record_cell_edit(t, row_id, column, old, new))
|
|
1947
|
+
document = TableDocument(table, view)
|
|
1948
|
+
document.rename_requested.connect(lambda name, t=table: self._rename_table_to(t, name))
|
|
1949
|
+
document.filter_requested.connect(lambda expression, t=table: self._apply_filter_for(t, expression))
|
|
1950
|
+
document.filter_cleared.connect(lambda t=table: self._clear_filter_for(t))
|
|
1951
|
+
document.formula_requested.connect(lambda column, expression, t=table: self._apply_formula_for(t, column, expression))
|
|
1952
|
+
self.table_views[table] = view
|
|
1953
|
+
self._table_documents[table] = document
|
|
1954
|
+
self._last_table_view = view
|
|
1955
|
+
self._add_document(document, table.name, table=table)
|
|
1956
|
+
if refresh_tree:
|
|
1957
|
+
self._refresh_project_tree()
|
|
1958
|
+
return view
|
|
1959
|
+
|
|
1960
|
+
def _close_tab(self, index: int) -> None:
|
|
1961
|
+
self._close_current_document()
|
|
1962
|
+
|
|
1963
|
+
def _close_current_tab(self) -> None:
|
|
1964
|
+
self._close_current_document()
|
|
1965
|
+
|
|
1966
|
+
def _on_tab_changed(self, index: int) -> None:
|
|
1967
|
+
self._update_undo_actions()
|
|
1968
|
+
|
|
1969
|
+
def _current_table(self) -> DataTable | None:
|
|
1970
|
+
view = self._active_table_view()
|
|
1971
|
+
return view.table if view is not None else None
|
|
1972
|
+
|
|
1973
|
+
def _require_table(self) -> DataTable | None:
|
|
1974
|
+
table = self._current_table()
|
|
1975
|
+
if table is None:
|
|
1976
|
+
QMessageBox.information(self, "StatStudio", "Select or open a data table first.")
|
|
1977
|
+
return table
|
|
1978
|
+
|
|
1979
|
+
|
|
1980
|
+
# ---------------------------------------------------------------- files
|
|
1981
|
+
def _import_file(self) -> None:
|
|
1982
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1983
|
+
self,
|
|
1984
|
+
"Import Data",
|
|
1985
|
+
"",
|
|
1986
|
+
"Data files (*.csv *.tsv *.txt *.xlsx *.xlsm *.xls *.parquet *.pq *.json *.jsonl *.dta *.sav *.sas7bdat *.xpt);;All files (*)",
|
|
1987
|
+
)
|
|
1988
|
+
if not path:
|
|
1989
|
+
return
|
|
1990
|
+
try:
|
|
1991
|
+
sheet: str | int = 0
|
|
1992
|
+
options = None
|
|
1993
|
+
if path.lower().endswith((".csv", ".tsv", ".txt")):
|
|
1994
|
+
options_dialog = CSVOptionsDialog(path, self)
|
|
1995
|
+
if options_dialog.exec() != QDialog.DialogCode.Accepted:
|
|
1996
|
+
return
|
|
1997
|
+
options = options_dialog.result
|
|
1998
|
+
if path.lower().endswith((".xlsx", ".xlsm", ".xls")):
|
|
1999
|
+
sheets = excel_sheet_names(path)
|
|
2000
|
+
if len(sheets) > 1:
|
|
2001
|
+
choice, ok = QInputDialog.getItem(self, "Select sheet", "Sheet", sheets, 0, False)
|
|
2002
|
+
if not ok:
|
|
2003
|
+
return
|
|
2004
|
+
sheet = choice
|
|
2005
|
+
table = read_file(path, options=options, sheet_name=sheet)
|
|
2006
|
+
except Exception as exc:
|
|
2007
|
+
QMessageBox.critical(self, "Import failed", str(exc))
|
|
2008
|
+
return
|
|
2009
|
+
preview = ImportPreviewDialog(table, path, self)
|
|
2010
|
+
if preview.exec() != QDialog.DialogCode.Accepted or preview.result is None:
|
|
2011
|
+
return
|
|
2012
|
+
table = preview.result
|
|
2013
|
+
option_params = dict(options.__dict__) if options is not None else None
|
|
2014
|
+
self._add_table(
|
|
2015
|
+
table,
|
|
2016
|
+
operation="import_file",
|
|
2017
|
+
journal_params={"path": path, "sheet_name": sheet, "options": option_params},
|
|
2018
|
+
journal_title=f"Import {Path(path).name}",
|
|
2019
|
+
)
|
|
2020
|
+
self._log(f"Imported {len(table)} rows from {Path(path).name}")
|
|
2021
|
+
|
|
2022
|
+
def _import_clipboard(self) -> None:
|
|
2023
|
+
text = QApplication.clipboard().text()
|
|
2024
|
+
try:
|
|
2025
|
+
table = read_clipboard()
|
|
2026
|
+
except Exception as exc:
|
|
2027
|
+
QMessageBox.critical(self, "Clipboard import failed", str(exc))
|
|
2028
|
+
return
|
|
2029
|
+
self._add_table(table, operation="clipboard", journal_params={"text": text}, journal_title="Import clipboard")
|
|
2030
|
+
self._log("Imported clipboard data")
|
|
2031
|
+
|
|
2032
|
+
def _import_odbc(self) -> None:
|
|
2033
|
+
dialog = ODBCDialog(self.project, self)
|
|
2034
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2035
|
+
self._add_table(
|
|
2036
|
+
dialog.result,
|
|
2037
|
+
operation="odbc",
|
|
2038
|
+
journal_params={"profile": dialog.import_profile or {}, "query": dialog.import_query, "name": dialog.result.name},
|
|
2039
|
+
journal_title="Import ODBC",
|
|
2040
|
+
)
|
|
2041
|
+
self._log(f"Imported {len(dialog.result)} rows from ODBC")
|
|
2042
|
+
|
|
2043
|
+
def _open_table_file(self) -> None:
|
|
2044
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
2045
|
+
self,
|
|
2046
|
+
"Open Table",
|
|
2047
|
+
"",
|
|
2048
|
+
f"StatStudio table (*{TABLE_SUFFIX} *.stattable)",
|
|
2049
|
+
)
|
|
2050
|
+
if not path:
|
|
2051
|
+
return
|
|
2052
|
+
try:
|
|
2053
|
+
table = load_table(path)
|
|
2054
|
+
except Exception as exc:
|
|
2055
|
+
QMessageBox.critical(self, "Open table failed", str(exc))
|
|
2056
|
+
return
|
|
2057
|
+
table.name = self.project.unique_name(table.name)
|
|
2058
|
+
self._add_table(table, operation="load_table", journal_params={"path": path}, journal_title=f"Open table {Path(path).name}")
|
|
2059
|
+
self._log(f"Opened table {table.name} from {path}")
|
|
2060
|
+
|
|
2061
|
+
def _save_table_as(self) -> None:
|
|
2062
|
+
table = self._require_table()
|
|
2063
|
+
if table is None:
|
|
2064
|
+
return
|
|
2065
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
2066
|
+
self,
|
|
2067
|
+
"Save Table As",
|
|
2068
|
+
f"{table.name}{TABLE_SUFFIX}",
|
|
2069
|
+
f"StatStudio table (*{TABLE_SUFFIX})",
|
|
2070
|
+
)
|
|
2071
|
+
if not path:
|
|
2072
|
+
return
|
|
2073
|
+
try:
|
|
2074
|
+
saved = save_table(table, path)
|
|
2075
|
+
except Exception as exc:
|
|
2076
|
+
QMessageBox.critical(self, "Save table failed", str(exc))
|
|
2077
|
+
return
|
|
2078
|
+
self._log(f"Saved table {table.name} to {saved}")
|
|
2079
|
+
|
|
2080
|
+
def _show_journal(self) -> None:
|
|
2081
|
+
from statstudio.ui.dialogs.script_dialogs import JournalDialog
|
|
2082
|
+
|
|
2083
|
+
JournalDialog(self.project, self).exec()
|
|
2084
|
+
|
|
2085
|
+
def _show_table_scripts(self) -> None:
|
|
2086
|
+
table = self._require_table()
|
|
2087
|
+
if table is None:
|
|
2088
|
+
return
|
|
2089
|
+
from statstudio.ui.dialogs.script_dialogs import TableScriptsDialog
|
|
2090
|
+
|
|
2091
|
+
TableScriptsDialog(table, self.project, self.console, self).exec()
|
|
2092
|
+
self._mark_project_dirty()
|
|
2093
|
+
|
|
2094
|
+
def _export_table(self) -> None:
|
|
2095
|
+
table = self._require_table()
|
|
2096
|
+
if table is None:
|
|
2097
|
+
return
|
|
2098
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
2099
|
+
self,
|
|
2100
|
+
"Export Table",
|
|
2101
|
+
f"{table.name}.csv",
|
|
2102
|
+
"CSV (*.csv);;Tab-delimited (*.tsv *.txt);;Excel (*.xlsx);;Parquet (*.parquet);;JSON (*.json)",
|
|
2103
|
+
)
|
|
2104
|
+
if not path:
|
|
2105
|
+
return
|
|
2106
|
+
try:
|
|
2107
|
+
export_table(table, path)
|
|
2108
|
+
except Exception as exc:
|
|
2109
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
2110
|
+
return
|
|
2111
|
+
self._log(f"Exported {table.name} to {path}")
|
|
2112
|
+
|
|
2113
|
+
def _new_data_table(self) -> None:
|
|
2114
|
+
dialog = NewTableDialog(self)
|
|
2115
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or dialog.result is None:
|
|
2116
|
+
return
|
|
2117
|
+
self._add_table(dialog.result, operation="new_table", journal_title=f"Create table {dialog.result.name}")
|
|
2118
|
+
self._log(f"Created table {dialog.result.name}")
|
|
2119
|
+
|
|
2120
|
+
def _add_rows(self) -> None:
|
|
2121
|
+
table = self._require_table()
|
|
2122
|
+
if table is None:
|
|
2123
|
+
return
|
|
2124
|
+
count, ok = QInputDialog.getInt(self, "Add Rows", "Number of blank rows", 10, 1, 100000)
|
|
2125
|
+
if not ok:
|
|
2126
|
+
return
|
|
2127
|
+
self._mutate_table(table, f"Add {count} rows", lambda: add_rows(table, count), operation="add_rows", journal_params={"count": count})
|
|
2128
|
+
|
|
2129
|
+
def _confirm_discard_changes(self, action: str) -> bool:
|
|
2130
|
+
if not self._has_unsaved_changes():
|
|
2131
|
+
return True
|
|
2132
|
+
choice = QMessageBox.question(
|
|
2133
|
+
self,
|
|
2134
|
+
"Unsaved Changes",
|
|
2135
|
+
f"Save changes to {self.project.name!r} before {action}?",
|
|
2136
|
+
QMessageBox.StandardButton.Save
|
|
2137
|
+
| QMessageBox.StandardButton.Discard
|
|
2138
|
+
| QMessageBox.StandardButton.Cancel,
|
|
2139
|
+
QMessageBox.StandardButton.Save,
|
|
2140
|
+
)
|
|
2141
|
+
if choice == QMessageBox.StandardButton.Save:
|
|
2142
|
+
return self._save_project()
|
|
2143
|
+
return choice == QMessageBox.StandardButton.Discard
|
|
2144
|
+
|
|
2145
|
+
def _mark_project_clean(self) -> None:
|
|
2146
|
+
self._project_dirty = False
|
|
2147
|
+
for table in self.project.tables:
|
|
2148
|
+
table.modified = False
|
|
2149
|
+
self._update_title()
|
|
2150
|
+
|
|
2151
|
+
def _new_project(self) -> None:
|
|
2152
|
+
if not self._confirm_discard_changes("creating a new project"):
|
|
2153
|
+
return
|
|
2154
|
+
self._load_project_into_ui(Project())
|
|
2155
|
+
self.command_stack.clear()
|
|
2156
|
+
self._update_undo_actions()
|
|
2157
|
+
|
|
2158
|
+
def _open_project(self) -> None:
|
|
2159
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
2160
|
+
self,
|
|
2161
|
+
"Open Project",
|
|
2162
|
+
"",
|
|
2163
|
+
f"StatStudio project (*{PROJECT_SUFFIX})",
|
|
2164
|
+
)
|
|
2165
|
+
if path:
|
|
2166
|
+
self._open_project_path(path)
|
|
2167
|
+
|
|
2168
|
+
def _open_recent_project(self, path: str) -> None:
|
|
2169
|
+
if not Path(path).exists():
|
|
2170
|
+
choice = QMessageBox.question(
|
|
2171
|
+
self,
|
|
2172
|
+
"Recent Project",
|
|
2173
|
+
f"{path}\n\nThis project file is missing. Remove it from the recent list?",
|
|
2174
|
+
)
|
|
2175
|
+
if choice == QMessageBox.StandardButton.Yes:
|
|
2176
|
+
recent.forget_project(path)
|
|
2177
|
+
self._refresh_home()
|
|
2178
|
+
return
|
|
2179
|
+
self._open_project_path(path)
|
|
2180
|
+
|
|
2181
|
+
def _open_project_path(self, path: str) -> None:
|
|
2182
|
+
if not self._confirm_discard_changes("opening another project"):
|
|
2183
|
+
return
|
|
2184
|
+
from statstudio.ui.jobs import start_job
|
|
2185
|
+
|
|
2186
|
+
def opened(project: Project) -> None:
|
|
2187
|
+
self._load_project_into_ui(project, live_reports=False)
|
|
2188
|
+
self.command_stack.clear()
|
|
2189
|
+
self._update_undo_actions()
|
|
2190
|
+
recent.remember_project(path)
|
|
2191
|
+
self._refresh_home()
|
|
2192
|
+
self._show_workspace()
|
|
2193
|
+
|
|
2194
|
+
def failed(message: str, details: str) -> None:
|
|
2195
|
+
QMessageBox.critical(self, "Open failed", f"{message}\n\n{details}".strip())
|
|
2196
|
+
|
|
2197
|
+
start_job(
|
|
2198
|
+
self,
|
|
2199
|
+
"Opening Project",
|
|
2200
|
+
lambda token, progress: Project.load(path),
|
|
2201
|
+
on_result=opened,
|
|
2202
|
+
on_error=failed,
|
|
2203
|
+
)
|
|
2204
|
+
|
|
2205
|
+
def _save_project(self) -> bool:
|
|
2206
|
+
if self.project.path is None:
|
|
2207
|
+
return self._save_project_as()
|
|
2208
|
+
try:
|
|
2209
|
+
self.project.save(self.project.path)
|
|
2210
|
+
except Exception as exc:
|
|
2211
|
+
QMessageBox.critical(self, "Save failed", str(exc))
|
|
2212
|
+
return False
|
|
2213
|
+
self._mark_project_clean()
|
|
2214
|
+
recent.remember_project(self.project.path)
|
|
2215
|
+
self._refresh_home()
|
|
2216
|
+
self._log(f"Saved project to {self.project.path}")
|
|
2217
|
+
return True
|
|
2218
|
+
|
|
2219
|
+
def _save_project_as(self) -> bool:
|
|
2220
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
2221
|
+
self,
|
|
2222
|
+
"Save Project As",
|
|
2223
|
+
f"{self.project.name}{PROJECT_SUFFIX}",
|
|
2224
|
+
f"StatStudio project (*{PROJECT_SUFFIX})",
|
|
2225
|
+
)
|
|
2226
|
+
if not path:
|
|
2227
|
+
return False
|
|
2228
|
+
try:
|
|
2229
|
+
self.project.save(path)
|
|
2230
|
+
except Exception as exc:
|
|
2231
|
+
QMessageBox.critical(self, "Save failed", str(exc))
|
|
2232
|
+
return False
|
|
2233
|
+
self._mark_project_clean()
|
|
2234
|
+
recent.remember_project(path)
|
|
2235
|
+
self._refresh_home()
|
|
2236
|
+
self._log(f"Saved project to {path}")
|
|
2237
|
+
return True
|
|
2238
|
+
|
|
2239
|
+
# --------------------------------------------------------------- tables
|
|
2240
|
+
def _table_script_name(self, table: DataTable, title: str) -> str:
|
|
2241
|
+
existing = {script.name for script in table.scripts}
|
|
2242
|
+
name = title.strip() or "Recorded script"
|
|
2243
|
+
if name not in existing:
|
|
2244
|
+
return name
|
|
2245
|
+
index = 2
|
|
2246
|
+
while f"{name} ({index})" in existing:
|
|
2247
|
+
index += 1
|
|
2248
|
+
return f"{name} ({index})"
|
|
2249
|
+
|
|
2250
|
+
def _record_entry(
|
|
2251
|
+
self,
|
|
2252
|
+
*,
|
|
2253
|
+
kind: str,
|
|
2254
|
+
operation: str,
|
|
2255
|
+
title: str,
|
|
2256
|
+
source_tables,
|
|
2257
|
+
result_table: str,
|
|
2258
|
+
params: dict | None,
|
|
2259
|
+
code: str,
|
|
2260
|
+
table_code: str | None = None,
|
|
2261
|
+
link_table: DataTable | None = None,
|
|
2262
|
+
analysis_type: str = "",
|
|
2263
|
+
role: str = "source",
|
|
2264
|
+
) -> JournalEntry:
|
|
2265
|
+
table = link_table
|
|
2266
|
+
data_hash = self._table_hash(table) if table is not None else ""
|
|
2267
|
+
entry = JournalEntry(
|
|
2268
|
+
kind=kind,
|
|
2269
|
+
operation=operation,
|
|
2270
|
+
title=title,
|
|
2271
|
+
source_tables=[name for name in source_tables if name],
|
|
2272
|
+
result_table=result_table,
|
|
2273
|
+
params=dict(params or {}),
|
|
2274
|
+
code=code,
|
|
2275
|
+
data_hashes={name: self._table_hash(t) for name, t in ((item.name, item) for item in self.project.tables) if name in set(source_tables)},
|
|
2276
|
+
)
|
|
2277
|
+
self.project.add_journal(entry)
|
|
2278
|
+
self._mark_project_dirty()
|
|
2279
|
+
if table is not None and code.strip() and not code.lstrip().startswith("# No replay"):
|
|
2280
|
+
table.scripts.append(
|
|
2281
|
+
TableScript(
|
|
2282
|
+
name=self._table_script_name(table, title),
|
|
2283
|
+
code=table_code if table_code is not None else code,
|
|
2284
|
+
analysis_type=analysis_type,
|
|
2285
|
+
params=dict(params or {}),
|
|
2286
|
+
journal_id=entry.id,
|
|
2287
|
+
data_hash=data_hash,
|
|
2288
|
+
role=role,
|
|
2289
|
+
)
|
|
2290
|
+
)
|
|
2291
|
+
self._refresh_project_tree()
|
|
2292
|
+
return entry
|
|
2293
|
+
|
|
2294
|
+
def _record_table_operation(
|
|
2295
|
+
self,
|
|
2296
|
+
*,
|
|
2297
|
+
operation: str,
|
|
2298
|
+
title: str,
|
|
2299
|
+
source_tables,
|
|
2300
|
+
result_table: str,
|
|
2301
|
+
params: dict,
|
|
2302
|
+
link_table: DataTable | None,
|
|
2303
|
+
role: str = "result",
|
|
2304
|
+
) -> JournalEntry:
|
|
2305
|
+
code = scripting.operation_code(operation, params, source_tables, result_table)
|
|
2306
|
+
table_code = None
|
|
2307
|
+
if (
|
|
2308
|
+
link_table is not None
|
|
2309
|
+
and operation in scripting.INPLACE_OPERATIONS
|
|
2310
|
+
and result_table == link_table.name
|
|
2311
|
+
):
|
|
2312
|
+
table_code = scripting.operation_code(
|
|
2313
|
+
operation,
|
|
2314
|
+
params,
|
|
2315
|
+
source_tables,
|
|
2316
|
+
result_table,
|
|
2317
|
+
source_expression="table",
|
|
2318
|
+
target_expression="table",
|
|
2319
|
+
)
|
|
2320
|
+
return self._record_entry(
|
|
2321
|
+
kind="data_prep",
|
|
2322
|
+
operation=operation,
|
|
2323
|
+
title=title,
|
|
2324
|
+
source_tables=source_tables,
|
|
2325
|
+
result_table=result_table,
|
|
2326
|
+
params=params,
|
|
2327
|
+
code=code,
|
|
2328
|
+
table_code=table_code,
|
|
2329
|
+
link_table=link_table,
|
|
2330
|
+
role=role,
|
|
2331
|
+
)
|
|
2332
|
+
|
|
2333
|
+
def _add_table(
|
|
2334
|
+
self,
|
|
2335
|
+
table: DataTable,
|
|
2336
|
+
*,
|
|
2337
|
+
operation: str | None = None,
|
|
2338
|
+
journal_params: dict | None = None,
|
|
2339
|
+
source_tables=None,
|
|
2340
|
+
journal_title: str | None = None,
|
|
2341
|
+
) -> DataTable:
|
|
2342
|
+
self.project.add_table(table)
|
|
2343
|
+
self._mark_project_dirty()
|
|
2344
|
+
self.open_table_view(table)
|
|
2345
|
+
if operation:
|
|
2346
|
+
self._record_table_operation(
|
|
2347
|
+
operation=operation,
|
|
2348
|
+
title=journal_title or f"Create {table.name}",
|
|
2349
|
+
source_tables=list(source_tables or []),
|
|
2350
|
+
result_table=table.name,
|
|
2351
|
+
params=dict(journal_params or {}),
|
|
2352
|
+
link_table=table,
|
|
2353
|
+
)
|
|
2354
|
+
self._refresh_project_tree()
|
|
2355
|
+
return table
|
|
2356
|
+
|
|
2357
|
+
def apply_script_outcome(self, outcome, selected_table: DataTable | None = None) -> None:
|
|
2358
|
+
snapshots = {table.name: table for table in outcome.tables}
|
|
2359
|
+
selected_snapshot = getattr(outcome, "selected", None)
|
|
2360
|
+
if selected_table is not None and selected_snapshot is not None:
|
|
2361
|
+
restore_table(selected_table, selected_snapshot)
|
|
2362
|
+
for live in list(self.project.tables):
|
|
2363
|
+
if selected_table is not None and live is selected_table:
|
|
2364
|
+
continue
|
|
2365
|
+
snapshot = snapshots.get(live.name)
|
|
2366
|
+
if snapshot is None:
|
|
2367
|
+
document = self._table_documents.pop(live, None)
|
|
2368
|
+
if document is not None:
|
|
2369
|
+
self._close_document(document)
|
|
2370
|
+
self.project.remove_table(live)
|
|
2371
|
+
else:
|
|
2372
|
+
restore_table(live, snapshot)
|
|
2373
|
+
for name, snapshot in snapshots.items():
|
|
2374
|
+
if self.project.find_table(name) is None:
|
|
2375
|
+
self.project.add_table(snapshot)
|
|
2376
|
+
self.open_table_view(snapshot)
|
|
2377
|
+
for table in list(self.project.tables):
|
|
2378
|
+
if table in self._table_documents:
|
|
2379
|
+
self._refresh_table(table)
|
|
2380
|
+
self._mark_project_dirty()
|
|
2381
|
+
self._refresh_project_tree()
|
|
2382
|
+
|
|
2383
|
+
def _refresh_table(self, table: DataTable) -> None:
|
|
2384
|
+
view = self.table_views.get(table)
|
|
2385
|
+
if view is not None:
|
|
2386
|
+
view.refresh()
|
|
2387
|
+
document = self._table_documents.get(table)
|
|
2388
|
+
if document is not None:
|
|
2389
|
+
document.set_title(table.name)
|
|
2390
|
+
document.refresh_bars()
|
|
2391
|
+
sub = self._table_windows.get(table)
|
|
2392
|
+
if sub is not None:
|
|
2393
|
+
sub.setWindowTitle(table.name)
|
|
2394
|
+
self._refresh_project_tree()
|
|
2395
|
+
self._refresh_plot_page(table)
|
|
2396
|
+
self._update_status_context()
|
|
2397
|
+
|
|
2398
|
+
def _refresh_plot_page(self, table: DataTable) -> None:
|
|
2399
|
+
for page in self._plot_pages_for_table(table):
|
|
2400
|
+
for plot in page.result.plots:
|
|
2401
|
+
if plot.data is not None:
|
|
2402
|
+
plot.row_styles = {row_id: table.row_state(row_id) for row_id in plot.data.index}
|
|
2403
|
+
page.refresh()
|
|
2404
|
+
self._update_plot_report(page)
|
|
2405
|
+
|
|
2406
|
+
def _refresh_all(self) -> None:
|
|
2407
|
+
for table, view in list(self.table_views.items()):
|
|
2408
|
+
view.refresh()
|
|
2409
|
+
self._refresh_project_tree()
|
|
2410
|
+
|
|
2411
|
+
def _restore_table(self, table: DataTable, snapshot: DataTable) -> None:
|
|
2412
|
+
restore_table(table, snapshot)
|
|
2413
|
+
self._refresh_table(table)
|
|
2414
|
+
|
|
2415
|
+
def _mutate_table(
|
|
2416
|
+
self,
|
|
2417
|
+
table: DataTable,
|
|
2418
|
+
label: str,
|
|
2419
|
+
func,
|
|
2420
|
+
*,
|
|
2421
|
+
operation: str | None = None,
|
|
2422
|
+
journal_params: dict | None = None,
|
|
2423
|
+
) -> bool:
|
|
2424
|
+
before = table.copy()
|
|
2425
|
+
try:
|
|
2426
|
+
outcome = func()
|
|
2427
|
+
except Exception as exc:
|
|
2428
|
+
restore_table(table, before)
|
|
2429
|
+
self._refresh_table(table)
|
|
2430
|
+
QMessageBox.critical(self, "Operation failed", str(exc))
|
|
2431
|
+
return False
|
|
2432
|
+
if outcome is False:
|
|
2433
|
+
self._refresh_table(table)
|
|
2434
|
+
return False
|
|
2435
|
+
entry: JournalEntry | None = None
|
|
2436
|
+
if operation:
|
|
2437
|
+
entry = self._record_table_operation(
|
|
2438
|
+
operation=operation,
|
|
2439
|
+
title=label,
|
|
2440
|
+
source_tables=[table.name],
|
|
2441
|
+
result_table=table.name,
|
|
2442
|
+
params=dict(journal_params or {}),
|
|
2443
|
+
link_table=table,
|
|
2444
|
+
role="result",
|
|
2445
|
+
)
|
|
2446
|
+
after = table.copy()
|
|
2447
|
+
|
|
2448
|
+
def undo() -> None:
|
|
2449
|
+
if entry is not None:
|
|
2450
|
+
entry.undone = True
|
|
2451
|
+
self._restore_table(table, before)
|
|
2452
|
+
|
|
2453
|
+
def redo() -> None:
|
|
2454
|
+
if entry is not None:
|
|
2455
|
+
entry.undone = False
|
|
2456
|
+
self._restore_table(table, after)
|
|
2457
|
+
|
|
2458
|
+
self.command_stack.record(label, undo, redo)
|
|
2459
|
+
self._mark_project_dirty()
|
|
2460
|
+
self._refresh_table(table)
|
|
2461
|
+
self._update_undo_actions()
|
|
2462
|
+
self._log(label)
|
|
2463
|
+
return True
|
|
2464
|
+
|
|
2465
|
+
def _undo(self) -> None:
|
|
2466
|
+
label = self.command_stack.undo()
|
|
2467
|
+
if label:
|
|
2468
|
+
self._log(f"Undo: {label}")
|
|
2469
|
+
self._update_undo_actions()
|
|
2470
|
+
|
|
2471
|
+
def _redo(self) -> None:
|
|
2472
|
+
label = self.command_stack.redo()
|
|
2473
|
+
if label:
|
|
2474
|
+
self._log(f"Redo: {label}")
|
|
2475
|
+
self._update_undo_actions()
|
|
2476
|
+
|
|
2477
|
+
def _update_undo_actions(self) -> None:
|
|
2478
|
+
self.undo_action.setEnabled(self.command_stack.can_undo())
|
|
2479
|
+
self.redo_action.setEnabled(self.command_stack.can_redo())
|
|
2480
|
+
self.undo_action.setText(f"Undo {self.command_stack.undo_label()}" if self.command_stack.can_undo() else "Undo")
|
|
2481
|
+
self.redo_action.setText(f"Redo {self.command_stack.redo_label()}" if self.command_stack.can_redo() else "Redo")
|
|
2482
|
+
|
|
2483
|
+
def _rename_column(self) -> None:
|
|
2484
|
+
table = self._require_table()
|
|
2485
|
+
if table:
|
|
2486
|
+
column = self._ask_column(table, "Rename Column")
|
|
2487
|
+
if column:
|
|
2488
|
+
self._rename_column_for(table, column)
|
|
2489
|
+
|
|
2490
|
+
def _rename_column_for(self, table: DataTable, column: str) -> None:
|
|
2491
|
+
new_name, ok = QInputDialog.getText(self, "Rename Column", "New name", text=column)
|
|
2492
|
+
if not ok or not new_name.strip() or new_name.strip() == column:
|
|
2493
|
+
return
|
|
2494
|
+
self._mutate_table(
|
|
2495
|
+
table,
|
|
2496
|
+
f"Rename {column}",
|
|
2497
|
+
lambda: table.rename_column(column, new_name.strip()),
|
|
2498
|
+
operation="rename_column",
|
|
2499
|
+
journal_params={"old": column, "new": new_name.strip()},
|
|
2500
|
+
)
|
|
2501
|
+
|
|
2502
|
+
def _column_properties_current(self) -> None:
|
|
2503
|
+
table = self._require_table()
|
|
2504
|
+
if table:
|
|
2505
|
+
column = self._ask_column(table, "Column Properties")
|
|
2506
|
+
if column:
|
|
2507
|
+
self._column_properties(table, column)
|
|
2508
|
+
|
|
2509
|
+
def _column_manager(self) -> None:
|
|
2510
|
+
table = self._require_table()
|
|
2511
|
+
if table is None:
|
|
2512
|
+
return
|
|
2513
|
+
dialog = ColumnManagerDialog(table, self)
|
|
2514
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or not dialog.result:
|
|
2515
|
+
return
|
|
2516
|
+
changes = dialog.result
|
|
2517
|
+
specs = changes.get("specs") or {}
|
|
2518
|
+
type_changes = {
|
|
2519
|
+
column: values.get("data_type", table.specs[column].data_type)
|
|
2520
|
+
for column, values in specs.items()
|
|
2521
|
+
if column in table.specs and values.get("data_type") != table.specs[column].data_type
|
|
2522
|
+
}
|
|
2523
|
+
if type_changes:
|
|
2524
|
+
proceed = QMessageBox.question(
|
|
2525
|
+
self,
|
|
2526
|
+
"Convert Columns",
|
|
2527
|
+
f"Convert {len(type_changes)} column(s) to a new data type?\nValues that cannot be parsed become missing.",
|
|
2528
|
+
)
|
|
2529
|
+
if proceed != QMessageBox.StandardButton.Yes:
|
|
2530
|
+
return
|
|
2531
|
+
lost = {"count": 0}
|
|
2532
|
+
|
|
2533
|
+
def apply() -> None:
|
|
2534
|
+
for column, mapping in (changes.get("recodes") or {}).items():
|
|
2535
|
+
if not mapping or column not in table.data.columns:
|
|
2536
|
+
continue
|
|
2537
|
+
recoded = recode_column(table, column, mapping, keep_unmapped=True)
|
|
2538
|
+
table.replace_column(column, recoded.data[column])
|
|
2539
|
+
for column, values in specs.items():
|
|
2540
|
+
if column not in table.specs:
|
|
2541
|
+
continue
|
|
2542
|
+
spec = table.specs[column]
|
|
2543
|
+
if column in type_changes:
|
|
2544
|
+
lost["count"] += table.convert_column(column, type_changes[column], values.get("modeling_type"))
|
|
2545
|
+
else:
|
|
2546
|
+
spec.data_type = values.get("data_type", spec.data_type)
|
|
2547
|
+
spec.modeling_type = values.get("modeling_type", spec.modeling_type)
|
|
2548
|
+
spec.units = values.get("units", spec.units)
|
|
2549
|
+
spec.notes = values.get("notes", spec.notes)
|
|
2550
|
+
spec.format = values.get("format", spec.format)
|
|
2551
|
+
spec.missing_values = list(values.get("missing_values", spec.missing_values))
|
|
2552
|
+
table.recompute_formulas()
|
|
2553
|
+
table.modified = True
|
|
2554
|
+
|
|
2555
|
+
if self._mutate_table(table, "Column Manager", apply):
|
|
2556
|
+
if lost["count"]:
|
|
2557
|
+
self._log(f"Updated column definitions for {table.name}; {lost['count']} value(s) became missing")
|
|
2558
|
+
else:
|
|
2559
|
+
self._log(f"Updated column definitions for {table.name}")
|
|
2560
|
+
|
|
2561
|
+
def _column_properties(self, table: DataTable, column: str) -> None:
|
|
2562
|
+
dialog = ColumnPropertiesDialog(table, column, self)
|
|
2563
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
2564
|
+
return
|
|
2565
|
+
values = dialog.result or {}
|
|
2566
|
+
current = table.specs[column]
|
|
2567
|
+
new_name = str(values.get("name", column)).strip()
|
|
2568
|
+
if not new_name:
|
|
2569
|
+
QMessageBox.critical(self, "Column properties", "Column name cannot be empty.")
|
|
2570
|
+
return
|
|
2571
|
+
if new_name != column and new_name in table.columns:
|
|
2572
|
+
QMessageBox.critical(self, "Column properties", f"Column {new_name!r} already exists.")
|
|
2573
|
+
return
|
|
2574
|
+
new_type = values.get("data_type", current.data_type)
|
|
2575
|
+
convert = new_type != current.data_type
|
|
2576
|
+
if convert:
|
|
2577
|
+
proceed = QMessageBox.question(
|
|
2578
|
+
self,
|
|
2579
|
+
"Convert Column",
|
|
2580
|
+
f"Convert {column!r} from {current.data_type} to {new_type}?\nValues that cannot be parsed become missing.",
|
|
2581
|
+
)
|
|
2582
|
+
if proceed != QMessageBox.StandardButton.Yes:
|
|
2583
|
+
return
|
|
2584
|
+
lost = {"count": 0}
|
|
2585
|
+
|
|
2586
|
+
def apply() -> None:
|
|
2587
|
+
target = column
|
|
2588
|
+
if new_name != column:
|
|
2589
|
+
table.rename_column(column, new_name)
|
|
2590
|
+
target = new_name
|
|
2591
|
+
spec = table.specs[target]
|
|
2592
|
+
spec.units = values.get("units", spec.units)
|
|
2593
|
+
spec.notes = values.get("notes", spec.notes)
|
|
2594
|
+
spec.formula = values.get("formula") or None
|
|
2595
|
+
spec.format = values.get("format")
|
|
2596
|
+
spec.missing_values = list(values.get("missing_values") or [])
|
|
2597
|
+
if not spec.formula:
|
|
2598
|
+
table.formula_errors.pop(target, None)
|
|
2599
|
+
if convert:
|
|
2600
|
+
lost["count"] = table.convert_column(target, new_type, values.get("modeling_type"))
|
|
2601
|
+
else:
|
|
2602
|
+
spec.modeling_type = values.get("modeling_type", spec.modeling_type)
|
|
2603
|
+
spec.data_type = new_type
|
|
2604
|
+
table.recompute_formulas()
|
|
2605
|
+
table.modified = True
|
|
2606
|
+
|
|
2607
|
+
if self._mutate_table(table, f"Properties for {column}", apply) and convert and lost["count"]:
|
|
2608
|
+
self._log(f"Converted {column} to {new_type}; {lost['count']} value(s) became missing")
|
|
2609
|
+
|
|
2610
|
+
def _hide_column(self) -> None:
|
|
2611
|
+
table = self._require_table()
|
|
2612
|
+
if table:
|
|
2613
|
+
column = self._ask_column(table, "Hide Column")
|
|
2614
|
+
if column:
|
|
2615
|
+
self._hide_column_for(table, column)
|
|
2616
|
+
|
|
2617
|
+
def _hide_column_for(self, table: DataTable, column: str) -> None:
|
|
2618
|
+
self._mutate_table(table, f"Hide {column}", lambda: table.hidden_columns.add(column), operation="hide_column", journal_params={"column": column})
|
|
2619
|
+
|
|
2620
|
+
def _delete_column(self) -> None:
|
|
2621
|
+
table = self._require_table()
|
|
2622
|
+
if table:
|
|
2623
|
+
column = self._ask_column(table, "Delete Column")
|
|
2624
|
+
if column:
|
|
2625
|
+
self._delete_column_for(table, column)
|
|
2626
|
+
|
|
2627
|
+
def _delete_column_for(self, table: DataTable, column: str) -> None:
|
|
2628
|
+
if QMessageBox.question(self, "Delete Column", f"Delete column {column!r}?") != QMessageBox.StandardButton.Yes:
|
|
2629
|
+
return
|
|
2630
|
+
self._mutate_table(table, f"Delete {column}", lambda: table.drop_columns([column]), operation="delete_column", journal_params={"columns": [column]})
|
|
2631
|
+
|
|
2632
|
+
def _ask_column(self, table: DataTable, title: str) -> str | None:
|
|
2633
|
+
column, ok = QInputDialog.getItem(self, title, "Column", table.columns, 0, False)
|
|
2634
|
+
return column if ok else None
|
|
2635
|
+
|
|
2636
|
+
def _filter_rows(self) -> None:
|
|
2637
|
+
table = self._require_table()
|
|
2638
|
+
if table is None:
|
|
2639
|
+
return
|
|
2640
|
+
dialog = FilterDialog(table, self)
|
|
2641
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
2642
|
+
return
|
|
2643
|
+
expression = dialog.result
|
|
2644
|
+
self._mutate_table(table, "Filter rows", lambda: table.set_filter(expression), operation="filter", journal_params={"expression": expression})
|
|
2645
|
+
|
|
2646
|
+
def _clear_filter(self) -> None:
|
|
2647
|
+
table = self._require_table()
|
|
2648
|
+
if table:
|
|
2649
|
+
self._clear_filter_for(table)
|
|
2650
|
+
|
|
2651
|
+
def _clear_filter_for(self, table: DataTable) -> None:
|
|
2652
|
+
self._mutate_table(table, "Clear filter", lambda: table.set_filter(None), operation="clear_filter")
|
|
2653
|
+
|
|
2654
|
+
def _apply_filter_for(self, table: DataTable, expression: str) -> None:
|
|
2655
|
+
expression = expression.strip()
|
|
2656
|
+
if not expression:
|
|
2657
|
+
self._clear_filter_for(table)
|
|
2658
|
+
return
|
|
2659
|
+
self._mutate_table(table, "Filter rows", lambda: table.set_filter(expression), operation="filter", journal_params={"expression": expression})
|
|
2660
|
+
|
|
2661
|
+
def _apply_formula_for(self, table: DataTable, column: str, expression: str) -> None:
|
|
2662
|
+
if column not in table.specs:
|
|
2663
|
+
return
|
|
2664
|
+
expression = expression.strip()
|
|
2665
|
+
self._mutate_table(
|
|
2666
|
+
table,
|
|
2667
|
+
f"Formula for {column}",
|
|
2668
|
+
lambda: table.set_formula(column, expression or None),
|
|
2669
|
+
operation="set_formula",
|
|
2670
|
+
journal_params={"column": column, "formula": expression or None},
|
|
2671
|
+
)
|
|
2672
|
+
|
|
2673
|
+
def _hide_selected(self) -> None:
|
|
2674
|
+
widget = self._active_table_view()
|
|
2675
|
+
if widget is None:
|
|
2676
|
+
self._require_table()
|
|
2677
|
+
return
|
|
2678
|
+
rows = widget.selected_row_ids()
|
|
2679
|
+
if rows:
|
|
2680
|
+
self._mutate_table(
|
|
2681
|
+
widget.table,
|
|
2682
|
+
"Hide rows",
|
|
2683
|
+
lambda: widget.table.set_hidden(rows, True),
|
|
2684
|
+
operation="hide_rows",
|
|
2685
|
+
journal_params={"rows": rows},
|
|
2686
|
+
)
|
|
2687
|
+
|
|
2688
|
+
def _exclude_selected(self) -> None:
|
|
2689
|
+
widget = self._active_table_view()
|
|
2690
|
+
if widget is None:
|
|
2691
|
+
self._require_table()
|
|
2692
|
+
return
|
|
2693
|
+
rows = widget.selected_row_ids()
|
|
2694
|
+
if rows:
|
|
2695
|
+
self._set_excluded(widget.table, rows, True)
|
|
2696
|
+
|
|
2697
|
+
def _set_excluded(self, table: DataTable, rows: list, excluded: bool) -> None:
|
|
2698
|
+
self._mutate_table(
|
|
2699
|
+
table,
|
|
2700
|
+
"Exclude rows" if excluded else "Include rows",
|
|
2701
|
+
lambda: table.set_excluded(rows, excluded),
|
|
2702
|
+
operation="exclude_rows" if excluded else "include_rows",
|
|
2703
|
+
journal_params={"rows": rows},
|
|
2704
|
+
)
|
|
2705
|
+
|
|
2706
|
+
def _clear_exclusions(self) -> None:
|
|
2707
|
+
table = self._require_table()
|
|
2708
|
+
if table:
|
|
2709
|
+
self._clear_exclusions_for(table)
|
|
2710
|
+
|
|
2711
|
+
def _clear_exclusions_for(self, table: DataTable) -> None:
|
|
2712
|
+
self._mutate_table(table, "Clear exclusions", table.clear_exclusions, operation="clear_exclusions")
|
|
2713
|
+
|
|
2714
|
+
# ---------------------------------------------------------- table ops
|
|
2715
|
+
def _join_tables(self) -> None:
|
|
2716
|
+
table = self._require_table()
|
|
2717
|
+
if table is None or len(self.project.tables) < 2:
|
|
2718
|
+
if table is not None:
|
|
2719
|
+
QMessageBox.information(self, "Merge", "Open at least two data tables to merge.")
|
|
2720
|
+
return
|
|
2721
|
+
dialog = JoinDialog(self.project, table, self)
|
|
2722
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2723
|
+
self._add_table(
|
|
2724
|
+
dialog.result,
|
|
2725
|
+
operation="join",
|
|
2726
|
+
journal_params={
|
|
2727
|
+
"how": dialog.how_combo.currentData(),
|
|
2728
|
+
"left_on": dialog.left_keys.checked_items(),
|
|
2729
|
+
"right_on": dialog.right_keys.checked_items(),
|
|
2730
|
+
},
|
|
2731
|
+
source_tables=[table.name, dialog.right_combo.currentData()],
|
|
2732
|
+
)
|
|
2733
|
+
|
|
2734
|
+
def _append_tables(self) -> None:
|
|
2735
|
+
table = self._require_table()
|
|
2736
|
+
if table is None or len(self.project.tables) < 2:
|
|
2737
|
+
if table is not None:
|
|
2738
|
+
QMessageBox.information(self, "Append", "Open at least two data tables to append.")
|
|
2739
|
+
return
|
|
2740
|
+
dialog = AppendDialog(self.project, table, self)
|
|
2741
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2742
|
+
source_names = dialog.tables.checked_items()
|
|
2743
|
+
self._add_table(dialog.result, operation="append", source_tables=source_names)
|
|
2744
|
+
|
|
2745
|
+
def _split_table(self) -> None:
|
|
2746
|
+
table = self._require_table()
|
|
2747
|
+
if table is None:
|
|
2748
|
+
return
|
|
2749
|
+
dialog = SplitDialog(table, self)
|
|
2750
|
+
if dialog.exec() == QDialog.DialogCode.Accepted:
|
|
2751
|
+
for index, result in enumerate(dialog.result or []):
|
|
2752
|
+
self._add_table(result, operation="split", journal_params={"column": dialog.column_combo.currentData(), "index": index}, source_tables=[table.name])
|
|
2753
|
+
|
|
2754
|
+
def _stack_table(self) -> None:
|
|
2755
|
+
table = self._require_table()
|
|
2756
|
+
if table is None:
|
|
2757
|
+
return
|
|
2758
|
+
dialog = StackDialog(table, self)
|
|
2759
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2760
|
+
self._add_table(dialog.result, operation="stack", journal_params={"id_columns": dialog.id_columns.checked_items(), "value_columns": dialog.value_columns.checked_items(), "variable_name": dialog.var_edit.text(), "value_name": dialog.value_edit.text()}, source_tables=[table.name])
|
|
2761
|
+
|
|
2762
|
+
def _unstack_table(self) -> None:
|
|
2763
|
+
table = self._require_table()
|
|
2764
|
+
if table is None:
|
|
2765
|
+
return
|
|
2766
|
+
dialog = UnstackDialog(table, self)
|
|
2767
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2768
|
+
self._add_table(dialog.result, operation="unstack", journal_params={"index_columns": dialog.index_columns.checked_items(), "column_column": dialog.column_combo.currentData(), "value_column": dialog.value_combo.currentData(), "aggregate": dialog.aggregate_combo.currentText()}, source_tables=[table.name])
|
|
2769
|
+
|
|
2770
|
+
def _transpose_table(self) -> None:
|
|
2771
|
+
table = self._require_table()
|
|
2772
|
+
if table is None:
|
|
2773
|
+
return
|
|
2774
|
+
try:
|
|
2775
|
+
result = transpose_table(table, f"{table.name} Transposed")
|
|
2776
|
+
except Exception as exc:
|
|
2777
|
+
QMessageBox.critical(self, "Transpose failed", str(exc))
|
|
2778
|
+
return
|
|
2779
|
+
self._add_table(result, operation="transpose", source_tables=[table.name])
|
|
2780
|
+
|
|
2781
|
+
def _subset_columns(self) -> None:
|
|
2782
|
+
table = self._require_table()
|
|
2783
|
+
if table is None:
|
|
2784
|
+
return
|
|
2785
|
+
dialog = SubsetColumnsDialog(table, self)
|
|
2786
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2787
|
+
self._add_table(dialog.result, operation="subset", journal_params={"columns": dialog.columns.checked_items()}, source_tables=[table.name])
|
|
2788
|
+
|
|
2789
|
+
def _current_selection(self) -> tuple[str, list] | None:
|
|
2790
|
+
widget = self._active_document()
|
|
2791
|
+
view = None
|
|
2792
|
+
if isinstance(widget, TableDocument):
|
|
2793
|
+
view = widget.view
|
|
2794
|
+
elif isinstance(widget, DataTableView):
|
|
2795
|
+
view = widget
|
|
2796
|
+
if view is not None:
|
|
2797
|
+
return view.table.name, view.selected_row_ids()
|
|
2798
|
+
return self._selection_state
|
|
2799
|
+
|
|
2800
|
+
def _create_subset_from_selection(self) -> None:
|
|
2801
|
+
selection = self._current_selection()
|
|
2802
|
+
if not selection or not selection[1]:
|
|
2803
|
+
QMessageBox.information(
|
|
2804
|
+
self,
|
|
2805
|
+
"Create Subset",
|
|
2806
|
+
"Select rows in a plot (Brush) or in a data table first.",
|
|
2807
|
+
)
|
|
2808
|
+
return
|
|
2809
|
+
table_name, row_ids = selection
|
|
2810
|
+
table = self.project.find_table(table_name) if table_name else None
|
|
2811
|
+
if table is None:
|
|
2812
|
+
table = self._require_table()
|
|
2813
|
+
if table is None:
|
|
2814
|
+
return
|
|
2815
|
+
valid = [row_id for row_id in row_ids if row_id in table.data.index]
|
|
2816
|
+
if not valid:
|
|
2817
|
+
QMessageBox.information(self, "Create Subset", "The selected rows are no longer available.")
|
|
2818
|
+
return
|
|
2819
|
+
try:
|
|
2820
|
+
subset = table.subset(rows=valid)
|
|
2821
|
+
except Exception as exc:
|
|
2822
|
+
QMessageBox.critical(self, "Create Subset", str(exc))
|
|
2823
|
+
return
|
|
2824
|
+
self._add_table(
|
|
2825
|
+
subset,
|
|
2826
|
+
operation="subset_rows",
|
|
2827
|
+
journal_params={"rows": valid},
|
|
2828
|
+
source_tables=[table.name],
|
|
2829
|
+
journal_title=f"Subset of {table.name}",
|
|
2830
|
+
)
|
|
2831
|
+
self._log(f"Created {subset.name} with {len(valid)} selected rows")
|
|
2832
|
+
|
|
2833
|
+
def _new_column(self) -> None:
|
|
2834
|
+
table = self._require_table()
|
|
2835
|
+
if table is None:
|
|
2836
|
+
return
|
|
2837
|
+
dialog = NewColumnDialog(table, self)
|
|
2838
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
2839
|
+
return
|
|
2840
|
+
name, data_type, default = dialog.result
|
|
2841
|
+
self._mutate_table(
|
|
2842
|
+
table,
|
|
2843
|
+
f"Add column {name}",
|
|
2844
|
+
lambda: add_empty_column(table, name, data_type, default),
|
|
2845
|
+
operation="add_column",
|
|
2846
|
+
journal_params={"name": name, "data_type": data_type, "default": default},
|
|
2847
|
+
)
|
|
2848
|
+
|
|
2849
|
+
def _formula_column(self) -> None:
|
|
2850
|
+
table = self._require_table()
|
|
2851
|
+
if table is None:
|
|
2852
|
+
return
|
|
2853
|
+
dialog = FormulaDialog(table, self)
|
|
2854
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
2855
|
+
return
|
|
2856
|
+
name, formula = dialog.result
|
|
2857
|
+
self._mutate_table(
|
|
2858
|
+
table,
|
|
2859
|
+
f"Formula column {name}",
|
|
2860
|
+
lambda: add_formula_column(table, name, formula),
|
|
2861
|
+
operation="formula",
|
|
2862
|
+
journal_params={"name": name, "formula": formula},
|
|
2863
|
+
)
|
|
2864
|
+
|
|
2865
|
+
def _recode_column(self) -> None:
|
|
2866
|
+
table = self._require_table()
|
|
2867
|
+
if table is None:
|
|
2868
|
+
return
|
|
2869
|
+
dialog = RecodeDialog(table, self)
|
|
2870
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2871
|
+
result = dialog.result
|
|
2872
|
+
result.name = f"{table.name} Recoded"
|
|
2873
|
+
self._add_table(
|
|
2874
|
+
result,
|
|
2875
|
+
operation="recode",
|
|
2876
|
+
journal_params={"column": dialog.column_combo.currentData(), "mapping": dialog._mapping(), "default": dialog._parse_value(dialog.default_edit.text()) if dialog.default_edit.text() else None, "new_name": dialog.new_name_edit.text() or None, "keep_unmapped": not bool(dialog.default_edit.text())},
|
|
2877
|
+
source_tables=[table.name],
|
|
2878
|
+
)
|
|
2879
|
+
|
|
2880
|
+
def _boxcox_column(self) -> None:
|
|
2881
|
+
table = self._require_table()
|
|
2882
|
+
if table is None:
|
|
2883
|
+
return
|
|
2884
|
+
columns = [column for column in table.columns if pd.api.types.is_numeric_dtype(table.data[column])]
|
|
2885
|
+
if not columns:
|
|
2886
|
+
QMessageBox.information(self, "Box-Cox Transform", "No numeric columns are available.")
|
|
2887
|
+
return
|
|
2888
|
+
column, ok = QInputDialog.getItem(self, "Box-Cox Transform", "Column", columns, 0, False)
|
|
2889
|
+
if not ok:
|
|
2890
|
+
return
|
|
2891
|
+
try:
|
|
2892
|
+
result, lam = boxcox_column(table, column)
|
|
2893
|
+
except Exception as exc:
|
|
2894
|
+
QMessageBox.critical(self, "Box-Cox Transform", str(exc))
|
|
2895
|
+
return
|
|
2896
|
+
self._add_table(
|
|
2897
|
+
result,
|
|
2898
|
+
operation="boxcox",
|
|
2899
|
+
journal_params={"column": column, "shift": float(table.data[column].min()) if len(table) else None},
|
|
2900
|
+
source_tables=[table.name],
|
|
2901
|
+
)
|
|
2902
|
+
self._log(f"Box-Cox transform for {column}: lambda = {lam:.6g}")
|
|
2903
|
+
|
|
2904
|
+
def _rank_column(self) -> None:
|
|
2905
|
+
table = self._require_table()
|
|
2906
|
+
if table is None:
|
|
2907
|
+
return
|
|
2908
|
+
columns = [column for column in table.columns if pd.api.types.is_numeric_dtype(table.data[column])]
|
|
2909
|
+
if not columns:
|
|
2910
|
+
return
|
|
2911
|
+
column, ok = QInputDialog.getItem(self, "Rank Column", "Column", columns, 0, False)
|
|
2912
|
+
if ok:
|
|
2913
|
+
self._add_table(rank_column(table, column), operation="rank", journal_params={"column": column, "method": "average"}, source_tables=[table.name])
|
|
2914
|
+
|
|
2915
|
+
def _bin_column(self) -> None:
|
|
2916
|
+
table = self._require_table()
|
|
2917
|
+
if table is None:
|
|
2918
|
+
return
|
|
2919
|
+
columns = [column for column in table.columns if pd.api.types.is_numeric_dtype(table.data[column])]
|
|
2920
|
+
if not columns:
|
|
2921
|
+
return
|
|
2922
|
+
column, ok = QInputDialog.getItem(self, "Bin Column", "Column", columns, 0, False)
|
|
2923
|
+
if not ok:
|
|
2924
|
+
return
|
|
2925
|
+
bins, ok = QInputDialog.getInt(self, "Bin Column", "Number of bins", 5, 2, 100)
|
|
2926
|
+
if ok:
|
|
2927
|
+
self._add_table(bin_column(table, column, bins), operation="bin", journal_params={"column": column, "bins": bins}, source_tables=[table.name])
|
|
2928
|
+
|
|
2929
|
+
def _text_to_columns(self) -> None:
|
|
2930
|
+
table = self._require_table()
|
|
2931
|
+
if table is None:
|
|
2932
|
+
return
|
|
2933
|
+
column, ok = QInputDialog.getItem(self, "Text to Columns", "Column", table.columns, 0, False)
|
|
2934
|
+
if not ok:
|
|
2935
|
+
return
|
|
2936
|
+
separator, ok = QInputDialog.getText(self, "Text to Columns", "Separator", text=",")
|
|
2937
|
+
if ok:
|
|
2938
|
+
self._add_table(text_to_columns(table, column, separator or ","), operation="text_to_columns", journal_params={"column": column, "separator": separator or ","}, source_tables=[table.name])
|
|
2939
|
+
|
|
2940
|
+
def _replace_missing(self) -> None:
|
|
2941
|
+
table = self._require_table()
|
|
2942
|
+
if table is None:
|
|
2943
|
+
return
|
|
2944
|
+
dialog = MissingDialog(table, self)
|
|
2945
|
+
if dialog.exec() == QDialog.DialogCode.Accepted and dialog.result is not None:
|
|
2946
|
+
result = dialog.result
|
|
2947
|
+
result.name = f"{table.name} Missing Replaced"
|
|
2948
|
+
value_text = dialog.value_edit.text()
|
|
2949
|
+
try:
|
|
2950
|
+
value = float(value_text)
|
|
2951
|
+
if value.is_integer():
|
|
2952
|
+
value = int(value)
|
|
2953
|
+
except ValueError:
|
|
2954
|
+
value = value_text
|
|
2955
|
+
self._add_table(
|
|
2956
|
+
result,
|
|
2957
|
+
operation="replace_missing",
|
|
2958
|
+
journal_params={"column": dialog.column_combo.currentData(), "value": value, "new_name": dialog.new_name_edit.text() or None},
|
|
2959
|
+
source_tables=[table.name],
|
|
2960
|
+
)
|
|
2961
|
+
|
|
2962
|
+
# --------------------------------------------------------------- stats
|
|
2963
|
+
def _open_stats(self, dialog_class) -> None:
|
|
2964
|
+
table = self._require_table()
|
|
2965
|
+
if table is None:
|
|
2966
|
+
return
|
|
2967
|
+
self._open_stats_for(table, dialog_class)
|
|
2968
|
+
|
|
2969
|
+
def _open_prediction_profiler(self) -> None:
|
|
2970
|
+
table = self._require_table()
|
|
2971
|
+
if table is None:
|
|
2972
|
+
return
|
|
2973
|
+
info = stats_pkg.doe.design_info(table) or {}
|
|
2974
|
+
dialog_class = ProfilerDialog if info else RegressionProfilerDialog
|
|
2975
|
+
self._open_stats_for(table, dialog_class)
|
|
2976
|
+
|
|
2977
|
+
def _open_multi_response_optimization(self) -> None:
|
|
2978
|
+
table = self._require_table()
|
|
2979
|
+
if table is None:
|
|
2980
|
+
return
|
|
2981
|
+
info = stats_pkg.doe.design_info(table) or {}
|
|
2982
|
+
dialog_class = MultiResponseDialog if info else RegressionMultiResponseDialog
|
|
2983
|
+
self._open_stats_for(table, dialog_class)
|
|
2984
|
+
|
|
2985
|
+
def _open_stats_for(self, table: DataTable, dialog_class, params: dict | None = None, kind: str | None = None) -> None:
|
|
2986
|
+
dialog = dialog_class(table, self)
|
|
2987
|
+
if kind:
|
|
2988
|
+
try:
|
|
2989
|
+
dialog.apply_kind(kind)
|
|
2990
|
+
except Exception as exc:
|
|
2991
|
+
self._log(f"Could not restore analysis type: {exc}")
|
|
2992
|
+
if params:
|
|
2993
|
+
try:
|
|
2994
|
+
dialog.apply_params(params)
|
|
2995
|
+
except Exception as exc:
|
|
2996
|
+
self._log(f"Could not restore analysis parameters: {exc}")
|
|
2997
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
2998
|
+
return
|
|
2999
|
+
result = dialog.result
|
|
3000
|
+
if result is None:
|
|
3001
|
+
return
|
|
3002
|
+
self.show_result(
|
|
3003
|
+
result,
|
|
3004
|
+
lambda: self._open_stats_for(table, dialog_class, dict(result.params), result.analysis_type),
|
|
3005
|
+
)
|
|
3006
|
+
|
|
3007
|
+
def _primary_plot_kinds(self, analysis_type: str) -> list[str]:
|
|
3008
|
+
return {
|
|
3009
|
+
"fit_y_by_x": ["scatter", "box"],
|
|
3010
|
+
"linear_regression": ["actual_predicted", "scatter"],
|
|
3011
|
+
"polynomial_regression": ["actual_predicted", "scatter"],
|
|
3012
|
+
"stepwise_regression": ["actual_predicted", "scatter"],
|
|
3013
|
+
"distribution_summary": ["histogram", "density", "box"],
|
|
3014
|
+
"distribution_fit": ["histogram", "density", "box"],
|
|
3015
|
+
"distribution_id": ["histogram", "density"],
|
|
3016
|
+
"predictive": ["importance", "actual_predicted"],
|
|
3017
|
+
"bayesian_linear_regression": ["bayes_forest"],
|
|
3018
|
+
"bayesian_logistic_regression": ["bayes_forest"],
|
|
3019
|
+
"bayesian_two_sample": ["bayes_forest"],
|
|
3020
|
+
"bayesian_anova": ["bayes_forest"],
|
|
3021
|
+
"bayesian_optimization": ["actual_predicted"],
|
|
3022
|
+
}.get(analysis_type, [])
|
|
3023
|
+
|
|
3024
|
+
def _profiler_keep_kinds(self, analysis_type: str) -> list[str]:
|
|
3025
|
+
if analysis_type in {
|
|
3026
|
+
"linear_regression",
|
|
3027
|
+
"logistic_regression",
|
|
3028
|
+
"glm",
|
|
3029
|
+
"polynomial_regression",
|
|
3030
|
+
"mixed_model",
|
|
3031
|
+
"gee",
|
|
3032
|
+
"stepwise_regression",
|
|
3033
|
+
}:
|
|
3034
|
+
return ["profiler"]
|
|
3035
|
+
if analysis_type in {
|
|
3036
|
+
"bayesian_linear_regression",
|
|
3037
|
+
"bayesian_logistic_regression",
|
|
3038
|
+
"bayesian_two_sample",
|
|
3039
|
+
"bayesian_anova",
|
|
3040
|
+
}:
|
|
3041
|
+
return ["bayes_trace", "bayes_posterior", "bayes_ppc"]
|
|
3042
|
+
if analysis_type == "bayesian_optimization":
|
|
3043
|
+
return ["contour", "bar"]
|
|
3044
|
+
return []
|
|
3045
|
+
|
|
3046
|
+
def show_result(self, result, rerun=None):
|
|
3047
|
+
from statstudio.ui.reports.report_view import ReportView
|
|
3048
|
+
|
|
3049
|
+
table = self.project.find_table(getattr(result, "source_table", "") or "")
|
|
3050
|
+
linked = None
|
|
3051
|
+
if table is not None:
|
|
3052
|
+
def linked(rows, t=table):
|
|
3053
|
+
self._linked_selection(t.name, rows)
|
|
3054
|
+
|
|
3055
|
+
try:
|
|
3056
|
+
analysis_type = getattr(result, "analysis_type", "")
|
|
3057
|
+
result.defer_extra_plots(
|
|
3058
|
+
self._primary_plot_kinds(analysis_type),
|
|
3059
|
+
self._profiler_keep_kinds(analysis_type),
|
|
3060
|
+
)
|
|
3061
|
+
except Exception:
|
|
3062
|
+
pass
|
|
3063
|
+
|
|
3064
|
+
record_holder: dict = {"record": None}
|
|
3065
|
+
|
|
3066
|
+
report_timer = QTimer(self)
|
|
3067
|
+
report_timer.setSingleShot(True)
|
|
3068
|
+
report_timer.setInterval(200)
|
|
3069
|
+
|
|
3070
|
+
def flush_report_change() -> None:
|
|
3071
|
+
record = record_holder.get("record")
|
|
3072
|
+
if record is None:
|
|
3073
|
+
return
|
|
3074
|
+
record.html = result.to_html(include_plots=True)
|
|
3075
|
+
self._persist_report_state(record, result)
|
|
3076
|
+
|
|
3077
|
+
def report_changed() -> None:
|
|
3078
|
+
record = record_holder.get("record")
|
|
3079
|
+
if record is not None:
|
|
3080
|
+
self._persist_report_state(record, result)
|
|
3081
|
+
report_timer.start()
|
|
3082
|
+
|
|
3083
|
+
report_timer.timeout.connect(flush_report_change)
|
|
3084
|
+
|
|
3085
|
+
code = (
|
|
3086
|
+
scripting.analysis_code(result, "table")
|
|
3087
|
+
if table is not None
|
|
3088
|
+
else "# No source table is available for this replay."
|
|
3089
|
+
)
|
|
3090
|
+
view = ReportView(
|
|
3091
|
+
result,
|
|
3092
|
+
rerun=rerun,
|
|
3093
|
+
linked_selection=linked,
|
|
3094
|
+
code=code,
|
|
3095
|
+
table=table,
|
|
3096
|
+
report_changed=report_changed,
|
|
3097
|
+
create_subset=self._create_subset_from_selection,
|
|
3098
|
+
)
|
|
3099
|
+
self._add_document(view, result.title)
|
|
3100
|
+
self.report_views.append(view)
|
|
3101
|
+
try:
|
|
3102
|
+
record = ReportRecord(
|
|
3103
|
+
title=result.title,
|
|
3104
|
+
html=result.to_html(include_plots=True),
|
|
3105
|
+
kind=result.analysis_type,
|
|
3106
|
+
source_table=result.source_table,
|
|
3107
|
+
params=dict(result.params),
|
|
3108
|
+
data_hash=self._table_hash(table) if table is not None else "",
|
|
3109
|
+
code=code,
|
|
3110
|
+
)
|
|
3111
|
+
record_holder["record"] = record
|
|
3112
|
+
view.report_record = record
|
|
3113
|
+
self.project.add_report(record)
|
|
3114
|
+
if table is not None:
|
|
3115
|
+
cumulative = scripting.analysis_code(
|
|
3116
|
+
result,
|
|
3117
|
+
f"_tables[{scripting.literal(table.name)}]",
|
|
3118
|
+
)
|
|
3119
|
+
self._record_entry(
|
|
3120
|
+
kind="analysis",
|
|
3121
|
+
operation=result.analysis_type,
|
|
3122
|
+
title=result.title,
|
|
3123
|
+
source_tables=[table.name],
|
|
3124
|
+
result_table="",
|
|
3125
|
+
params=dict(result.params),
|
|
3126
|
+
code=cumulative,
|
|
3127
|
+
table_code=code,
|
|
3128
|
+
link_table=table,
|
|
3129
|
+
analysis_type=result.analysis_type,
|
|
3130
|
+
role="analysis",
|
|
3131
|
+
)
|
|
3132
|
+
except Exception as exc:
|
|
3133
|
+
self._log(f"Could not store report: {exc}")
|
|
3134
|
+
self._mark_project_dirty()
|
|
3135
|
+
self._refresh_project_tree()
|
|
3136
|
+
self._log(f"Analysis complete: {result.title}")
|
|
3137
|
+
return view
|
|
3138
|
+
|
|
3139
|
+
# ----------------------------------------------------------------- DOE
|
|
3140
|
+
def _create_doe(self, design_type: str) -> None:
|
|
3141
|
+
dialog = DOEDesignDialog(self, design_type)
|
|
3142
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or dialog.result is None:
|
|
3143
|
+
return
|
|
3144
|
+
self._add_table(
|
|
3145
|
+
dialog.result,
|
|
3146
|
+
operation="doe_design",
|
|
3147
|
+
journal_params={"spec": dialog.design_spec()},
|
|
3148
|
+
journal_title=f"Create {design_type} design {dialog.result.name}",
|
|
3149
|
+
)
|
|
3150
|
+
self._log(f"Created {design_type} design with {len(dialog.result)} runs")
|
|
3151
|
+
|
|
3152
|
+
def _create_custom_doe(self) -> None:
|
|
3153
|
+
dialog = CustomDesignDialog(self)
|
|
3154
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or dialog.result is None:
|
|
3155
|
+
return
|
|
3156
|
+
table = dialog.result
|
|
3157
|
+
spec = dict((table.metadata.get("design") or {}).get("spec") or {})
|
|
3158
|
+
self._add_table(
|
|
3159
|
+
table,
|
|
3160
|
+
operation="custom_design",
|
|
3161
|
+
journal_params={"spec": spec},
|
|
3162
|
+
journal_title=f"Create custom design {table.name}",
|
|
3163
|
+
)
|
|
3164
|
+
self._log(f"Created custom design with {len(table)} runs")
|
|
3165
|
+
|
|
3166
|
+
# --------------------------------------------------------------- graphs
|
|
3167
|
+
def _open_plot(self) -> None:
|
|
3168
|
+
table = self._require_table()
|
|
3169
|
+
if table is None:
|
|
3170
|
+
return
|
|
3171
|
+
self._open_plot_for(table)
|
|
3172
|
+
|
|
3173
|
+
def _open_plot_kind(self, kind: str) -> None:
|
|
3174
|
+
table = self._require_table()
|
|
3175
|
+
if table is None:
|
|
3176
|
+
return
|
|
3177
|
+
self._open_plot_for(table, kind)
|
|
3178
|
+
|
|
3179
|
+
def _open_plot_for(self, table: DataTable, default_kind: str | None = None) -> None:
|
|
3180
|
+
dialog = PlotDialog(table, self, default_kind)
|
|
3181
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or dialog.result is None:
|
|
3182
|
+
return
|
|
3183
|
+
self._show_plot_result(table, dialog.result)
|
|
3184
|
+
|
|
3185
|
+
def _column_switcher(self) -> None:
|
|
3186
|
+
page = self._active_document()
|
|
3187
|
+
if page not in self._plot_records:
|
|
3188
|
+
page = self._plot_page_for_table(self._current_table())
|
|
3189
|
+
if page is None:
|
|
3190
|
+
QMessageBox.information(self, "Column Switcher", "Create a graph for this table first.")
|
|
3191
|
+
return
|
|
3192
|
+
self._open_column_switcher(page)
|
|
3193
|
+
|
|
3194
|
+
def _open_column_switcher(self, page) -> None:
|
|
3195
|
+
if page is None or not page.result.plots:
|
|
3196
|
+
QMessageBox.information(self, "Column Switcher", "Create a graph for this table first.")
|
|
3197
|
+
return
|
|
3198
|
+
table = self._page_table(page)
|
|
3199
|
+
if table is None:
|
|
3200
|
+
QMessageBox.information(self, "Column Switcher", "The data table for this graph is no longer available.")
|
|
3201
|
+
return
|
|
3202
|
+
dialog = ColumnSwitcherDialog(table, page.result.plots, self)
|
|
3203
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or not dialog.result:
|
|
3204
|
+
return
|
|
3205
|
+
for spec, params in zip(page.result.plots, dialog.result):
|
|
3206
|
+
spec.params = params
|
|
3207
|
+
page.refresh()
|
|
3208
|
+
self._update_plot_report(page)
|
|
3209
|
+
self._refresh_project_tree()
|
|
3210
|
+
self._log(f"Switched graph columns for {table.name}")
|
|
3211
|
+
|
|
3212
|
+
def _show_plot_result(self, table: DataTable, result: AnalysisResult) -> None:
|
|
3213
|
+
from statstudio.ui.reports.report_view import ReportView
|
|
3214
|
+
|
|
3215
|
+
title = self._next_plot_page_title(table)
|
|
3216
|
+
page_result = AnalysisResult(
|
|
3217
|
+
title=title,
|
|
3218
|
+
analysis_type="plot_page",
|
|
3219
|
+
source_table=table.name,
|
|
3220
|
+
summary=f"Graphs of {table.name}.",
|
|
3221
|
+
)
|
|
3222
|
+
page_result.plots.extend(result.plots)
|
|
3223
|
+
|
|
3224
|
+
def linked(rows, t=table):
|
|
3225
|
+
self._linked_selection(t.name, rows)
|
|
3226
|
+
|
|
3227
|
+
holder: dict = {}
|
|
3228
|
+
|
|
3229
|
+
def report_changed(*_args):
|
|
3230
|
+
page = holder.get("page")
|
|
3231
|
+
if page is not None:
|
|
3232
|
+
self._update_plot_report(page)
|
|
3233
|
+
|
|
3234
|
+
def switch_columns(*_args):
|
|
3235
|
+
page = holder.get("page")
|
|
3236
|
+
if page is not None:
|
|
3237
|
+
self._open_column_switcher(page)
|
|
3238
|
+
|
|
3239
|
+
page = ReportView(
|
|
3240
|
+
page_result,
|
|
3241
|
+
linked_selection=linked,
|
|
3242
|
+
table=table,
|
|
3243
|
+
report_changed=report_changed,
|
|
3244
|
+
column_switcher=switch_columns,
|
|
3245
|
+
create_subset=self._create_subset_from_selection,
|
|
3246
|
+
defer_plots=len(page_result.plots) > 1,
|
|
3247
|
+
)
|
|
3248
|
+
holder["page"] = page
|
|
3249
|
+
self._add_document(page, page_result.title)
|
|
3250
|
+
self.report_views.append(page)
|
|
3251
|
+
record = ReportRecord(
|
|
3252
|
+
title=page_result.title,
|
|
3253
|
+
html="",
|
|
3254
|
+
kind="plot_page",
|
|
3255
|
+
source_table=table.name,
|
|
3256
|
+
params={"plots": len(page_result.plots)},
|
|
3257
|
+
data_hash=self._table_hash(table),
|
|
3258
|
+
)
|
|
3259
|
+
self.project.add_report(record)
|
|
3260
|
+
self._plot_records[page] = record
|
|
3261
|
+
page.report_record = record
|
|
3262
|
+
self._record_plot_code(table, result)
|
|
3263
|
+
self._update_plot_report(page)
|
|
3264
|
+
self._refresh_project_tree()
|
|
3265
|
+
self._log(f"Added graph to {table.name} plot page")
|
|
3266
|
+
|
|
3267
|
+
def _record_plot_code(self, table: DataTable, result: AnalysisResult) -> None:
|
|
3268
|
+
code = scripting.analysis_code(result, "table")
|
|
3269
|
+
cumulative = scripting.analysis_code(result, f"_tables[{scripting.literal(table.name)}]")
|
|
3270
|
+
self._record_entry(
|
|
3271
|
+
kind="analysis",
|
|
3272
|
+
operation="plot",
|
|
3273
|
+
title=result.title or "Graph",
|
|
3274
|
+
source_tables=[table.name],
|
|
3275
|
+
result_table="",
|
|
3276
|
+
params=dict(result.params),
|
|
3277
|
+
code=cumulative,
|
|
3278
|
+
table_code=code,
|
|
3279
|
+
link_table=table,
|
|
3280
|
+
analysis_type="plot",
|
|
3281
|
+
role="analysis",
|
|
3282
|
+
)
|
|
3283
|
+
self._log(f"Recorded graph script for {table.name}")
|
|
3284
|
+
|
|
3285
|
+
def _report_html(self, record: ReportRecord) -> str:
|
|
3286
|
+
if record.kind == "plot_page":
|
|
3287
|
+
for page, plot_record in self._plot_records.items():
|
|
3288
|
+
if plot_record is record:
|
|
3289
|
+
return page.result.to_html(include_plots=True)
|
|
3290
|
+
page_result, _table = self._plot_page_result(record)
|
|
3291
|
+
if page_result is not None:
|
|
3292
|
+
local_filter = (record.params or {}).get("local_filter", "") or ""
|
|
3293
|
+
if local_filter:
|
|
3294
|
+
for plot in page_result.plots:
|
|
3295
|
+
try:
|
|
3296
|
+
data, ids = filtered_plot_data(plot.data, plot.row_ids, local_filter)
|
|
3297
|
+
plot.data = data
|
|
3298
|
+
plot.row_ids = ids
|
|
3299
|
+
except Exception:
|
|
3300
|
+
continue
|
|
3301
|
+
return page_result.to_html(include_plots=True)
|
|
3302
|
+
return record.html
|
|
3303
|
+
|
|
3304
|
+
def _update_plot_report(self, page) -> None:
|
|
3305
|
+
record = self._plot_records.get(page)
|
|
3306
|
+
if record is None:
|
|
3307
|
+
return
|
|
3308
|
+
record.html = ""
|
|
3309
|
+
self._mark_project_dirty()
|
|
3310
|
+
record.params = {
|
|
3311
|
+
"plots": len(page.result.plots),
|
|
3312
|
+
"local_filter": getattr(page, "local_filter", "") or "",
|
|
3313
|
+
"specs": [
|
|
3314
|
+
{
|
|
3315
|
+
"kind": plot.kind,
|
|
3316
|
+
"params": dict(plot.params),
|
|
3317
|
+
"title": plot.title,
|
|
3318
|
+
"row_ids": page.base_row_ids(plot)
|
|
3319
|
+
if page.base_row_ids(plot) is not None
|
|
3320
|
+
else (list(plot.row_ids) if plot.row_ids is not None else None),
|
|
3321
|
+
"include_in_report": plot.include_in_report,
|
|
3322
|
+
}
|
|
3323
|
+
for plot in page.result.plots
|
|
3324
|
+
],
|
|
3325
|
+
}
|
|
3326
|
+
self._store_report_ui(page.result, record.params)
|
|
3327
|
+
|
|
3328
|
+
# ------------------------------------------------------- table editing
|
|
3329
|
+
def _unhide_columns(self) -> None:
|
|
3330
|
+
table = self._require_table()
|
|
3331
|
+
if table is None:
|
|
3332
|
+
return
|
|
3333
|
+
self._mutate_table(table, "Unhide columns", lambda: unhide_all_columns(table))
|
|
3334
|
+
|
|
3335
|
+
def _paste_into_table(self, with_names: bool) -> None:
|
|
3336
|
+
view = self._active_table_view()
|
|
3337
|
+
if view is None:
|
|
3338
|
+
self._require_table()
|
|
3339
|
+
return
|
|
3340
|
+
table = view.table
|
|
3341
|
+
if table.row_filter or table.sort_spec or table.hidden_columns:
|
|
3342
|
+
QMessageBox.information(
|
|
3343
|
+
self,
|
|
3344
|
+
"Paste Data",
|
|
3345
|
+
"Clear row filters, sorting, and hidden columns before pasting into the grid.",
|
|
3346
|
+
)
|
|
3347
|
+
return
|
|
3348
|
+
text = QApplication.clipboard().text()
|
|
3349
|
+
if not text.strip():
|
|
3350
|
+
QMessageBox.information(self, "Paste Data", "The clipboard is empty.")
|
|
3351
|
+
return
|
|
3352
|
+
dialog = PasteDialog(text, self, default_header=with_names)
|
|
3353
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or dialog.result is None:
|
|
3354
|
+
return
|
|
3355
|
+
frame = dialog.result
|
|
3356
|
+
if frame.empty and not len(frame.columns):
|
|
3357
|
+
return
|
|
3358
|
+
header_check = getattr(dialog, "header_check", None)
|
|
3359
|
+
use_names = header_check.isChecked() if header_check is not None else with_names
|
|
3360
|
+
index = view.currentIndex()
|
|
3361
|
+
start_row = index.row() if index.isValid() else 0
|
|
3362
|
+
start_col = index.column() if index.isValid() else 0
|
|
3363
|
+
|
|
3364
|
+
def apply() -> None:
|
|
3365
|
+
existing = list(table.columns)
|
|
3366
|
+
row_count = start_row + len(frame)
|
|
3367
|
+
table.ensure_rows(row_count)
|
|
3368
|
+
row_count = len(table.data)
|
|
3369
|
+
headers: list[str] = []
|
|
3370
|
+
used_names = set(existing)
|
|
3371
|
+
next_column = len(existing) + 1
|
|
3372
|
+
for offset in range(len(frame.columns)):
|
|
3373
|
+
position = start_col + offset
|
|
3374
|
+
if use_names:
|
|
3375
|
+
name = str(frame.columns[offset]).strip() or f"Column {position + 1}"
|
|
3376
|
+
elif position < len(existing):
|
|
3377
|
+
name = existing[position]
|
|
3378
|
+
else:
|
|
3379
|
+
while f"Column {next_column}" in used_names:
|
|
3380
|
+
next_column += 1
|
|
3381
|
+
name = f"Column {next_column}"
|
|
3382
|
+
next_column += 1
|
|
3383
|
+
used_names.add(name)
|
|
3384
|
+
headers.append(name)
|
|
3385
|
+
if use_names:
|
|
3386
|
+
outside = {name for position, name in enumerate(headers) if start_col + position >= len(existing)}
|
|
3387
|
+
for name in outside:
|
|
3388
|
+
if name in existing:
|
|
3389
|
+
raise ValueError(f"Column {name!r} already exists outside the paste range.")
|
|
3390
|
+
for position, name in enumerate(headers):
|
|
3391
|
+
target = start_col + position
|
|
3392
|
+
if target < len(existing) and existing[target] != name:
|
|
3393
|
+
table.rename_column(existing[target], name)
|
|
3394
|
+
for offset, name in enumerate(headers):
|
|
3395
|
+
position = start_col + offset
|
|
3396
|
+
values = [np.nan] * row_count
|
|
3397
|
+
original = None
|
|
3398
|
+
if position < len(table.columns):
|
|
3399
|
+
original = table.data[table.columns[position]].tolist()
|
|
3400
|
+
values = list(original)
|
|
3401
|
+
for row in range(len(frame)):
|
|
3402
|
+
value = frame.iat[row, offset]
|
|
3403
|
+
values[start_row + row] = None if pd.isna(value) else value
|
|
3404
|
+
series = pd.Series(values, index=table.data.index)
|
|
3405
|
+
if position >= len(table.columns):
|
|
3406
|
+
numeric = pd.to_numeric(series, errors="coerce")
|
|
3407
|
+
if numeric.notna().sum() == series.notna().sum():
|
|
3408
|
+
series = numeric
|
|
3409
|
+
elif pd.api.types.is_numeric_dtype(table.data[table.columns[position]].dtype):
|
|
3410
|
+
series = pd.to_numeric(series, errors="coerce")
|
|
3411
|
+
if use_names or position >= len(table.columns):
|
|
3412
|
+
if position < len(table.columns):
|
|
3413
|
+
table.replace_column(table.columns[position], series)
|
|
3414
|
+
else:
|
|
3415
|
+
table.insert_column(name, series, position=position)
|
|
3416
|
+
else:
|
|
3417
|
+
updates = []
|
|
3418
|
+
for row in range(len(frame)):
|
|
3419
|
+
value = frame.iat[row, offset]
|
|
3420
|
+
updates.append((table.data.index[start_row + row], name, "" if pd.isna(value) else value))
|
|
3421
|
+
table.set_cells(updates)
|
|
3422
|
+
|
|
3423
|
+
if self._mutate_table(table, "Paste data", apply):
|
|
3424
|
+
self._log(f"Pasted {len(frame)} row(s) into {table.name}")
|
|
3425
|
+
|
|
3426
|
+
def _find_replace(self) -> None:
|
|
3427
|
+
table = self._require_table()
|
|
3428
|
+
if table is not None:
|
|
3429
|
+
self._find_replace_for(table)
|
|
3430
|
+
|
|
3431
|
+
def _find_replace_for(self, table: DataTable) -> None:
|
|
3432
|
+
dialog = FindReplaceDialog(table, self)
|
|
3433
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or not dialog.result:
|
|
3434
|
+
return
|
|
3435
|
+
columns, find, replace, regex, match_case, whole_cell = dialog.result
|
|
3436
|
+
self._mutate_table(
|
|
3437
|
+
table,
|
|
3438
|
+
"Find and replace",
|
|
3439
|
+
lambda: self._report_replacements(find_replace(table, columns, find, replace, regex=regex, match_case=match_case, whole_cell=whole_cell)),
|
|
3440
|
+
operation="find_replace",
|
|
3441
|
+
journal_params={"columns": columns, "find": find, "replace": replace, "regex": regex, "match_case": match_case, "whole_cell": whole_cell},
|
|
3442
|
+
)
|
|
3443
|
+
|
|
3444
|
+
def _report_replacements(self, count: int) -> None:
|
|
3445
|
+
self._log(f"Replaced {count} cell(s)")
|
|
3446
|
+
|
|
3447
|
+
def _duplicate_selected_rows(self) -> None:
|
|
3448
|
+
widget = self._active_table_view()
|
|
3449
|
+
if widget is not None:
|
|
3450
|
+
self._duplicate_rows(widget.table, widget.selected_row_ids())
|
|
3451
|
+
else:
|
|
3452
|
+
self._require_table()
|
|
3453
|
+
|
|
3454
|
+
def _duplicate_rows(self, table: DataTable, rows: list) -> None:
|
|
3455
|
+
if not rows:
|
|
3456
|
+
QMessageBox.information(self, "Duplicate Rows", "Select one or more rows first.")
|
|
3457
|
+
return
|
|
3458
|
+
self._mutate_table(table, "Duplicate rows", lambda: duplicate_rows(table, rows), operation="duplicate_rows", journal_params={"rows": rows})
|
|
3459
|
+
|
|
3460
|
+
def _delete_selected_rows(self) -> None:
|
|
3461
|
+
widget = self._active_table_view()
|
|
3462
|
+
if widget is not None:
|
|
3463
|
+
self._delete_rows_for(widget.table, widget.selected_row_ids())
|
|
3464
|
+
else:
|
|
3465
|
+
self._require_table()
|
|
3466
|
+
|
|
3467
|
+
def _delete_rows_for(self, table: DataTable, rows: list) -> None:
|
|
3468
|
+
if not rows:
|
|
3469
|
+
QMessageBox.information(self, "Delete Rows", "Select one or more rows first.")
|
|
3470
|
+
return
|
|
3471
|
+
if QMessageBox.question(self, "Delete Rows", f"Delete {len(rows)} row(s)?") != QMessageBox.StandardButton.Yes:
|
|
3472
|
+
return
|
|
3473
|
+
self._mutate_table(table, "Delete rows", lambda: delete_rows(table, rows), operation="delete_rows", journal_params={"rows": rows})
|
|
3474
|
+
|
|
3475
|
+
def _move_column(self, table: DataTable, column: str, offset: int) -> None:
|
|
3476
|
+
self._mutate_table(table, "Move column", lambda: move_column(table, column, offset), operation="move_column", journal_params={"column": column, "offset": offset})
|
|
3477
|
+
|
|
3478
|
+
def _sort_columns(self) -> None:
|
|
3479
|
+
table = self._require_table()
|
|
3480
|
+
if table is None:
|
|
3481
|
+
return
|
|
3482
|
+
dialog = SortDialog(table, self)
|
|
3483
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or dialog.result is None:
|
|
3484
|
+
return
|
|
3485
|
+
view = self.table_views.get(table)
|
|
3486
|
+
if view is not None:
|
|
3487
|
+
view.model().apply_sort(dialog.result)
|
|
3488
|
+
|
|
3489
|
+
def _record_sort(self, table: DataTable, old: list, new: list) -> None:
|
|
3490
|
+
scripts_before = list(table.scripts)
|
|
3491
|
+
entry = self._record_table_operation(
|
|
3492
|
+
operation="sort",
|
|
3493
|
+
title=f"Sort {table.name}",
|
|
3494
|
+
source_tables=[table.name],
|
|
3495
|
+
result_table=table.name,
|
|
3496
|
+
params={"spec": [[column, bool(ascending)] for column, ascending in new]},
|
|
3497
|
+
link_table=table,
|
|
3498
|
+
)
|
|
3499
|
+
scripts_after = list(table.scripts)
|
|
3500
|
+
|
|
3501
|
+
def apply(spec: list) -> None:
|
|
3502
|
+
table.sort_by(spec)
|
|
3503
|
+
table.modified = True
|
|
3504
|
+
self._refresh_table(table)
|
|
3505
|
+
self._update_title()
|
|
3506
|
+
|
|
3507
|
+
def undo() -> None:
|
|
3508
|
+
entry.undone = True
|
|
3509
|
+
table.scripts[:] = scripts_before
|
|
3510
|
+
apply(old)
|
|
3511
|
+
|
|
3512
|
+
def redo() -> None:
|
|
3513
|
+
entry.undone = False
|
|
3514
|
+
table.scripts[:] = scripts_after
|
|
3515
|
+
apply(new)
|
|
3516
|
+
|
|
3517
|
+
self.command_stack.record("Sort", undo, redo)
|
|
3518
|
+
self._mark_project_dirty()
|
|
3519
|
+
self._update_undo_actions()
|
|
3520
|
+
|
|
3521
|
+
# ------------------------------------------------------- extra actions
|
|
3522
|
+
def _load_sample(self, name: str) -> None:
|
|
3523
|
+
try:
|
|
3524
|
+
table = load_sample(name)
|
|
3525
|
+
except Exception as exc:
|
|
3526
|
+
QMessageBox.critical(self, "Sample data", str(exc))
|
|
3527
|
+
return
|
|
3528
|
+
self._add_table(table, operation="sample", journal_params={"sample": name}, journal_title=f"Load sample {name}")
|
|
3529
|
+
self._log(f"Loaded sample data: {name}")
|
|
3530
|
+
|
|
3531
|
+
def _rename_table(self) -> None:
|
|
3532
|
+
table = self._require_table()
|
|
3533
|
+
if table is None:
|
|
3534
|
+
return
|
|
3535
|
+
dialog = RenameTableDialog(table.name, self)
|
|
3536
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
3537
|
+
return
|
|
3538
|
+
self._rename_table_to(table, dialog.result)
|
|
3539
|
+
|
|
3540
|
+
def _rename_table_to(self, table: DataTable, name: str) -> None:
|
|
3541
|
+
old_name = table.name
|
|
3542
|
+
try:
|
|
3543
|
+
self.project.rename_table(table, name)
|
|
3544
|
+
except Exception as exc:
|
|
3545
|
+
QMessageBox.critical(self, "Rename failed", str(exc))
|
|
3546
|
+
return
|
|
3547
|
+
self._record_table_operation(
|
|
3548
|
+
operation="rename_table",
|
|
3549
|
+
title=f"Rename table {old_name}",
|
|
3550
|
+
source_tables=[old_name],
|
|
3551
|
+
result_table=table.name,
|
|
3552
|
+
params={"old": old_name},
|
|
3553
|
+
link_table=table,
|
|
3554
|
+
)
|
|
3555
|
+
old_ref = f"_tables[{scripting.literal(old_name)}]"
|
|
3556
|
+
new_ref = f"_tables[{scripting.literal(table.name)}]"
|
|
3557
|
+
for script in table.scripts:
|
|
3558
|
+
script.code = (script.code or "").replace(old_ref, new_ref)
|
|
3559
|
+
for code in list(self.project.scripts):
|
|
3560
|
+
self.project.scripts[code] = self.project.scripts[code].replace(old_ref, new_ref)
|
|
3561
|
+
for entry in self.project.journal:
|
|
3562
|
+
entry.code = (entry.code or "").replace(old_ref, new_ref)
|
|
3563
|
+
for record in self.project.reports:
|
|
3564
|
+
if record.source_table == old_name:
|
|
3565
|
+
record.source_table = table.name
|
|
3566
|
+
record.code = (record.code or "").replace(old_ref, new_ref)
|
|
3567
|
+
for page in self._plot_pages_for_table(table):
|
|
3568
|
+
title = self._next_plot_page_title(table)
|
|
3569
|
+
page.result.title = title
|
|
3570
|
+
page.result.source_table = table.name
|
|
3571
|
+
page.title_label.setText(title)
|
|
3572
|
+
record = self._plot_records.get(page)
|
|
3573
|
+
if record is not None:
|
|
3574
|
+
record.title = title
|
|
3575
|
+
record.source_table = table.name
|
|
3576
|
+
self._refresh_table(table)
|
|
3577
|
+
self._update_title()
|
|
3578
|
+
|
|
3579
|
+
def _duplicate_table(self) -> None:
|
|
3580
|
+
table = self._require_table()
|
|
3581
|
+
if table is None:
|
|
3582
|
+
return
|
|
3583
|
+
dialog = DuplicateTableDialog(f"{table.name} Copy", self)
|
|
3584
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
3585
|
+
return
|
|
3586
|
+
try:
|
|
3587
|
+
clone = self.project.duplicate_table(table, dialog.result)
|
|
3588
|
+
except Exception as exc:
|
|
3589
|
+
QMessageBox.critical(self, "Duplicate failed", str(exc))
|
|
3590
|
+
return
|
|
3591
|
+
self.open_table_view(clone)
|
|
3592
|
+
self._record_table_operation(
|
|
3593
|
+
operation="duplicate_table",
|
|
3594
|
+
title=f"Duplicate table {table.name}",
|
|
3595
|
+
source_tables=[table.name],
|
|
3596
|
+
result_table=clone.name,
|
|
3597
|
+
params={},
|
|
3598
|
+
link_table=clone,
|
|
3599
|
+
)
|
|
3600
|
+
self._refresh_project_tree()
|
|
3601
|
+
|
|
3602
|
+
def _delete_table(self) -> None:
|
|
3603
|
+
table = self._require_table()
|
|
3604
|
+
if table is None:
|
|
3605
|
+
return
|
|
3606
|
+
self._delete_table_checked(table, confirm=True)
|
|
3607
|
+
|
|
3608
|
+
def _delete_table_now(self, table: DataTable) -> None:
|
|
3609
|
+
self._delete_table_checked(table, confirm=True)
|
|
3610
|
+
|
|
3611
|
+
def _delete_table_checked(self, table: DataTable, confirm: bool) -> None:
|
|
3612
|
+
if len(self.project.tables) <= 1:
|
|
3613
|
+
QMessageBox.information(self, "Delete Table", "At least one table must remain.")
|
|
3614
|
+
return
|
|
3615
|
+
if confirm:
|
|
3616
|
+
if QMessageBox.question(self, "Delete Table", f"Delete table {table.name!r}?") != QMessageBox.StandardButton.Yes:
|
|
3617
|
+
return
|
|
3618
|
+
document = self._table_documents.pop(table, None)
|
|
3619
|
+
self.table_views.pop(table, None)
|
|
3620
|
+
self._table_windows.pop(table, None)
|
|
3621
|
+
for page in self._plot_pages_for_table(table):
|
|
3622
|
+
self._plot_records.pop(page, None)
|
|
3623
|
+
self._close_document(page)
|
|
3624
|
+
if document is not None:
|
|
3625
|
+
if self._last_table_view is document.view:
|
|
3626
|
+
self._last_table_view = None
|
|
3627
|
+
self._close_document(document)
|
|
3628
|
+
name = table.name
|
|
3629
|
+
self.project.reports = [
|
|
3630
|
+
record
|
|
3631
|
+
for record in self.project.reports
|
|
3632
|
+
if not (record.kind == "plot_page" and record.source_table == name)
|
|
3633
|
+
]
|
|
3634
|
+
self.project.remove_table(table)
|
|
3635
|
+
self._record_entry(
|
|
3636
|
+
kind="data_prep",
|
|
3637
|
+
operation="delete_table",
|
|
3638
|
+
title=f"Delete table {name}",
|
|
3639
|
+
source_tables=[name],
|
|
3640
|
+
result_table="",
|
|
3641
|
+
params={"name": name},
|
|
3642
|
+
code=scripting.operation_code("delete_table", {"name": name}, [name], name),
|
|
3643
|
+
link_table=None,
|
|
3644
|
+
)
|
|
3645
|
+
self._mark_project_dirty()
|
|
3646
|
+
self._refresh_project_tree()
|
|
3647
|
+
self._log(f"Deleted table {name}")
|
|
3648
|
+
|
|
3649
|
+
def _delete_document(self, widget: QWidget | None = None) -> None:
|
|
3650
|
+
widget = widget or self._active_document()
|
|
3651
|
+
if widget is None:
|
|
3652
|
+
return
|
|
3653
|
+
record = getattr(widget, "report_record", None)
|
|
3654
|
+
if record is not None:
|
|
3655
|
+
self._delete_report(record)
|
|
3656
|
+
return
|
|
3657
|
+
if isinstance(widget, TableDocument):
|
|
3658
|
+
self._delete_table_now(widget.table)
|
|
3659
|
+
return
|
|
3660
|
+
if isinstance(widget, DataTableView):
|
|
3661
|
+
self._delete_table_now(widget.table)
|
|
3662
|
+
return
|
|
3663
|
+
self._close_document(widget)
|
|
3664
|
+
|
|
3665
|
+
def _delete_report(self, record: ReportRecord) -> None:
|
|
3666
|
+
if all(item is not record for item in self.project.reports):
|
|
3667
|
+
return
|
|
3668
|
+
if QMessageBox.question(self, "Delete Report", f"Delete report {record.title!r}?") != QMessageBox.StandardButton.Yes:
|
|
3669
|
+
return
|
|
3670
|
+
for widget in list(self._windows):
|
|
3671
|
+
if getattr(widget, "report_record", None) is record:
|
|
3672
|
+
self._close_document(widget)
|
|
3673
|
+
for page, rec in list(self._plot_records.items()):
|
|
3674
|
+
if rec is record:
|
|
3675
|
+
self._plot_records.pop(page, None)
|
|
3676
|
+
self._close_document(page)
|
|
3677
|
+
self.project.remove_report(record)
|
|
3678
|
+
self._mark_project_dirty()
|
|
3679
|
+
self._refresh_project_tree()
|
|
3680
|
+
self._log(f"Deleted report {record.title!r}")
|
|
3681
|
+
|
|
3682
|
+
def _mark_project_dirty(self) -> None:
|
|
3683
|
+
self._project_dirty = True
|
|
3684
|
+
self._hash_cache.clear()
|
|
3685
|
+
self._update_title()
|
|
3686
|
+
|
|
3687
|
+
def _standardize_columns(self) -> None:
|
|
3688
|
+
table = self._require_table()
|
|
3689
|
+
if table is None:
|
|
3690
|
+
return
|
|
3691
|
+
dialog = StandardizeDialog(table, self)
|
|
3692
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or not dialog.result:
|
|
3693
|
+
return
|
|
3694
|
+
columns, suffix = dialog.result
|
|
3695
|
+
self._mutate_table(table, "Standardize columns", lambda: standardize_columns(table, columns, suffix), operation="standardize", journal_params={"columns": columns, "suffix": suffix})
|
|
3696
|
+
|
|
3697
|
+
def _label_rows(self, table: DataTable, rows: list) -> None:
|
|
3698
|
+
label, ok = QInputDialog.getText(self, "Label Rows", "Label")
|
|
3699
|
+
if not ok:
|
|
3700
|
+
return
|
|
3701
|
+
self._mutate_table(table, "Label rows", lambda: table.set_labels(rows, label))
|
|
3702
|
+
|
|
3703
|
+
def _record_cell_edit(self, table: DataTable, row_id, column: str, old, new) -> None:
|
|
3704
|
+
scripts_before = list(table.scripts)
|
|
3705
|
+
entry = self._record_table_operation(
|
|
3706
|
+
operation="cell_edit",
|
|
3707
|
+
title=f"Edit {column}",
|
|
3708
|
+
source_tables=[table.name],
|
|
3709
|
+
result_table=table.name,
|
|
3710
|
+
params={"row": row_id, "column": column, "value": new},
|
|
3711
|
+
link_table=table,
|
|
3712
|
+
)
|
|
3713
|
+
scripts_after = list(table.scripts)
|
|
3714
|
+
|
|
3715
|
+
def apply(value) -> None:
|
|
3716
|
+
if row_id in table.data.index and column in table.data.columns:
|
|
3717
|
+
table.data.at[row_id, column] = value
|
|
3718
|
+
table.recompute_formulas()
|
|
3719
|
+
table.modified = True
|
|
3720
|
+
self._refresh_table(table)
|
|
3721
|
+
self._update_title()
|
|
3722
|
+
|
|
3723
|
+
def undo() -> None:
|
|
3724
|
+
entry.undone = True
|
|
3725
|
+
table.scripts[:] = scripts_before
|
|
3726
|
+
apply(old)
|
|
3727
|
+
|
|
3728
|
+
def redo() -> None:
|
|
3729
|
+
entry.undone = False
|
|
3730
|
+
table.scripts[:] = scripts_after
|
|
3731
|
+
apply(new)
|
|
3732
|
+
|
|
3733
|
+
self.command_stack.record(f"Edit {column}", undo, redo)
|
|
3734
|
+
self._mark_project_dirty()
|
|
3735
|
+
self._refresh_plot_page(table)
|
|
3736
|
+
self._update_undo_actions()
|
|
3737
|
+
|
|
3738
|
+
def _design_diagnostics(self) -> None:
|
|
3739
|
+
table = self._require_table()
|
|
3740
|
+
if table is None:
|
|
3741
|
+
return
|
|
3742
|
+
try:
|
|
3743
|
+
result = stats_pkg.doe.design_diagnostics(table)
|
|
3744
|
+
except Exception as exc:
|
|
3745
|
+
QMessageBox.information(self, "Design Diagnostics", str(exc))
|
|
3746
|
+
return
|
|
3747
|
+
self.show_result(result)
|
|
3748
|
+
|
|
3749
|
+
def _assign_blocks(self) -> None:
|
|
3750
|
+
table = self._require_table()
|
|
3751
|
+
if table is None:
|
|
3752
|
+
return
|
|
3753
|
+
count, ok = QInputDialog.getInt(self, "Assign Blocks", "Number of blocks", 2, 1, 100)
|
|
3754
|
+
if not ok:
|
|
3755
|
+
return
|
|
3756
|
+
try:
|
|
3757
|
+
blocked = stats_pkg.doe.assign_blocks(table, count)
|
|
3758
|
+
except Exception as exc:
|
|
3759
|
+
QMessageBox.critical(self, "Assign Blocks", str(exc))
|
|
3760
|
+
return
|
|
3761
|
+
self._add_table(blocked)
|
|
3762
|
+
|
|
3763
|
+
def _fold_over_design(self) -> None:
|
|
3764
|
+
table = self._require_table()
|
|
3765
|
+
if table is None:
|
|
3766
|
+
return
|
|
3767
|
+
try:
|
|
3768
|
+
folded = stats_pkg.doe.fold_over(table)
|
|
3769
|
+
except Exception as exc:
|
|
3770
|
+
QMessageBox.critical(self, "Fold Over", str(exc))
|
|
3771
|
+
return
|
|
3772
|
+
self._add_table(folded)
|
|
3773
|
+
|
|
3774
|
+
def _fold_one_factor(self) -> None:
|
|
3775
|
+
table = self._require_table()
|
|
3776
|
+
if table is None:
|
|
3777
|
+
return
|
|
3778
|
+
factors = stats_pkg.doe.design_factors(table)
|
|
3779
|
+
if not factors:
|
|
3780
|
+
QMessageBox.information(self, "Fold One Factor", "This table has no DOE design metadata.")
|
|
3781
|
+
return
|
|
3782
|
+
name, ok = QInputDialog.getItem(self, "Fold One Factor", "Factor", [factor.name for factor in factors], 0, False)
|
|
3783
|
+
if not ok:
|
|
3784
|
+
return
|
|
3785
|
+
try:
|
|
3786
|
+
folded = stats_pkg.doe.fold_factor(table, name)
|
|
3787
|
+
except Exception as exc:
|
|
3788
|
+
QMessageBox.critical(self, "Fold One Factor", str(exc))
|
|
3789
|
+
return
|
|
3790
|
+
self._add_table(folded)
|
|
3791
|
+
|
|
3792
|
+
def _replicate_design(self) -> None:
|
|
3793
|
+
table = self._require_table()
|
|
3794
|
+
if table is None:
|
|
3795
|
+
return
|
|
3796
|
+
count, ok = QInputDialog.getInt(self, "Replicate Design", "Replicates", 2, 1, 100)
|
|
3797
|
+
if not ok:
|
|
3798
|
+
return
|
|
3799
|
+
try:
|
|
3800
|
+
replicated = stats_pkg.doe.replicate_design(table, count)
|
|
3801
|
+
except Exception as exc:
|
|
3802
|
+
QMessageBox.critical(self, "Replicate Design", str(exc))
|
|
3803
|
+
return
|
|
3804
|
+
self._add_table(replicated)
|
|
3805
|
+
|
|
3806
|
+
def _add_axial_points(self) -> None:
|
|
3807
|
+
table = self._require_table()
|
|
3808
|
+
if table is None:
|
|
3809
|
+
return
|
|
3810
|
+
alpha, ok = QInputDialog.getDouble(self, "Add Axial Points", "Axial distance (coded)", 2.0, 0.1, 100.0, 3)
|
|
3811
|
+
if not ok:
|
|
3812
|
+
return
|
|
3813
|
+
try:
|
|
3814
|
+
augmented = stats_pkg.doe.add_axial_points(table, alpha)
|
|
3815
|
+
except Exception as exc:
|
|
3816
|
+
QMessageBox.critical(self, "Add Axial Points", str(exc))
|
|
3817
|
+
return
|
|
3818
|
+
self._add_table(augmented)
|
|
3819
|
+
|
|
3820
|
+
def _report_composer(self) -> None:
|
|
3821
|
+
dialog = ReportComposerDialog(self.project, self, html_resolver=self._report_html)
|
|
3822
|
+
dialog.exec()
|
|
3823
|
+
|
|
3824
|
+
# ---------------------------------------------------------------- tools
|
|
3825
|
+
def _show_odbc_info(self) -> None:
|
|
3826
|
+
from statstudio.io import odbc
|
|
3827
|
+
|
|
3828
|
+
drivers = odbc.available_drivers()
|
|
3829
|
+
dsns = odbc.available_dsns()
|
|
3830
|
+
text = "Drivers:\n" + ("\n".join(f" {d}" for d in drivers) or " (none)")
|
|
3831
|
+
text += "\n\nDSNs:\n" + ("\n".join(f" {name}: {driver}" for name, driver in dsns.items()) or " (none)")
|
|
3832
|
+
QMessageBox.information(self, "ODBC Drivers and DSNs", text)
|
|
3833
|
+
|
|
3834
|
+
def _statstudio_help(self, topic_id: str | None = None) -> None:
|
|
3835
|
+
from shiboken6 import isValid
|
|
3836
|
+
|
|
3837
|
+
from statstudio.ui.dialogs.help_dialog import FeatureHelpDialog
|
|
3838
|
+
|
|
3839
|
+
dialog = self._help_dialog
|
|
3840
|
+
if dialog is None or not isValid(dialog):
|
|
3841
|
+
try:
|
|
3842
|
+
dialog = FeatureHelpDialog(parent=self, topic_id=topic_id)
|
|
3843
|
+
except Exception as exc:
|
|
3844
|
+
QMessageBox.critical(self, "Help unavailable", str(exc))
|
|
3845
|
+
return
|
|
3846
|
+
dialog.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
|
|
3847
|
+
dialog.destroyed.connect(self._help_dialog_destroyed)
|
|
3848
|
+
self._help_dialog = dialog
|
|
3849
|
+
elif topic_id:
|
|
3850
|
+
dialog.show_topic(topic_id)
|
|
3851
|
+
if dialog.isMinimized():
|
|
3852
|
+
dialog.showNormal()
|
|
3853
|
+
elif not dialog.isVisible():
|
|
3854
|
+
dialog.show()
|
|
3855
|
+
dialog.raise_()
|
|
3856
|
+
dialog.activateWindow()
|
|
3857
|
+
|
|
3858
|
+
def _help_dialog_destroyed(self, *_args) -> None:
|
|
3859
|
+
self._help_dialog = None
|
|
3860
|
+
|
|
3861
|
+
def _about(self) -> None:
|
|
3862
|
+
QMessageBox.about(
|
|
3863
|
+
self,
|
|
3864
|
+
"About StatStudio",
|
|
3865
|
+
f"<h3>StatStudio {__version__}</h3>"
|
|
3866
|
+
"<p>A desktop environment for statistical analysis, visualization, and design of experiments.</p>"
|
|
3867
|
+
f"<p><b>Author:</b> {__author__}</p>"
|
|
3868
|
+
f"<p><b>License:</b> GNU General Public License v3.0 or later ({__license__})</p>"
|
|
3869
|
+
f"<p>{__copyright__}</p>"
|
|
3870
|
+
"<p><b>Capabilities:</b> data import, editing, and formula columns; descriptive and "
|
|
3871
|
+
"inferential statistics; regression, multivariate, time-series, survival, and "
|
|
3872
|
+
"reliability analysis; quality, SPC, and measurement systems; design of experiments "
|
|
3873
|
+
"and optimization; Bayesian modeling; predictive machine learning; interactive "
|
|
3874
|
+
"graphs; reports and export; Python scripting and automation.</p>"
|
|
3875
|
+
"<p><b>Built with:</b> Python 3.11+, PySide6, NumPy, pandas, SciPy, statsmodels, "
|
|
3876
|
+
"scikit-learn, Matplotlib, and Plotly. Optional: PyMC/ArviZ, XGBoost, pyreadstat, "
|
|
3877
|
+
"and xlrd.</p>"
|
|
3878
|
+
"<p>Press F1 for searchable feature help. See the README for optional dependencies "
|
|
3879
|
+
"and current limitations.</p>",
|
|
3880
|
+
)
|
|
3881
|
+
|
|
3882
|
+
def _log(self, message: str) -> None:
|
|
3883
|
+
self.log_view.appendPlainText(message)
|
|
3884
|
+
self.statusBar().showMessage(message, 5000)
|
|
3885
|
+
|
|
3886
|
+
def eventFilter(self, obj, event) -> bool:
|
|
3887
|
+
if obj is self.mdi.viewport():
|
|
3888
|
+
if event.type() == QEvent.Type.DragEnter:
|
|
3889
|
+
self.dragEnterEvent(event)
|
|
3890
|
+
return event.isAccepted()
|
|
3891
|
+
if event.type() == QEvent.Type.Drop:
|
|
3892
|
+
self.dropEvent(event)
|
|
3893
|
+
return True
|
|
3894
|
+
return super().eventFilter(obj, event)
|
|
3895
|
+
|
|
3896
|
+
def dragEnterEvent(self, event) -> None:
|
|
3897
|
+
if event.mimeData().hasUrls():
|
|
3898
|
+
event.acceptProposedAction()
|
|
3899
|
+
else:
|
|
3900
|
+
super().dragEnterEvent(event)
|
|
3901
|
+
|
|
3902
|
+
def _import_paths(self, paths: list[str]) -> None:
|
|
3903
|
+
errors = []
|
|
3904
|
+
for path in paths:
|
|
3905
|
+
try:
|
|
3906
|
+
table = read_file(path)
|
|
3907
|
+
self._add_table(
|
|
3908
|
+
table,
|
|
3909
|
+
operation="import_file",
|
|
3910
|
+
journal_params={"path": path, "sheet_name": 0, "options": None},
|
|
3911
|
+
journal_title=f"Import {Path(path).name}",
|
|
3912
|
+
)
|
|
3913
|
+
self._log(f"Imported {path}")
|
|
3914
|
+
except Exception as exc:
|
|
3915
|
+
errors.append(f"{path}: {exc}")
|
|
3916
|
+
if errors:
|
|
3917
|
+
QMessageBox.critical(self, "Import failed", "\n".join(errors))
|
|
3918
|
+
|
|
3919
|
+
def dropEvent(self, event) -> None:
|
|
3920
|
+
paths = [url.toLocalFile() for url in event.mimeData().urls() if url.isLocalFile()]
|
|
3921
|
+
self._import_paths(paths)
|
|
3922
|
+
event.acceptProposedAction()
|
|
3923
|
+
|
|
3924
|
+
def closeEvent(self, event) -> None:
|
|
3925
|
+
if self.isVisible() and not self._confirm_discard_changes("closing StatStudio"):
|
|
3926
|
+
event.ignore()
|
|
3927
|
+
return
|
|
3928
|
+
help_dialog = self._help_dialog
|
|
3929
|
+
if help_dialog is not None and _qt_alive(help_dialog):
|
|
3930
|
+
help_dialog.close()
|
|
3931
|
+
settings = QSettings("StatStudio", "StatStudio")
|
|
3932
|
+
settings.setValue("geometry_v2", self.saveGeometry())
|
|
3933
|
+
settings.setValue("windowState_v2", self.saveState())
|
|
3934
|
+
event.accept()
|