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,1632 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import tempfile
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from typing import Callable
|
|
9
|
+
|
|
10
|
+
import pandas as pd
|
|
11
|
+
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg, NavigationToolbar2QT
|
|
12
|
+
from matplotlib.widgets import RectangleSelector
|
|
13
|
+
from PySide6.QtCore import Qt, QTimer, Signal
|
|
14
|
+
from PySide6.QtGui import QCursor, QFont, QImage, QKeySequence, QPixmap
|
|
15
|
+
from PySide6.QtWidgets import (
|
|
16
|
+
QApplication,
|
|
17
|
+
QCheckBox,
|
|
18
|
+
QDialog,
|
|
19
|
+
QFileDialog,
|
|
20
|
+
QFrame,
|
|
21
|
+
QHBoxLayout,
|
|
22
|
+
QInputDialog,
|
|
23
|
+
QLabel,
|
|
24
|
+
QLineEdit,
|
|
25
|
+
QMenu,
|
|
26
|
+
QMessageBox,
|
|
27
|
+
QPushButton,
|
|
28
|
+
QScrollArea,
|
|
29
|
+
QSizePolicy,
|
|
30
|
+
QSlider,
|
|
31
|
+
QSpinBox,
|
|
32
|
+
QSplitter,
|
|
33
|
+
QTableWidget,
|
|
34
|
+
QTableWidgetItem,
|
|
35
|
+
QTextBrowser,
|
|
36
|
+
QToolButton,
|
|
37
|
+
QToolTip,
|
|
38
|
+
QVBoxLayout,
|
|
39
|
+
QWidget,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
from statstudio.core import scripting
|
|
43
|
+
from statstudio.io.export import export_dataframe
|
|
44
|
+
from statstudio.plots.registry import build_figure
|
|
45
|
+
from statstudio.stats.results import AnalysisResult, ResultTable, figure_png_base64
|
|
46
|
+
from statstudio.ui import icons
|
|
47
|
+
from statstudio.ui.dialogs.plot_dialog import PlotEditDialog
|
|
48
|
+
from statstudio.ui.plot_interaction import (
|
|
49
|
+
describe_row,
|
|
50
|
+
filtered_plot_data,
|
|
51
|
+
hit_test,
|
|
52
|
+
ids_for_event,
|
|
53
|
+
ids_for_indices,
|
|
54
|
+
ids_in_rect,
|
|
55
|
+
)
|
|
56
|
+
from statstudio.ui.profiler_widget import InteractiveProfilerWidget
|
|
57
|
+
from statstudio.ui.window_controls import WindowControls
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _export_button(parent: QWidget, entries: list[tuple[str, Callable[[], None]]]) -> QToolButton:
|
|
61
|
+
button = QToolButton(parent)
|
|
62
|
+
button.setText("Export")
|
|
63
|
+
icons.set_button_icon(button, "export")
|
|
64
|
+
button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
|
|
65
|
+
button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
|
|
66
|
+
menu = QMenu(button)
|
|
67
|
+
for label, slot in entries:
|
|
68
|
+
action = menu.addAction(label)
|
|
69
|
+
action.triggered.connect(slot)
|
|
70
|
+
button.setMenu(menu)
|
|
71
|
+
return button
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _python_prelude(table_name: str | None, code: str) -> str:
|
|
75
|
+
lines = [scripting.import_prelude()]
|
|
76
|
+
if table_name and "table" in code:
|
|
77
|
+
lines.extend(
|
|
78
|
+
[
|
|
79
|
+
"try:",
|
|
80
|
+
" table",
|
|
81
|
+
"except NameError:",
|
|
82
|
+
" try:",
|
|
83
|
+
" sdk",
|
|
84
|
+
" except NameError as exc:",
|
|
85
|
+
" raise RuntimeError('Provide table = load_table(...) or run in the StatStudio console.') from exc",
|
|
86
|
+
f" table = sdk.dataset({table_name!r}).copy()",
|
|
87
|
+
]
|
|
88
|
+
)
|
|
89
|
+
return "\n".join(lines) + "\n\n"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _frame_tsv(frame: pd.DataFrame) -> str:
|
|
93
|
+
display = frame.copy()
|
|
94
|
+
for column in display.columns:
|
|
95
|
+
if pd.api.types.is_float_dtype(display[column]):
|
|
96
|
+
display[column] = display[column].map(
|
|
97
|
+
lambda value: "" if pd.isna(value) else f"{value:.6g}"
|
|
98
|
+
)
|
|
99
|
+
return display.to_csv(sep="\t", index=False, na_rep="")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class CopyableTableWidget(QTableWidget):
|
|
103
|
+
"""Read-only summary table with selectable cells and clipboard support."""
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
frame: pd.DataFrame,
|
|
108
|
+
full_frame: pd.DataFrame | None = None,
|
|
109
|
+
parent: QWidget | None = None,
|
|
110
|
+
title: str = "Table",
|
|
111
|
+
) -> None:
|
|
112
|
+
super().__init__(len(frame), len(frame.columns), parent)
|
|
113
|
+
self.frame = frame
|
|
114
|
+
self.copy_frame = full_frame if full_frame is not None else frame
|
|
115
|
+
self.title = title
|
|
116
|
+
self.setHorizontalHeaderLabels([str(column) for column in frame.columns])
|
|
117
|
+
self.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectItems)
|
|
118
|
+
self.setSelectionMode(QTableWidget.SelectionMode.ExtendedSelection)
|
|
119
|
+
self.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
|
120
|
+
for row in range(len(frame)):
|
|
121
|
+
for col in range(len(frame.columns)):
|
|
122
|
+
value = frame.iat[row, col]
|
|
123
|
+
if pd.isna(value):
|
|
124
|
+
text = ""
|
|
125
|
+
elif isinstance(value, float):
|
|
126
|
+
text = f"{value:.6g}"
|
|
127
|
+
else:
|
|
128
|
+
text = str(value)
|
|
129
|
+
self.setItem(row, col, QTableWidgetItem(text))
|
|
130
|
+
self.verticalHeader().setVisible(False)
|
|
131
|
+
self.setWordWrap(False)
|
|
132
|
+
self.setSortingEnabled(True)
|
|
133
|
+
self._apply_compact_font()
|
|
134
|
+
self.fit_to_contents()
|
|
135
|
+
|
|
136
|
+
def _apply_compact_font(self) -> None:
|
|
137
|
+
font = QFont(self.font())
|
|
138
|
+
point_size = font.pointSizeF()
|
|
139
|
+
if point_size <= 0:
|
|
140
|
+
point_size = QApplication.font().pointSizeF()
|
|
141
|
+
if point_size > 0:
|
|
142
|
+
font.setPointSizeF(max(8.0, point_size - 0.5))
|
|
143
|
+
self.setFont(font)
|
|
144
|
+
self.horizontalHeader().setFont(font)
|
|
145
|
+
|
|
146
|
+
def fit_to_contents(self) -> None:
|
|
147
|
+
self.resizeColumnsToContents()
|
|
148
|
+
self.resizeRowsToContents()
|
|
149
|
+
height = self.horizontalHeader().height() + 2 * self.frameWidth()
|
|
150
|
+
height += sum(self.rowHeight(row) for row in range(self.rowCount()))
|
|
151
|
+
self.setFixedHeight(height)
|
|
152
|
+
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
|
153
|
+
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
|
154
|
+
|
|
155
|
+
def _selection_text(self) -> str:
|
|
156
|
+
blocks: list[str] = []
|
|
157
|
+
for selection in self.selectedRanges():
|
|
158
|
+
rows = range(selection.topRow(), selection.bottomRow() + 1)
|
|
159
|
+
columns = range(selection.leftColumn(), selection.rightColumn() + 1)
|
|
160
|
+
lines = []
|
|
161
|
+
for row in rows:
|
|
162
|
+
cells = []
|
|
163
|
+
for column in columns:
|
|
164
|
+
item = self.item(row, column)
|
|
165
|
+
cells.append(item.text() if item is not None else "")
|
|
166
|
+
lines.append("\t".join(cells))
|
|
167
|
+
blocks.append("\n".join(lines))
|
|
168
|
+
return "\n".join(blocks)
|
|
169
|
+
|
|
170
|
+
def copy_selection(self) -> None:
|
|
171
|
+
text = self._selection_text()
|
|
172
|
+
if not text:
|
|
173
|
+
return
|
|
174
|
+
QApplication.clipboard().setText(text)
|
|
175
|
+
QToolTip.showText(QCursor.pos(), "Selected cells copied", self)
|
|
176
|
+
|
|
177
|
+
def copy_all(self) -> None:
|
|
178
|
+
QApplication.clipboard().setText(_frame_tsv(self.copy_frame))
|
|
179
|
+
QToolTip.showText(QCursor.pos(), "Table copied", self)
|
|
180
|
+
|
|
181
|
+
def export_csv(self) -> None:
|
|
182
|
+
self._export_table("CSV (*.csv)", ".csv")
|
|
183
|
+
|
|
184
|
+
def export_excel(self) -> None:
|
|
185
|
+
self._export_table("Excel (*.xlsx)", ".xlsx")
|
|
186
|
+
|
|
187
|
+
def _export_table(self, file_filter: str, suffix: str) -> None:
|
|
188
|
+
safe_title = "".join(
|
|
189
|
+
character if character.isalnum() or character in " -_" else "_"
|
|
190
|
+
for character in self.title
|
|
191
|
+
).strip() or "table"
|
|
192
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
193
|
+
self,
|
|
194
|
+
"Export Table",
|
|
195
|
+
f"{safe_title}{suffix}",
|
|
196
|
+
file_filter,
|
|
197
|
+
)
|
|
198
|
+
if not path:
|
|
199
|
+
return
|
|
200
|
+
try:
|
|
201
|
+
export_dataframe(self.copy_frame, path)
|
|
202
|
+
except Exception as exc:
|
|
203
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
204
|
+
|
|
205
|
+
def keyPressEvent(self, event) -> None: # type: ignore[override]
|
|
206
|
+
if event.matches(QKeySequence.StandardKey.Copy):
|
|
207
|
+
self.copy_selection()
|
|
208
|
+
event.accept()
|
|
209
|
+
return
|
|
210
|
+
super().keyPressEvent(event)
|
|
211
|
+
|
|
212
|
+
def build_context_menu(self) -> QMenu:
|
|
213
|
+
menu = QMenu(self)
|
|
214
|
+
copy_selected = menu.addAction("Copy Selected Cells")
|
|
215
|
+
copy_selected.setEnabled(bool(self.selectedRanges()))
|
|
216
|
+
copy_selected.triggered.connect(self.copy_selection)
|
|
217
|
+
copy_all = menu.addAction("Copy Table")
|
|
218
|
+
copy_all.triggered.connect(self.copy_all)
|
|
219
|
+
menu.addSeparator()
|
|
220
|
+
export_csv = menu.addAction("Export Table as CSV...")
|
|
221
|
+
export_csv.triggered.connect(self.export_csv)
|
|
222
|
+
export_excel = menu.addAction("Export Table as Excel...")
|
|
223
|
+
export_excel.triggered.connect(self.export_excel)
|
|
224
|
+
menu.addSeparator()
|
|
225
|
+
select_all = menu.addAction("Select All")
|
|
226
|
+
select_all.triggered.connect(self.selectAll)
|
|
227
|
+
return menu
|
|
228
|
+
|
|
229
|
+
def contextMenuEvent(self, event) -> None: # type: ignore[override]
|
|
230
|
+
self.build_context_menu().exec(event.globalPos())
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class ReportView(QWidget):
|
|
234
|
+
minimize_requested = Signal()
|
|
235
|
+
maximize_requested = Signal()
|
|
236
|
+
delete_requested = Signal()
|
|
237
|
+
|
|
238
|
+
def __init__(
|
|
239
|
+
self,
|
|
240
|
+
result: AnalysisResult,
|
|
241
|
+
rerun: Callable[[], None] | None = None,
|
|
242
|
+
parent: QWidget | None = None,
|
|
243
|
+
linked_selection: Callable[[list], None] | None = None,
|
|
244
|
+
code: str = "",
|
|
245
|
+
table=None,
|
|
246
|
+
report_changed: Callable[[], None] | None = None,
|
|
247
|
+
column_switcher: Callable[[], None] | None = None,
|
|
248
|
+
local_filter: str = "",
|
|
249
|
+
create_subset: Callable[[], None] | None = None,
|
|
250
|
+
defer_plots: bool = False,
|
|
251
|
+
) -> None:
|
|
252
|
+
super().__init__(parent)
|
|
253
|
+
self.result = result
|
|
254
|
+
self.rerun = rerun
|
|
255
|
+
self.linked_selection = linked_selection
|
|
256
|
+
self.code = code
|
|
257
|
+
self.table = table
|
|
258
|
+
self.report_changed = report_changed
|
|
259
|
+
self.column_switcher = column_switcher
|
|
260
|
+
self.local_filter = local_filter
|
|
261
|
+
self.create_subset = create_subset
|
|
262
|
+
self.defer_plots = defer_plots
|
|
263
|
+
self._render_queue: list[dict] = []
|
|
264
|
+
self._render_timer = QTimer(self)
|
|
265
|
+
self._render_timer.setSingleShot(True)
|
|
266
|
+
self._render_timer.setInterval(0)
|
|
267
|
+
self._render_timer.timeout.connect(self._render_next_queued)
|
|
268
|
+
self._figures = []
|
|
269
|
+
self._plot_views: list[dict] = []
|
|
270
|
+
self._plot_base: dict[int, tuple] = {}
|
|
271
|
+
self._last_selection: tuple[str, list] | None = None
|
|
272
|
+
self._table_sections: dict[int, QWidget] = {}
|
|
273
|
+
self.filter_edit: QLineEdit | None = None
|
|
274
|
+
layout = QVBoxLayout(self)
|
|
275
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
276
|
+
layout.setSpacing(0)
|
|
277
|
+
|
|
278
|
+
self.header = QFrame()
|
|
279
|
+
self.header.setObjectName("documentHeader")
|
|
280
|
+
toolbar = QHBoxLayout(self.header)
|
|
281
|
+
toolbar.setContentsMargins(9, 4, 6, 4)
|
|
282
|
+
toolbar.setSpacing(7)
|
|
283
|
+
self.title_label = QLabel(result.title)
|
|
284
|
+
self.title_label.setObjectName("documentTitle")
|
|
285
|
+
toolbar.addWidget(self.title_label)
|
|
286
|
+
help_button = QPushButton("Help")
|
|
287
|
+
icons.set_button_icon(help_button, "help")
|
|
288
|
+
help_button.setProperty("quiet", "true")
|
|
289
|
+
help_button.setToolTip("Open help for this analysis")
|
|
290
|
+
help_button.clicked.connect(self._show_help)
|
|
291
|
+
toolbar.addWidget(help_button)
|
|
292
|
+
if any(plot.data is not None and plot.kind != "profiler" for plot in result.plots):
|
|
293
|
+
self.filter_edit = QLineEdit()
|
|
294
|
+
self.filter_edit.setPlaceholderText('Filter plots, e.g. col("x") > 5')
|
|
295
|
+
self.filter_edit.setClearButtonEnabled(True)
|
|
296
|
+
self.filter_edit.setText(local_filter)
|
|
297
|
+
self.filter_edit.returnPressed.connect(self._apply_filter_from_edit)
|
|
298
|
+
toolbar.addWidget(self.filter_edit, 1)
|
|
299
|
+
apply_button = QPushButton("Apply Filter")
|
|
300
|
+
apply_button.clicked.connect(self._apply_filter_from_edit)
|
|
301
|
+
toolbar.addWidget(apply_button)
|
|
302
|
+
clear_button = QPushButton("Clear")
|
|
303
|
+
clear_button.setProperty("quiet", "true")
|
|
304
|
+
clear_button.clicked.connect(lambda: self.set_local_filter(""))
|
|
305
|
+
toolbar.addWidget(clear_button)
|
|
306
|
+
toolbar.addStretch(1)
|
|
307
|
+
if rerun:
|
|
308
|
+
rerun_button = QPushButton("Re-run")
|
|
309
|
+
rerun_button.clicked.connect(rerun)
|
|
310
|
+
toolbar.addWidget(rerun_button)
|
|
311
|
+
if column_switcher:
|
|
312
|
+
switch_button = QPushButton("Column Switcher")
|
|
313
|
+
switch_button.clicked.connect(column_switcher)
|
|
314
|
+
toolbar.addWidget(switch_button)
|
|
315
|
+
if getattr(result, "deferred_plots", None):
|
|
316
|
+
add_plot_button = QPushButton("Add Plot...")
|
|
317
|
+
add_plot_button.setToolTip("Add another diagnostic plot from this analysis")
|
|
318
|
+
add_plot_button.clicked.connect(self._add_deferred_plot)
|
|
319
|
+
toolbar.addWidget(add_plot_button)
|
|
320
|
+
if code:
|
|
321
|
+
copy_button = QPushButton("Copy Python")
|
|
322
|
+
copy_button.clicked.connect(self.copy_python)
|
|
323
|
+
toolbar.addWidget(copy_button)
|
|
324
|
+
save_button = QPushButton("Save Python")
|
|
325
|
+
save_button.clicked.connect(self.export_python)
|
|
326
|
+
toolbar.addWidget(save_button)
|
|
327
|
+
toolbar.addWidget(
|
|
328
|
+
_export_button(
|
|
329
|
+
self,
|
|
330
|
+
[
|
|
331
|
+
("HTML...", self.export_html),
|
|
332
|
+
("Interactive HTML...", self.export_interactive_html),
|
|
333
|
+
("PDF...", self.export_pdf),
|
|
334
|
+
("Plots...", self.export_plots),
|
|
335
|
+
("Word...", self.export_word),
|
|
336
|
+
],
|
|
337
|
+
)
|
|
338
|
+
)
|
|
339
|
+
self.window_controls = WindowControls()
|
|
340
|
+
self.window_controls.minimize_requested.connect(self.minimize_requested.emit)
|
|
341
|
+
self.window_controls.maximize_requested.connect(self.maximize_requested.emit)
|
|
342
|
+
self.window_controls.delete_requested.connect(self.delete_requested.emit)
|
|
343
|
+
toolbar.addWidget(self.window_controls)
|
|
344
|
+
layout.addWidget(self.header)
|
|
345
|
+
|
|
346
|
+
self.scroll = QScrollArea()
|
|
347
|
+
self.scroll.setWidgetResizable(True)
|
|
348
|
+
self.content = QWidget()
|
|
349
|
+
self.content_layout = QVBoxLayout(self.content)
|
|
350
|
+
self.content_layout.setContentsMargins(16, 10, 16, 20)
|
|
351
|
+
self.content_layout.setSpacing(8)
|
|
352
|
+
self.scroll.setWidget(self.content)
|
|
353
|
+
layout.addWidget(self.scroll, 1)
|
|
354
|
+
self._render()
|
|
355
|
+
if local_filter:
|
|
356
|
+
self.set_local_filter(local_filter, silent=True)
|
|
357
|
+
from statstudio.ui.dialogs.help_topics import analysis_help_topic, install_context_help
|
|
358
|
+
|
|
359
|
+
install_context_help(self, analysis_help_topic(result))
|
|
360
|
+
|
|
361
|
+
def _show_help(self) -> None:
|
|
362
|
+
from statstudio.ui.dialogs.help_topics import analysis_help_topic, open_help
|
|
363
|
+
|
|
364
|
+
open_help(self, analysis_help_topic(self.result))
|
|
365
|
+
|
|
366
|
+
def _apply_filter_from_edit(self) -> None:
|
|
367
|
+
if self.filter_edit is not None:
|
|
368
|
+
self.set_local_filter(self.filter_edit.text())
|
|
369
|
+
|
|
370
|
+
def set_local_filter(self, expression: str, silent: bool = False) -> bool:
|
|
371
|
+
expression = (expression or "").strip()
|
|
372
|
+
prepared: list[tuple] = []
|
|
373
|
+
errors: list[str] = []
|
|
374
|
+
for plot in self.result.plots:
|
|
375
|
+
if plot.kind == "profiler":
|
|
376
|
+
continue
|
|
377
|
+
base = self._plot_base.get(id(plot))
|
|
378
|
+
if base is None:
|
|
379
|
+
continue
|
|
380
|
+
try:
|
|
381
|
+
data, ids = filtered_plot_data(base[0], base[1], expression)
|
|
382
|
+
except Exception as exc:
|
|
383
|
+
errors.append(f"{plot.title or plot.kind.title()}: {exc}")
|
|
384
|
+
continue
|
|
385
|
+
prepared.append((plot, data, ids))
|
|
386
|
+
if errors:
|
|
387
|
+
if not silent:
|
|
388
|
+
QMessageBox.critical(self, "Filter", "\n".join(errors))
|
|
389
|
+
return False
|
|
390
|
+
for plot, data, ids in prepared:
|
|
391
|
+
plot.data = data
|
|
392
|
+
plot.row_ids = ids
|
|
393
|
+
self.local_filter = expression
|
|
394
|
+
if self.filter_edit is not None and self.filter_edit.text() != expression:
|
|
395
|
+
self.filter_edit.setText(expression)
|
|
396
|
+
self.refresh()
|
|
397
|
+
if self.report_changed is not None:
|
|
398
|
+
self.report_changed()
|
|
399
|
+
return True
|
|
400
|
+
|
|
401
|
+
def base_row_ids(self, plot) -> list | None:
|
|
402
|
+
base = self._plot_base.get(id(plot))
|
|
403
|
+
if base is None or base[1] is None:
|
|
404
|
+
return None
|
|
405
|
+
return list(base[1])
|
|
406
|
+
|
|
407
|
+
def _render(self) -> None:
|
|
408
|
+
if self.result.source_table:
|
|
409
|
+
source = QLabel(f"Data table: {self.result.source_table}")
|
|
410
|
+
source.setStyleSheet("color:#5a6270;")
|
|
411
|
+
self.content_layout.addWidget(source)
|
|
412
|
+
if self.result.summary:
|
|
413
|
+
summary = QLabel(self.result.summary)
|
|
414
|
+
summary.setWordWrap(True)
|
|
415
|
+
summary.setStyleSheet("background:#f4f6f8;border-left:4px solid #3c78b4;padding:8px;")
|
|
416
|
+
summary.setTextInteractionFlags(
|
|
417
|
+
Qt.TextInteractionFlag.TextSelectableByMouse
|
|
418
|
+
| Qt.TextInteractionFlag.TextSelectableByKeyboard
|
|
419
|
+
)
|
|
420
|
+
summary.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
|
|
421
|
+
formula = self._formula_from_summary(self.result.summary)
|
|
422
|
+
summary.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
|
423
|
+
summary.customContextMenuRequested.connect(
|
|
424
|
+
lambda position, label=summary, text=formula: self._show_summary_context_menu(
|
|
425
|
+
label, position, text
|
|
426
|
+
)
|
|
427
|
+
)
|
|
428
|
+
self._append_content(summary)
|
|
429
|
+
self._table_sections = {}
|
|
430
|
+
for index, table in enumerate(self.result.tables):
|
|
431
|
+
self._add_table(table, index)
|
|
432
|
+
for plot in self.result.plots:
|
|
433
|
+
self._add_plot(plot, defer=self.defer_plots)
|
|
434
|
+
if self.result.notes:
|
|
435
|
+
note = QLabel(self.result.notes)
|
|
436
|
+
note.setWordWrap(True)
|
|
437
|
+
note.setStyleSheet("color:#5a6270;")
|
|
438
|
+
self._append_content(note)
|
|
439
|
+
self.content_layout.addStretch(1)
|
|
440
|
+
|
|
441
|
+
@staticmethod
|
|
442
|
+
def _formula_from_summary(summary: str) -> str:
|
|
443
|
+
marker = "Formula:"
|
|
444
|
+
if marker not in summary:
|
|
445
|
+
return ""
|
|
446
|
+
return summary.split(marker, 1)[1].strip()
|
|
447
|
+
|
|
448
|
+
def build_summary_context_menu(self, label: QLabel, formula: str) -> QMenu:
|
|
449
|
+
menu = QMenu(label)
|
|
450
|
+
menu.addAction(
|
|
451
|
+
"Copy Summary",
|
|
452
|
+
lambda: QApplication.clipboard().setText(self.result.summary),
|
|
453
|
+
)
|
|
454
|
+
if formula:
|
|
455
|
+
menu.addAction("Copy Formula", lambda: self._copy_formula(formula))
|
|
456
|
+
return menu
|
|
457
|
+
|
|
458
|
+
def _show_summary_context_menu(self, label: QLabel, position, formula: str) -> None:
|
|
459
|
+
self.build_summary_context_menu(label, formula).exec(label.mapToGlobal(position))
|
|
460
|
+
|
|
461
|
+
def _copy_formula(self, formula: str) -> None:
|
|
462
|
+
QApplication.clipboard().setText(formula)
|
|
463
|
+
QToolTip.showText(QCursor.pos(), "Formula copied", self)
|
|
464
|
+
|
|
465
|
+
def _append_content(self, widget: QWidget) -> None:
|
|
466
|
+
if self.content_layout.count() and self.content_layout.itemAt(self.content_layout.count() - 1).spacerItem() is not None:
|
|
467
|
+
self.content_layout.insertWidget(self.content_layout.count() - 1, widget)
|
|
468
|
+
else:
|
|
469
|
+
self.content_layout.addWidget(widget)
|
|
470
|
+
|
|
471
|
+
def refresh(self) -> None:
|
|
472
|
+
"""Rebuild the report content from the current result (e.g. after switching columns)."""
|
|
473
|
+
self._render_timer.stop()
|
|
474
|
+
self._render_queue = []
|
|
475
|
+
for figure, _canvas in self._figures:
|
|
476
|
+
try:
|
|
477
|
+
import matplotlib.pyplot as plt
|
|
478
|
+
|
|
479
|
+
plt.close(figure)
|
|
480
|
+
except Exception:
|
|
481
|
+
pass
|
|
482
|
+
while self.content_layout.count():
|
|
483
|
+
item = self.content_layout.takeAt(0)
|
|
484
|
+
widget = item.widget()
|
|
485
|
+
if widget is not None:
|
|
486
|
+
widget.deleteLater()
|
|
487
|
+
self._figures = []
|
|
488
|
+
self._plot_views = []
|
|
489
|
+
self._render()
|
|
490
|
+
|
|
491
|
+
def add_result_plots(self, result: AnalysisResult) -> None:
|
|
492
|
+
for plot in result.plots:
|
|
493
|
+
self.result.plots.append(plot)
|
|
494
|
+
self._add_plot(plot)
|
|
495
|
+
if self.report_changed is not None:
|
|
496
|
+
self.report_changed()
|
|
497
|
+
|
|
498
|
+
def _add_table(self, table: ResultTable, index: int) -> None:
|
|
499
|
+
section = QWidget()
|
|
500
|
+
section_layout = QVBoxLayout(section)
|
|
501
|
+
section_layout.setContentsMargins(0, 0, 0, 0)
|
|
502
|
+
section_layout.setSpacing(4)
|
|
503
|
+
heading = QLabel(table.title)
|
|
504
|
+
heading.setFont(QFont("", 11, QFont.Weight.Bold))
|
|
505
|
+
section_layout.addWidget(heading)
|
|
506
|
+
if table.notes:
|
|
507
|
+
note = QLabel(table.notes)
|
|
508
|
+
note.setWordWrap(True)
|
|
509
|
+
note.setStyleSheet("color:#5a6270;")
|
|
510
|
+
section_layout.addWidget(note)
|
|
511
|
+
|
|
512
|
+
frame = table.frame
|
|
513
|
+
if frame is None or frame.empty:
|
|
514
|
+
empty = QLabel("No rows.")
|
|
515
|
+
empty.setStyleSheet("color:#777777;")
|
|
516
|
+
section_layout.addWidget(empty)
|
|
517
|
+
else:
|
|
518
|
+
display = frame.head(500)
|
|
519
|
+
widget = CopyableTableWidget(
|
|
520
|
+
display,
|
|
521
|
+
full_frame=frame,
|
|
522
|
+
title=table.title,
|
|
523
|
+
)
|
|
524
|
+
section_layout.addWidget(widget)
|
|
525
|
+
if len(frame) > len(display):
|
|
526
|
+
note = QLabel(
|
|
527
|
+
f"Showing first {len(display)} of {len(frame)} rows in this view; "
|
|
528
|
+
"right-click the table to copy or export the full data."
|
|
529
|
+
)
|
|
530
|
+
note.setStyleSheet("color:#777777;")
|
|
531
|
+
section_layout.addWidget(note)
|
|
532
|
+
|
|
533
|
+
self._table_sections[index] = section
|
|
534
|
+
self._append_content(section)
|
|
535
|
+
|
|
536
|
+
def _table_name(self) -> str:
|
|
537
|
+
return getattr(self.table, "name", "") or getattr(self.result, "source_table", "") or ""
|
|
538
|
+
|
|
539
|
+
def _plot_extents(self, plot) -> tuple[list, list]:
|
|
540
|
+
base = self._plot_base.get(id(plot))
|
|
541
|
+
if base is not None:
|
|
542
|
+
return base[0], (base[1] if base[1] is not None else [])
|
|
543
|
+
data = plot.data
|
|
544
|
+
if data is None:
|
|
545
|
+
return [], []
|
|
546
|
+
return data, (list(plot.row_ids) if plot.row_ids is not None else [])
|
|
547
|
+
|
|
548
|
+
def _add_plot(self, plot, *, defer: bool = False) -> None:
|
|
549
|
+
if plot.data is not None and plot.kind != "profiler" and id(plot) not in self._plot_base:
|
|
550
|
+
self._plot_base[id(plot)] = (
|
|
551
|
+
plot.data.copy(deep=False),
|
|
552
|
+
list(plot.row_ids) if plot.row_ids is not None else None,
|
|
553
|
+
)
|
|
554
|
+
outer = QWidget()
|
|
555
|
+
outer_layout = QVBoxLayout(outer)
|
|
556
|
+
outer_layout.setContentsMargins(0, 0, 0, 0)
|
|
557
|
+
outer_layout.setSpacing(0)
|
|
558
|
+
heading_row = QHBoxLayout()
|
|
559
|
+
toggle = QToolButton()
|
|
560
|
+
toggle.setText("-" if plot.include_in_report else "+")
|
|
561
|
+
toggle.setToolTip("Collapse or expand this plot")
|
|
562
|
+
title = QLabel(plot.title or plot.kind.title())
|
|
563
|
+
title.setFont(QFont("", 11, QFont.Weight.Bold))
|
|
564
|
+
heading_row.addWidget(toggle)
|
|
565
|
+
heading_row.addWidget(title)
|
|
566
|
+
heading_row.addStretch(1)
|
|
567
|
+
|
|
568
|
+
bins_spin = QSpinBox()
|
|
569
|
+
bins_spin.setRange(0, 500)
|
|
570
|
+
bins_spin.setToolTip("Histogram bins (0 = automatic)")
|
|
571
|
+
bins_slider = QSlider(Qt.Orientation.Horizontal)
|
|
572
|
+
bins_slider.setRange(0, 500)
|
|
573
|
+
bins_slider.setFixedWidth(110)
|
|
574
|
+
bins_label = QLabel("Bins")
|
|
575
|
+
heading_row.addWidget(bins_label)
|
|
576
|
+
heading_row.addWidget(bins_spin)
|
|
577
|
+
heading_row.addWidget(bins_slider)
|
|
578
|
+
|
|
579
|
+
bubble_label = QLabel("Bubble size")
|
|
580
|
+
bubble_slider = QSlider(Qt.Orientation.Horizontal)
|
|
581
|
+
bubble_slider.setRange(25, 400)
|
|
582
|
+
bubble_slider.setSingleStep(5)
|
|
583
|
+
bubble_slider.setFixedWidth(90)
|
|
584
|
+
bubble_slider.setToolTip("Bubble size scale")
|
|
585
|
+
bubble_value = QLabel("100%")
|
|
586
|
+
heading_row.addWidget(bubble_label)
|
|
587
|
+
heading_row.addWidget(bubble_slider)
|
|
588
|
+
heading_row.addWidget(bubble_value)
|
|
589
|
+
|
|
590
|
+
brush_button = QToolButton()
|
|
591
|
+
brush_button.setText("Brush")
|
|
592
|
+
brush_button.setCheckable(True)
|
|
593
|
+
brush_button.setToolTip("Drag a box on the plot to select its points")
|
|
594
|
+
heading_row.addWidget(brush_button)
|
|
595
|
+
reset_button = QPushButton("Reset View")
|
|
596
|
+
reset_button.setToolTip("Restore the default 3D camera")
|
|
597
|
+
heading_row.addWidget(reset_button)
|
|
598
|
+
edit_button = QPushButton("Edit")
|
|
599
|
+
edit_button.setToolTip("Type axis ranges, scales, labels and other plot settings")
|
|
600
|
+
heading_row.addWidget(edit_button)
|
|
601
|
+
outer_layout.addLayout(heading_row)
|
|
602
|
+
|
|
603
|
+
body = QWidget()
|
|
604
|
+
details = QWidget()
|
|
605
|
+
details_layout = QVBoxLayout(details)
|
|
606
|
+
details_layout.setContentsMargins(6, 4, 6, 4)
|
|
607
|
+
details_layout.setSpacing(4)
|
|
608
|
+
rows_label = QLabel()
|
|
609
|
+
columns_label = QLabel()
|
|
610
|
+
columns_label.setWordWrap(True)
|
|
611
|
+
selection_label = QLabel()
|
|
612
|
+
hint_label = QLabel()
|
|
613
|
+
hint_label.setWordWrap(True)
|
|
614
|
+
hint_label.setStyleSheet("color:#5a6270;")
|
|
615
|
+
y1_points_check = QCheckBox("Y1 points")
|
|
616
|
+
y1_line_check = QCheckBox("Y1 line")
|
|
617
|
+
y1_row = QHBoxLayout()
|
|
618
|
+
y1_row.addWidget(y1_points_check)
|
|
619
|
+
y1_row.addWidget(y1_line_check)
|
|
620
|
+
y1_row.addStretch(1)
|
|
621
|
+
y2_points_check = QCheckBox("Y2 points")
|
|
622
|
+
y2_line_check = QCheckBox("Y2 line")
|
|
623
|
+
y2_row = QHBoxLayout()
|
|
624
|
+
y2_row.addWidget(y2_points_check)
|
|
625
|
+
y2_row.addWidget(y2_line_check)
|
|
626
|
+
y2_row.addStretch(1)
|
|
627
|
+
subset_button = QPushButton("Create Subset")
|
|
628
|
+
subset_button.setToolTip("Create a new table from the rows selected in this plot")
|
|
629
|
+
subset_button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
|
630
|
+
subset_row = QHBoxLayout()
|
|
631
|
+
subset_row.addWidget(subset_button)
|
|
632
|
+
subset_row.addStretch(1)
|
|
633
|
+
details_layout.addWidget(rows_label)
|
|
634
|
+
details_layout.addWidget(columns_label)
|
|
635
|
+
details_layout.addWidget(selection_label)
|
|
636
|
+
details_layout.addWidget(hint_label)
|
|
637
|
+
details_layout.addLayout(y1_row)
|
|
638
|
+
details_layout.addLayout(y2_row)
|
|
639
|
+
details_layout.addLayout(subset_row)
|
|
640
|
+
details_layout.addStretch(1)
|
|
641
|
+
splitter = QSplitter(Qt.Orientation.Horizontal)
|
|
642
|
+
splitter.setChildrenCollapsible(False)
|
|
643
|
+
splitter.addWidget(body)
|
|
644
|
+
splitter.addWidget(details)
|
|
645
|
+
splitter.setStretchFactor(0, 1)
|
|
646
|
+
splitter.setStretchFactor(1, 0)
|
|
647
|
+
splitter.setSizes([520, 260])
|
|
648
|
+
outer_layout.addWidget(splitter)
|
|
649
|
+
|
|
650
|
+
entry = {
|
|
651
|
+
"plot": plot,
|
|
652
|
+
"figure": None,
|
|
653
|
+
"canvas": None,
|
|
654
|
+
"body": body,
|
|
655
|
+
"details": details,
|
|
656
|
+
"splitter": splitter,
|
|
657
|
+
"toggle": toggle,
|
|
658
|
+
"title_label": title,
|
|
659
|
+
"selector": None,
|
|
660
|
+
"brush_button": brush_button,
|
|
661
|
+
"reset_button": reset_button,
|
|
662
|
+
"edit_button": edit_button,
|
|
663
|
+
"bins_spin": bins_spin,
|
|
664
|
+
"bins_slider": bins_slider,
|
|
665
|
+
"bins_label": bins_label,
|
|
666
|
+
"bubble_slider": bubble_slider,
|
|
667
|
+
"bubble_label": bubble_label,
|
|
668
|
+
"bubble_value": bubble_value,
|
|
669
|
+
"y1_points_check": y1_points_check,
|
|
670
|
+
"y1_line_check": y1_line_check,
|
|
671
|
+
"y2_points_check": y2_points_check,
|
|
672
|
+
"y2_line_check": y2_line_check,
|
|
673
|
+
"rows_label": rows_label,
|
|
674
|
+
"columns_label": columns_label,
|
|
675
|
+
"selection_label": selection_label,
|
|
676
|
+
"hint_label": hint_label,
|
|
677
|
+
"subset_button": subset_button,
|
|
678
|
+
"selected_count": 0,
|
|
679
|
+
"syncing": False,
|
|
680
|
+
"_selection_artists": [],
|
|
681
|
+
}
|
|
682
|
+
entry["bins_timer"] = QTimer(self)
|
|
683
|
+
entry["bins_timer"].setSingleShot(True)
|
|
684
|
+
entry["bins_timer"].setInterval(150)
|
|
685
|
+
entry["bins_timer"].timeout.connect(lambda e=entry: self._apply_bins(e))
|
|
686
|
+
entry["bubble_timer"] = QTimer(self)
|
|
687
|
+
entry["bubble_timer"].setSingleShot(True)
|
|
688
|
+
entry["bubble_timer"].setInterval(120)
|
|
689
|
+
entry["bubble_timer"].timeout.connect(lambda e=entry: self._apply_bubble_scale(e))
|
|
690
|
+
|
|
691
|
+
brush_button.toggled.connect(lambda checked, e=entry: self._toggle_brush(e, checked))
|
|
692
|
+
reset_button.clicked.connect(lambda _=False, e=entry: self._reset_3d(e))
|
|
693
|
+
edit_button.clicked.connect(lambda _=False, p=plot: self._edit_plot(p))
|
|
694
|
+
toggle.clicked.connect(lambda _=False, p=plot, b=body, t=toggle: self._toggle_plot(p, b, t))
|
|
695
|
+
bins_spin.valueChanged.connect(lambda value, e=entry: self._bin_control_changed(e, value, source="spin"))
|
|
696
|
+
bins_slider.valueChanged.connect(lambda value, e=entry: self._bin_control_changed(e, value, source="slider"))
|
|
697
|
+
bubble_slider.valueChanged.connect(lambda value, e=entry: self._bubble_control_changed(e, value))
|
|
698
|
+
y1_points_check.toggled.connect(lambda _checked, e=entry: self._y1_control_changed(e))
|
|
699
|
+
y1_line_check.toggled.connect(lambda _checked, e=entry: self._y1_control_changed(e))
|
|
700
|
+
y2_points_check.toggled.connect(lambda _checked, e=entry: self._y2_control_changed(e))
|
|
701
|
+
y2_line_check.toggled.connect(lambda _checked, e=entry: self._y2_control_changed(e))
|
|
702
|
+
if self.create_subset is not None:
|
|
703
|
+
subset_button.clicked.connect(lambda _=False, p=plot: self._request_subset(p))
|
|
704
|
+
else:
|
|
705
|
+
subset_button.hide()
|
|
706
|
+
|
|
707
|
+
self._append_content(outer)
|
|
708
|
+
self._plot_views.append(entry)
|
|
709
|
+
if defer:
|
|
710
|
+
placeholder = QLabel("Rendering plot...")
|
|
711
|
+
placeholder.setStyleSheet("color:#5a6270; padding:12px;")
|
|
712
|
+
body_layout = QVBoxLayout(body)
|
|
713
|
+
body_layout.setContentsMargins(0, 0, 0, 0)
|
|
714
|
+
body_layout.addWidget(placeholder)
|
|
715
|
+
for key in ("bins_label", "bins_spin", "bins_slider", "bubble_label", "bubble_slider", "bubble_value"):
|
|
716
|
+
entry[key].hide()
|
|
717
|
+
for key in ("brush_button", "reset_button", "y1_points_check", "y1_line_check", "y2_points_check", "y2_line_check"):
|
|
718
|
+
entry[key].hide()
|
|
719
|
+
self._render_queue.append(entry)
|
|
720
|
+
self._render_timer.start()
|
|
721
|
+
else:
|
|
722
|
+
self._render_plot_body(entry)
|
|
723
|
+
self._update_details(entry)
|
|
724
|
+
|
|
725
|
+
def _render_next_queued(self) -> None:
|
|
726
|
+
while self._render_queue:
|
|
727
|
+
entry = self._render_queue.pop(0)
|
|
728
|
+
if entry not in self._plot_views:
|
|
729
|
+
continue
|
|
730
|
+
self._render_plot_body(entry)
|
|
731
|
+
self._update_details(entry)
|
|
732
|
+
if self._render_queue:
|
|
733
|
+
self._render_timer.start()
|
|
734
|
+
return
|
|
735
|
+
|
|
736
|
+
def _render_plot_body(self, entry: dict) -> None:
|
|
737
|
+
plot = entry["plot"]
|
|
738
|
+
body = entry["body"]
|
|
739
|
+
brush_was_active = entry["brush_button"].isChecked()
|
|
740
|
+
layout = body.layout()
|
|
741
|
+
if layout is None:
|
|
742
|
+
layout = QVBoxLayout(body)
|
|
743
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
744
|
+
layout.setSpacing(0)
|
|
745
|
+
old_figure = entry.get("figure")
|
|
746
|
+
entry["_selection_artists"] = []
|
|
747
|
+
entry["profiler_widget"] = None
|
|
748
|
+
old_selector = entry.get("selector")
|
|
749
|
+
if old_selector is not None:
|
|
750
|
+
try:
|
|
751
|
+
old_selector.set_active(False)
|
|
752
|
+
old_selector.disconnect_events()
|
|
753
|
+
except Exception:
|
|
754
|
+
pass
|
|
755
|
+
entry["selector"] = None
|
|
756
|
+
while layout.count():
|
|
757
|
+
item = layout.takeAt(0)
|
|
758
|
+
widget = item.widget()
|
|
759
|
+
if widget is not None:
|
|
760
|
+
widget.setParent(None)
|
|
761
|
+
widget.deleteLater()
|
|
762
|
+
if old_figure is not None:
|
|
763
|
+
try:
|
|
764
|
+
import matplotlib.pyplot as plt
|
|
765
|
+
|
|
766
|
+
plt.close(old_figure)
|
|
767
|
+
except Exception:
|
|
768
|
+
pass
|
|
769
|
+
self._figures = [item for item in self._figures if item[0] is not old_figure]
|
|
770
|
+
|
|
771
|
+
session = getattr(self.result, "profiler_session", None)
|
|
772
|
+
if plot.kind == "profiler" and session is not None:
|
|
773
|
+
try:
|
|
774
|
+
profiler_widget = InteractiveProfilerWidget(session, self)
|
|
775
|
+
except Exception as exc:
|
|
776
|
+
label = QLabel(f"Interactive profiler unavailable: {exc}")
|
|
777
|
+
label.setStyleSheet("color:#a33;")
|
|
778
|
+
layout.addWidget(label)
|
|
779
|
+
entry["figure"] = None
|
|
780
|
+
entry["canvas"] = None
|
|
781
|
+
body.setVisible(plot.include_in_report)
|
|
782
|
+
return
|
|
783
|
+
profiler_widget.changed.connect(
|
|
784
|
+
lambda p=plot, w=profiler_widget: self._profiler_changed(p, w)
|
|
785
|
+
)
|
|
786
|
+
entry["profiler_widget"] = profiler_widget
|
|
787
|
+
entry["figure"] = profiler_widget.figure
|
|
788
|
+
entry["canvas"] = profiler_widget.canvas
|
|
789
|
+
entry["is_3d"] = False
|
|
790
|
+
entry["selector"] = None
|
|
791
|
+
self._attach_plot_context_menu(profiler_widget.canvas, entry)
|
|
792
|
+
self._figures.append((profiler_widget.figure, profiler_widget.canvas))
|
|
793
|
+
layout.addWidget(profiler_widget)
|
|
794
|
+
body.setVisible(plot.include_in_report)
|
|
795
|
+
for key in (
|
|
796
|
+
"bins_label",
|
|
797
|
+
"bins_spin",
|
|
798
|
+
"bins_slider",
|
|
799
|
+
"bubble_label",
|
|
800
|
+
"bubble_slider",
|
|
801
|
+
"bubble_value",
|
|
802
|
+
"reset_button",
|
|
803
|
+
"y1_points_check",
|
|
804
|
+
"y1_line_check",
|
|
805
|
+
"y2_points_check",
|
|
806
|
+
"y2_line_check",
|
|
807
|
+
"subset_button",
|
|
808
|
+
):
|
|
809
|
+
entry[key].setVisible(False)
|
|
810
|
+
entry["brush_button"].setVisible(False)
|
|
811
|
+
entry["brush_button"].setChecked(False)
|
|
812
|
+
return
|
|
813
|
+
|
|
814
|
+
try:
|
|
815
|
+
figure = build_figure(plot)
|
|
816
|
+
try:
|
|
817
|
+
plot.png_cache = figure_png_base64(figure)
|
|
818
|
+
except Exception:
|
|
819
|
+
plot.png_cache = None
|
|
820
|
+
except Exception as exc:
|
|
821
|
+
label = QLabel(f"Plot unavailable: {exc}")
|
|
822
|
+
label.setStyleSheet("color:#a33;")
|
|
823
|
+
layout.addWidget(label)
|
|
824
|
+
entry["figure"] = None
|
|
825
|
+
entry["canvas"] = None
|
|
826
|
+
body.setVisible(plot.include_in_report)
|
|
827
|
+
return
|
|
828
|
+
|
|
829
|
+
canvas = FigureCanvasQTAgg(figure)
|
|
830
|
+
canvas.setMinimumHeight(340)
|
|
831
|
+
canvas.setMinimumWidth(360)
|
|
832
|
+
canvas.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)
|
|
833
|
+
is_3d = bool(figure.axes) and getattr(figure.axes[0], "name", "") == "3d"
|
|
834
|
+
entry["is_3d"] = is_3d
|
|
835
|
+
self._capture_base_colors(figure)
|
|
836
|
+
selector = None
|
|
837
|
+
if plot.data is not None:
|
|
838
|
+
try:
|
|
839
|
+
canvas.mpl_connect(
|
|
840
|
+
"motion_notify_event",
|
|
841
|
+
lambda event, f=figure, p=plot, c=canvas: self._hover_event(event, f, p, c),
|
|
842
|
+
)
|
|
843
|
+
except Exception:
|
|
844
|
+
pass
|
|
845
|
+
brushable = self._has_brushable_points(figure)
|
|
846
|
+
if self.linked_selection is not None and plot.data is not None and not is_3d and brushable:
|
|
847
|
+
try:
|
|
848
|
+
canvas.mpl_connect("pick_event", lambda event, p=plot: self._pick(event, p))
|
|
849
|
+
except Exception:
|
|
850
|
+
pass
|
|
851
|
+
try:
|
|
852
|
+
selector = RectangleSelector(
|
|
853
|
+
figure.axes[0],
|
|
854
|
+
lambda press, release, p=plot, f=figure: self._brush_selected(press, release, f, p),
|
|
855
|
+
useblit=False,
|
|
856
|
+
button=[1],
|
|
857
|
+
minspanx=3,
|
|
858
|
+
minspany=3,
|
|
859
|
+
spancoords="pixels",
|
|
860
|
+
interactive=True,
|
|
861
|
+
drag_from_anywhere=True,
|
|
862
|
+
)
|
|
863
|
+
selector.set_active(brush_was_active)
|
|
864
|
+
except Exception:
|
|
865
|
+
selector = None
|
|
866
|
+
if plot.kind == "histogram" and not is_3d:
|
|
867
|
+
try:
|
|
868
|
+
canvas.mpl_connect("scroll_event", lambda event, e=entry: self._wheel_bins(event, e))
|
|
869
|
+
except Exception:
|
|
870
|
+
pass
|
|
871
|
+
|
|
872
|
+
layout.addWidget(NavigationToolbar2QT(canvas, body))
|
|
873
|
+
layout.addWidget(canvas)
|
|
874
|
+
body.setVisible(plot.include_in_report)
|
|
875
|
+
entry["figure"] = figure
|
|
876
|
+
entry["canvas"] = canvas
|
|
877
|
+
entry["selector"] = selector
|
|
878
|
+
self._attach_plot_context_menu(canvas, entry)
|
|
879
|
+
self._figures.append((figure, canvas))
|
|
880
|
+
entry["brush_button"].setVisible(selector is not None)
|
|
881
|
+
entry["subset_button"].setVisible(
|
|
882
|
+
selector is not None and self.create_subset is not None and plot.data is not None
|
|
883
|
+
)
|
|
884
|
+
if selector is None and entry["brush_button"].isChecked():
|
|
885
|
+
entry["brush_button"].setChecked(False)
|
|
886
|
+
entry["reset_button"].setVisible(is_3d)
|
|
887
|
+
entry["bins_label"].setVisible(plot.kind == "histogram")
|
|
888
|
+
entry["bins_spin"].setVisible(plot.kind == "histogram")
|
|
889
|
+
entry["bins_slider"].setVisible(plot.kind == "histogram")
|
|
890
|
+
self._sync_bin_controls(entry)
|
|
891
|
+
bubble_visible = plot.kind == "bubble"
|
|
892
|
+
entry["bubble_label"].setVisible(bubble_visible)
|
|
893
|
+
entry["bubble_slider"].setVisible(bubble_visible)
|
|
894
|
+
entry["bubble_value"].setVisible(bubble_visible)
|
|
895
|
+
self._sync_bubble_control(entry)
|
|
896
|
+
y1_visible = plot.kind in {"scatter", "line"}
|
|
897
|
+
entry["y1_points_check"].setVisible(y1_visible)
|
|
898
|
+
entry["y1_line_check"].setVisible(y1_visible)
|
|
899
|
+
self._sync_y1_controls(entry)
|
|
900
|
+
y2_visible = plot.kind in {"scatter", "line", "bar"} and bool((plot.params or {}).get("y2"))
|
|
901
|
+
entry["y2_points_check"].setVisible(y2_visible)
|
|
902
|
+
entry["y2_line_check"].setVisible(y2_visible)
|
|
903
|
+
self._sync_y2_controls(entry)
|
|
904
|
+
if not is_3d and self._last_selection is not None:
|
|
905
|
+
try:
|
|
906
|
+
self.apply_selection(*self._last_selection)
|
|
907
|
+
except Exception:
|
|
908
|
+
pass
|
|
909
|
+
|
|
910
|
+
def _sync_bin_controls(self, entry: dict) -> None:
|
|
911
|
+
plot = entry["plot"]
|
|
912
|
+
value = plot.params.get("bins", "auto")
|
|
913
|
+
try:
|
|
914
|
+
numeric = int(value) if value not in (None, "auto") else 0
|
|
915
|
+
except (TypeError, ValueError):
|
|
916
|
+
numeric = 0
|
|
917
|
+
entry["syncing"] = True
|
|
918
|
+
entry["bins_spin"].setValue(numeric)
|
|
919
|
+
entry["bins_slider"].setValue(numeric)
|
|
920
|
+
entry["syncing"] = False
|
|
921
|
+
|
|
922
|
+
def _bin_control_changed(self, entry: dict, value: int, source: str) -> None:
|
|
923
|
+
if entry.get("syncing"):
|
|
924
|
+
return
|
|
925
|
+
entry["syncing"] = True
|
|
926
|
+
if source == "spin":
|
|
927
|
+
entry["bins_slider"].setValue(value)
|
|
928
|
+
else:
|
|
929
|
+
entry["bins_spin"].setValue(value)
|
|
930
|
+
entry["syncing"] = False
|
|
931
|
+
entry["bins_timer"].start()
|
|
932
|
+
|
|
933
|
+
def _wheel_bins(self, event, entry: dict) -> None:
|
|
934
|
+
figure = entry.get("figure")
|
|
935
|
+
if figure is None or not figure.axes or getattr(event, "inaxes", None) is not figure.axes[0]:
|
|
936
|
+
return
|
|
937
|
+
step = 1 if getattr(event, "button", None) == "up" else -1
|
|
938
|
+
current = entry["bins_spin"].value()
|
|
939
|
+
if current <= 0:
|
|
940
|
+
current = 10
|
|
941
|
+
entry["bins_spin"].setValue(max(1, current + step))
|
|
942
|
+
|
|
943
|
+
def _apply_bins(self, entry: dict) -> None:
|
|
944
|
+
value = entry["bins_spin"].value()
|
|
945
|
+
entry["plot"].params["bins"] = value if value > 0 else "auto"
|
|
946
|
+
self._rebuild_plot_view(entry["plot"])
|
|
947
|
+
|
|
948
|
+
def _sync_bubble_control(self, entry: dict) -> None:
|
|
949
|
+
plot = entry["plot"]
|
|
950
|
+
try:
|
|
951
|
+
value = int(round(float(plot.params.get("bubble_scale", 1.0)) * 100))
|
|
952
|
+
except (TypeError, ValueError):
|
|
953
|
+
value = 100
|
|
954
|
+
value = max(25, min(400, value))
|
|
955
|
+
entry["syncing"] = True
|
|
956
|
+
entry["bubble_slider"].setValue(value)
|
|
957
|
+
entry["bubble_value"].setText(f"{value}%")
|
|
958
|
+
entry["syncing"] = False
|
|
959
|
+
|
|
960
|
+
def _bubble_control_changed(self, entry: dict, value: int) -> None:
|
|
961
|
+
if entry.get("syncing"):
|
|
962
|
+
return
|
|
963
|
+
entry["bubble_value"].setText(f"{value}%")
|
|
964
|
+
entry["bubble_timer"].start()
|
|
965
|
+
|
|
966
|
+
def _apply_bubble_scale(self, entry: dict) -> None:
|
|
967
|
+
plot = entry["plot"]
|
|
968
|
+
if plot.kind != "bubble":
|
|
969
|
+
return
|
|
970
|
+
scale = entry["bubble_slider"].value() / 100.0
|
|
971
|
+
if abs(scale - 1.0) > 1e-9:
|
|
972
|
+
plot.params["bubble_scale"] = scale
|
|
973
|
+
else:
|
|
974
|
+
plot.params.pop("bubble_scale", None)
|
|
975
|
+
self._rebuild_plot_view(plot)
|
|
976
|
+
|
|
977
|
+
def _sync_y1_controls(self, entry: dict) -> None:
|
|
978
|
+
plot = entry["plot"]
|
|
979
|
+
params = plot.params or {}
|
|
980
|
+
entry["syncing"] = True
|
|
981
|
+
entry["y1_points_check"].setChecked(
|
|
982
|
+
bool(params.get("y1_show_points", plot.kind == "scatter"))
|
|
983
|
+
)
|
|
984
|
+
entry["y1_line_check"].setChecked(
|
|
985
|
+
bool(params.get("y1_show_line", plot.kind == "line"))
|
|
986
|
+
)
|
|
987
|
+
entry["syncing"] = False
|
|
988
|
+
|
|
989
|
+
def _y1_control_changed(self, entry: dict) -> None:
|
|
990
|
+
if entry.get("syncing"):
|
|
991
|
+
return
|
|
992
|
+
plot = entry["plot"]
|
|
993
|
+
default_line = plot.kind == "line"
|
|
994
|
+
default_points = plot.kind == "scatter"
|
|
995
|
+
points = entry["y1_points_check"].isChecked()
|
|
996
|
+
line = entry["y1_line_check"].isChecked()
|
|
997
|
+
if points != default_points:
|
|
998
|
+
plot.params["y1_show_points"] = points
|
|
999
|
+
else:
|
|
1000
|
+
plot.params.pop("y1_show_points", None)
|
|
1001
|
+
if line != default_line:
|
|
1002
|
+
plot.params["y1_show_line"] = line
|
|
1003
|
+
else:
|
|
1004
|
+
plot.params.pop("y1_show_line", None)
|
|
1005
|
+
self._rebuild_plot_view(plot)
|
|
1006
|
+
|
|
1007
|
+
def _sync_y2_controls(self, entry: dict) -> None:
|
|
1008
|
+
params = entry["plot"].params or {}
|
|
1009
|
+
entry["syncing"] = True
|
|
1010
|
+
entry["y2_points_check"].setChecked(bool(params.get("y2_show_points", True)))
|
|
1011
|
+
entry["y2_line_check"].setChecked(bool(params.get("y2_show_line", True)))
|
|
1012
|
+
entry["syncing"] = False
|
|
1013
|
+
|
|
1014
|
+
def _y2_control_changed(self, entry: dict) -> None:
|
|
1015
|
+
if entry.get("syncing"):
|
|
1016
|
+
return
|
|
1017
|
+
plot = entry["plot"]
|
|
1018
|
+
if not (plot.params or {}).get("y2"):
|
|
1019
|
+
return
|
|
1020
|
+
if entry["y2_points_check"].isChecked():
|
|
1021
|
+
plot.params.pop("y2_show_points", None)
|
|
1022
|
+
else:
|
|
1023
|
+
plot.params["y2_show_points"] = False
|
|
1024
|
+
if entry["y2_line_check"].isChecked():
|
|
1025
|
+
plot.params.pop("y2_show_line", None)
|
|
1026
|
+
else:
|
|
1027
|
+
plot.params["y2_show_line"] = False
|
|
1028
|
+
self._rebuild_plot_view(plot)
|
|
1029
|
+
|
|
1030
|
+
def _toggle_brush(self, entry: dict, checked: bool) -> None:
|
|
1031
|
+
selector = entry.get("selector")
|
|
1032
|
+
if selector is not None:
|
|
1033
|
+
selector.set_active(checked)
|
|
1034
|
+
|
|
1035
|
+
def _reset_3d(self, entry: dict) -> None:
|
|
1036
|
+
figure = entry.get("figure")
|
|
1037
|
+
if not figure or not figure.axes:
|
|
1038
|
+
return
|
|
1039
|
+
params = entry["plot"].params or {}
|
|
1040
|
+
try:
|
|
1041
|
+
figure.axes[0].view_init(elev=float(params.get("elev", 22)), azim=float(params.get("azim", -60)))
|
|
1042
|
+
entry["canvas"].draw_idle()
|
|
1043
|
+
except Exception:
|
|
1044
|
+
pass
|
|
1045
|
+
|
|
1046
|
+
def _update_details(self, entry: dict) -> None:
|
|
1047
|
+
plot = entry["plot"]
|
|
1048
|
+
data, ids = self._plot_extents(plot)
|
|
1049
|
+
entry["rows_label"].setText(f"Rows: {len(data)}")
|
|
1050
|
+
params = plot.params or {}
|
|
1051
|
+
columns = [params.get(key) for key in ("x", "y", "y2", "z", "column", "size", "group", "category") if params.get(key)]
|
|
1052
|
+
entry["columns_label"].setText("Columns: " + (", ".join(str(column) for column in columns) if columns else "—"))
|
|
1053
|
+
selected = entry.get("selected_count") or 0
|
|
1054
|
+
entry["selection_label"].setText(f"Selected: {selected} row{'s' if selected != 1 else ''}")
|
|
1055
|
+
if entry.get("is_3d"):
|
|
1056
|
+
entry["hint_label"].setText("Drag to rotate · scroll to zoom")
|
|
1057
|
+
elif plot.kind == "profiler" and entry.get("profiler_widget") is not None:
|
|
1058
|
+
entry["hint_label"].setText(
|
|
1059
|
+
"Drag the red lines, change factor settings, or globally optimize all unlocked factors."
|
|
1060
|
+
)
|
|
1061
|
+
elif plot.kind == "histogram":
|
|
1062
|
+
entry["hint_label"].setText("Scroll over the plot or drag the slider to change bins.")
|
|
1063
|
+
elif plot.kind == "bubble":
|
|
1064
|
+
entry["hint_label"].setText("Drag the slider to change the bubble size scale.")
|
|
1065
|
+
else:
|
|
1066
|
+
entry["hint_label"].setText("")
|
|
1067
|
+
subset = entry.get("subset_button")
|
|
1068
|
+
if subset is not None:
|
|
1069
|
+
subset.setEnabled(self.create_subset is not None and plot.data is not None)
|
|
1070
|
+
|
|
1071
|
+
def _request_subset(self, plot) -> None:
|
|
1072
|
+
if self.create_subset is not None:
|
|
1073
|
+
self.create_subset()
|
|
1074
|
+
|
|
1075
|
+
def _edit_plot(self, plot) -> None:
|
|
1076
|
+
dialog = PlotEditDialog(plot, self)
|
|
1077
|
+
if dialog.exec() != QDialog.DialogCode.Accepted or dialog.result is None:
|
|
1078
|
+
return
|
|
1079
|
+
title, params = dialog.result
|
|
1080
|
+
plot.params = params
|
|
1081
|
+
plot.title = title
|
|
1082
|
+
self._rebuild_plot_view(plot)
|
|
1083
|
+
self._refresh_heading(plot)
|
|
1084
|
+
|
|
1085
|
+
def _refresh_heading(self, plot) -> None:
|
|
1086
|
+
for entry in self._plot_views:
|
|
1087
|
+
if entry["plot"] is plot:
|
|
1088
|
+
entry["title_label"].setText(plot.title or plot.kind.title())
|
|
1089
|
+
self._update_details(entry)
|
|
1090
|
+
|
|
1091
|
+
def _profiler_changed(self, plot, widget) -> None:
|
|
1092
|
+
entry = next((item for item in self._plot_views if item["plot"] is plot), None)
|
|
1093
|
+
try:
|
|
1094
|
+
plot.data = widget.snapshot_frame()
|
|
1095
|
+
plot.png_cache = None
|
|
1096
|
+
except Exception:
|
|
1097
|
+
pass
|
|
1098
|
+
if entry is not None:
|
|
1099
|
+
self._update_details(entry)
|
|
1100
|
+
if self.report_changed is not None:
|
|
1101
|
+
self.report_changed()
|
|
1102
|
+
|
|
1103
|
+
def _rebuild_plot_view(self, plot) -> None:
|
|
1104
|
+
entry = next((item for item in self._plot_views if item["plot"] is plot), None)
|
|
1105
|
+
if entry is None:
|
|
1106
|
+
return
|
|
1107
|
+
base = self._plot_base.get(id(plot))
|
|
1108
|
+
if base is not None:
|
|
1109
|
+
if self.local_filter:
|
|
1110
|
+
try:
|
|
1111
|
+
data, ids = filtered_plot_data(base[0], base[1], self.local_filter)
|
|
1112
|
+
plot.data = data
|
|
1113
|
+
plot.row_ids = ids
|
|
1114
|
+
except Exception:
|
|
1115
|
+
pass
|
|
1116
|
+
else:
|
|
1117
|
+
plot.data = base[0].copy(deep=False)
|
|
1118
|
+
plot.row_ids = list(base[1]) if base[1] is not None else None
|
|
1119
|
+
self._render_plot_body(entry)
|
|
1120
|
+
self._refresh_heading(plot)
|
|
1121
|
+
if self.report_changed is not None:
|
|
1122
|
+
self.report_changed()
|
|
1123
|
+
|
|
1124
|
+
def _add_deferred_plot(self) -> None:
|
|
1125
|
+
deferred = list(getattr(self.result, "deferred_plots", []) or [])
|
|
1126
|
+
if not deferred:
|
|
1127
|
+
return
|
|
1128
|
+
titles = [plot.title or plot.kind.title() for plot in deferred]
|
|
1129
|
+
selection, ok = QInputDialog.getItem(self, "Add Plot", "Plot to add:", titles, 0, False)
|
|
1130
|
+
if not ok or not selection:
|
|
1131
|
+
return
|
|
1132
|
+
index = titles.index(selection)
|
|
1133
|
+
plot = deferred.pop(index)
|
|
1134
|
+
self.result.deferred_plots = deferred
|
|
1135
|
+
self.result.plots.append(plot)
|
|
1136
|
+
self._add_plot(plot)
|
|
1137
|
+
if self.report_changed is not None:
|
|
1138
|
+
self.report_changed()
|
|
1139
|
+
|
|
1140
|
+
def _toggle_plot(self, plot, body: QWidget, toggle: QToolButton) -> None:
|
|
1141
|
+
plot.include_in_report = not plot.include_in_report
|
|
1142
|
+
body.setVisible(plot.include_in_report)
|
|
1143
|
+
toggle.setText("-" if plot.include_in_report else "+")
|
|
1144
|
+
if self.report_changed is not None:
|
|
1145
|
+
self.report_changed()
|
|
1146
|
+
|
|
1147
|
+
def _attach_plot_context_menu(self, canvas, entry: dict) -> None:
|
|
1148
|
+
if canvas is None:
|
|
1149
|
+
return
|
|
1150
|
+
canvas.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
|
1151
|
+
canvas.customContextMenuRequested.connect(
|
|
1152
|
+
lambda position, target=canvas, plot_entry=entry: self._show_plot_context_menu(
|
|
1153
|
+
target, position, plot_entry
|
|
1154
|
+
)
|
|
1155
|
+
)
|
|
1156
|
+
|
|
1157
|
+
def build_plot_context_menu(self, canvas, entry: dict) -> QMenu | None:
|
|
1158
|
+
figure = entry.get("figure")
|
|
1159
|
+
if figure is None:
|
|
1160
|
+
return None
|
|
1161
|
+
plot = entry["plot"]
|
|
1162
|
+
menu = QMenu(canvas)
|
|
1163
|
+
menu.addAction("Copy Plot", lambda: self.copy_plot_figure(figure))
|
|
1164
|
+
menu.addAction(
|
|
1165
|
+
"Export Plot as PNG...",
|
|
1166
|
+
lambda: self._export_plot_figure(figure, plot.title or plot.kind.title(), "PNG (*.png)", ".png"),
|
|
1167
|
+
)
|
|
1168
|
+
menu.addAction(
|
|
1169
|
+
"Export Plot as SVG...",
|
|
1170
|
+
lambda: self._export_plot_figure(figure, plot.title or plot.kind.title(), "SVG (*.svg)", ".svg"),
|
|
1171
|
+
)
|
|
1172
|
+
menu.addSeparator()
|
|
1173
|
+
menu.addAction("Export All Plots...", self.export_plots)
|
|
1174
|
+
return menu
|
|
1175
|
+
|
|
1176
|
+
def _show_plot_context_menu(self, canvas, position, entry: dict) -> None:
|
|
1177
|
+
menu = self.build_plot_context_menu(canvas, entry)
|
|
1178
|
+
if menu is not None:
|
|
1179
|
+
menu.exec(canvas.mapToGlobal(position))
|
|
1180
|
+
|
|
1181
|
+
def _export_plot_figure(self, figure, title: str, file_filter: str, suffix: str) -> None:
|
|
1182
|
+
safe_title = "".join(
|
|
1183
|
+
character if character.isalnum() or character in " -_" else "_"
|
|
1184
|
+
for character in title
|
|
1185
|
+
).strip() or "plot"
|
|
1186
|
+
path, _ = QFileDialog.getSaveFileName(
|
|
1187
|
+
self,
|
|
1188
|
+
"Export Plot",
|
|
1189
|
+
f"{safe_title}{suffix}",
|
|
1190
|
+
file_filter,
|
|
1191
|
+
)
|
|
1192
|
+
if not path:
|
|
1193
|
+
return
|
|
1194
|
+
try:
|
|
1195
|
+
figure.savefig(path, dpi=180, bbox_inches="tight")
|
|
1196
|
+
except Exception as exc:
|
|
1197
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1198
|
+
|
|
1199
|
+
def copy_plot_figure(self, figure) -> None:
|
|
1200
|
+
buffer = io.BytesIO()
|
|
1201
|
+
try:
|
|
1202
|
+
figure.savefig(buffer, format="png", dpi=180, bbox_inches="tight")
|
|
1203
|
+
image = QImage.fromData(buffer.getvalue(), "PNG")
|
|
1204
|
+
QApplication.clipboard().setPixmap(QPixmap.fromImage(image))
|
|
1205
|
+
except Exception as exc:
|
|
1206
|
+
QMessageBox.critical(self, "Copy Plot", str(exc))
|
|
1207
|
+
|
|
1208
|
+
def _visible_figures(self) -> list:
|
|
1209
|
+
return [entry["figure"] for entry in self._plot_views if entry["plot"].include_in_report]
|
|
1210
|
+
|
|
1211
|
+
def _python_text(self) -> str:
|
|
1212
|
+
table_name = getattr(self.table, "name", self.result.source_table)
|
|
1213
|
+
return _python_prelude(table_name, self.code) + self.code.strip() + "\n"
|
|
1214
|
+
|
|
1215
|
+
def copy_python(self) -> None:
|
|
1216
|
+
QApplication.clipboard().setText(self._python_text())
|
|
1217
|
+
|
|
1218
|
+
def export_python(self) -> None:
|
|
1219
|
+
path, _ = QFileDialog.getSaveFileName(self, "Save Python Script", f"{self.result.title}.py", "Python (*.py)")
|
|
1220
|
+
if not path:
|
|
1221
|
+
return
|
|
1222
|
+
try:
|
|
1223
|
+
Path(path).write_text(self._python_text(), encoding="utf-8")
|
|
1224
|
+
except Exception as exc:
|
|
1225
|
+
QMessageBox.critical(self, "Save failed", str(exc))
|
|
1226
|
+
|
|
1227
|
+
def export_html(self) -> None:
|
|
1228
|
+
path, _ = QFileDialog.getSaveFileName(self, "Export Report as HTML", f"{self.result.title}.html", "HTML (*.html)")
|
|
1229
|
+
if not path:
|
|
1230
|
+
return
|
|
1231
|
+
try:
|
|
1232
|
+
Path(path).write_text(self.result.to_html(include_plots=True), encoding="utf-8")
|
|
1233
|
+
except Exception as exc:
|
|
1234
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1235
|
+
|
|
1236
|
+
def export_interactive_html(self) -> None:
|
|
1237
|
+
path, _ = QFileDialog.getSaveFileName(self, "Export Interactive Report", f"{self.result.title}.html", "HTML (*.html)")
|
|
1238
|
+
if not path:
|
|
1239
|
+
return
|
|
1240
|
+
try:
|
|
1241
|
+
Path(path).write_text(self.result.to_html(include_plots=True, interactive=True), encoding="utf-8")
|
|
1242
|
+
except Exception as exc:
|
|
1243
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1244
|
+
|
|
1245
|
+
def _mark_selection(self, rows) -> None:
|
|
1246
|
+
for entry in self._plot_views:
|
|
1247
|
+
entry["selected_count"] = len(rows)
|
|
1248
|
+
self._update_details(entry)
|
|
1249
|
+
|
|
1250
|
+
def _pick(self, event, plot) -> None:
|
|
1251
|
+
if self.linked_selection is None or plot.data is None:
|
|
1252
|
+
return
|
|
1253
|
+
rows = ids_for_event(event, plot)
|
|
1254
|
+
if rows:
|
|
1255
|
+
self._last_selection = (self._table_name(), list(rows))
|
|
1256
|
+
self._mark_selection(rows)
|
|
1257
|
+
self.linked_selection(rows)
|
|
1258
|
+
|
|
1259
|
+
def _has_brushable_points(self, figure) -> bool:
|
|
1260
|
+
for ax in figure.axes:
|
|
1261
|
+
for collection in ax.collections:
|
|
1262
|
+
if getattr(collection, "_statstudio_row_ids", None):
|
|
1263
|
+
return True
|
|
1264
|
+
return False
|
|
1265
|
+
|
|
1266
|
+
def _capture_base_colors(self, figure) -> None:
|
|
1267
|
+
for ax in figure.axes:
|
|
1268
|
+
for collection in ax.collections:
|
|
1269
|
+
if getattr(collection, "_statstudio_row_ids", None):
|
|
1270
|
+
try:
|
|
1271
|
+
collection._statstudio_base_colors = np.array(
|
|
1272
|
+
collection.get_facecolor(), dtype=float, copy=True
|
|
1273
|
+
)
|
|
1274
|
+
except Exception:
|
|
1275
|
+
pass
|
|
1276
|
+
|
|
1277
|
+
def _hover_event(self, event, figure, plot, canvas) -> None:
|
|
1278
|
+
if plot.data is None or getattr(event, "inaxes", None) is None:
|
|
1279
|
+
QToolTip.hideText()
|
|
1280
|
+
return
|
|
1281
|
+
collection, indices = hit_test(figure, event)
|
|
1282
|
+
if collection is None:
|
|
1283
|
+
QToolTip.hideText()
|
|
1284
|
+
return
|
|
1285
|
+
rows = ids_for_indices(collection, plot, indices)
|
|
1286
|
+
if not rows:
|
|
1287
|
+
QToolTip.hideText()
|
|
1288
|
+
return
|
|
1289
|
+
QToolTip.showText(QCursor.pos(), describe_row(plot, rows[0]), canvas)
|
|
1290
|
+
|
|
1291
|
+
def _brush_selected(self, press, release, figure, plot) -> None:
|
|
1292
|
+
if self.linked_selection is None or plot.data is None:
|
|
1293
|
+
return
|
|
1294
|
+
try:
|
|
1295
|
+
xmin, xmax = press.xdata, release.xdata
|
|
1296
|
+
ymin, ymax = press.ydata, release.ydata
|
|
1297
|
+
except Exception:
|
|
1298
|
+
return
|
|
1299
|
+
if None in (xmin, xmax, ymin, ymax):
|
|
1300
|
+
return
|
|
1301
|
+
axes = getattr(press, "inaxes", None) or figure.axes[0]
|
|
1302
|
+
rows = ids_in_rect(figure, plot, xmin, xmax, ymin, ymax, axes=axes)
|
|
1303
|
+
if rows:
|
|
1304
|
+
self._last_selection = (self._table_name(), list(rows))
|
|
1305
|
+
self._mark_selection(rows)
|
|
1306
|
+
self.linked_selection(rows)
|
|
1307
|
+
|
|
1308
|
+
def _clear_histogram_overlay(self, entry: dict) -> None:
|
|
1309
|
+
for artist in entry.get("_selection_artists", []):
|
|
1310
|
+
try:
|
|
1311
|
+
artist.remove()
|
|
1312
|
+
except Exception:
|
|
1313
|
+
pass
|
|
1314
|
+
entry["_selection_artists"] = []
|
|
1315
|
+
|
|
1316
|
+
def _apply_histogram_selection(self, entry: dict, selected: set) -> None:
|
|
1317
|
+
"""Overlay the brushed subset on a histogram (bins cannot be recolored per point)."""
|
|
1318
|
+
self._clear_histogram_overlay(entry)
|
|
1319
|
+
plot = entry.get("plot")
|
|
1320
|
+
figure = entry.get("figure")
|
|
1321
|
+
if plot is None or figure is None or not figure.axes:
|
|
1322
|
+
return
|
|
1323
|
+
if plot.kind != "histogram" or plot.data is None or not selected:
|
|
1324
|
+
return
|
|
1325
|
+
column = plot.params.get("column") or plot.params.get("x")
|
|
1326
|
+
if not column or column not in plot.data.columns:
|
|
1327
|
+
return
|
|
1328
|
+
values = pd.to_numeric(plot.data[column], errors="coerce")
|
|
1329
|
+
full = values.dropna().to_numpy(dtype=float)
|
|
1330
|
+
if full.size == 0:
|
|
1331
|
+
return
|
|
1332
|
+
try:
|
|
1333
|
+
edges = np.histogram_bin_edges(full, bins=plot.params.get("bins", "auto"))
|
|
1334
|
+
except Exception:
|
|
1335
|
+
return
|
|
1336
|
+
mask = plot.data.index.isin(list(selected))
|
|
1337
|
+
subset = values[mask].dropna().to_numpy(dtype=float)
|
|
1338
|
+
if subset.size == 0:
|
|
1339
|
+
return
|
|
1340
|
+
density = bool(plot.params.get("distribution"))
|
|
1341
|
+
try:
|
|
1342
|
+
heights, _ = np.histogram(subset, bins=edges, density=density)
|
|
1343
|
+
bars = figure.axes[0].bar(
|
|
1344
|
+
edges[:-1],
|
|
1345
|
+
heights,
|
|
1346
|
+
width=np.diff(edges),
|
|
1347
|
+
align="edge",
|
|
1348
|
+
color="#1f4e79",
|
|
1349
|
+
alpha=0.6,
|
|
1350
|
+
linewidth=0,
|
|
1351
|
+
zorder=6,
|
|
1352
|
+
)
|
|
1353
|
+
except Exception:
|
|
1354
|
+
return
|
|
1355
|
+
entry["_selection_artists"] = [bars]
|
|
1356
|
+
|
|
1357
|
+
def apply_selection(self, table_name: str, row_ids) -> None:
|
|
1358
|
+
source = getattr(self.result, "source_table", "") or ""
|
|
1359
|
+
table = getattr(self, "table", None)
|
|
1360
|
+
view_table_name = getattr(table, "name", "") if table is not None else ""
|
|
1361
|
+
names = {source, view_table_name}
|
|
1362
|
+
if table_name and table_name not in names:
|
|
1363
|
+
return
|
|
1364
|
+
selected = set(row_ids)
|
|
1365
|
+
self._last_selection = (table_name, list(row_ids))
|
|
1366
|
+
for entry in self._plot_views:
|
|
1367
|
+
entry["selected_count"] = len(selected)
|
|
1368
|
+
self._update_details(entry)
|
|
1369
|
+
for entry in self._plot_views:
|
|
1370
|
+
figure = entry.get("figure")
|
|
1371
|
+
if figure is not None:
|
|
1372
|
+
self._apply_histogram_selection(entry, selected)
|
|
1373
|
+
for ax in figure.axes:
|
|
1374
|
+
for collection in ax.collections:
|
|
1375
|
+
ids = getattr(collection, "_statstudio_row_ids", None)
|
|
1376
|
+
base = getattr(collection, "_statstudio_base_colors", None)
|
|
1377
|
+
if not ids or base is None or len(base) == 0:
|
|
1378
|
+
continue
|
|
1379
|
+
colors = np.array(
|
|
1380
|
+
[base[position % len(base)] for position in range(len(ids))],
|
|
1381
|
+
dtype=float,
|
|
1382
|
+
)
|
|
1383
|
+
if selected:
|
|
1384
|
+
for position, row_id in enumerate(ids):
|
|
1385
|
+
if row_id not in selected:
|
|
1386
|
+
colors[position][:3] = 1.0 - (1.0 - colors[position][:3]) * 0.25
|
|
1387
|
+
try:
|
|
1388
|
+
collection.set_facecolor(colors)
|
|
1389
|
+
except Exception:
|
|
1390
|
+
pass
|
|
1391
|
+
canvas = entry.get("canvas")
|
|
1392
|
+
if canvas is not None:
|
|
1393
|
+
try:
|
|
1394
|
+
canvas.draw_idle()
|
|
1395
|
+
except Exception:
|
|
1396
|
+
pass
|
|
1397
|
+
|
|
1398
|
+
def export_plots(self) -> None:
|
|
1399
|
+
figures = self._visible_figures()
|
|
1400
|
+
if not figures:
|
|
1401
|
+
QMessageBox.information(self, "Export Plots", "This report has no visible plots.")
|
|
1402
|
+
return
|
|
1403
|
+
folder = QFileDialog.getExistingDirectory(self, "Export Plot Images")
|
|
1404
|
+
if not folder:
|
|
1405
|
+
return
|
|
1406
|
+
try:
|
|
1407
|
+
root = Path(folder)
|
|
1408
|
+
for index, figure in enumerate(figures, start=1):
|
|
1409
|
+
figure.savefig(root / f"plot_{index:02d}.png", dpi=150, bbox_inches="tight")
|
|
1410
|
+
try:
|
|
1411
|
+
figure.savefig(root / f"plot_{index:02d}.svg", bbox_inches="tight")
|
|
1412
|
+
except Exception:
|
|
1413
|
+
pass
|
|
1414
|
+
except Exception as exc:
|
|
1415
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1416
|
+
|
|
1417
|
+
def export_word(self) -> None:
|
|
1418
|
+
path, _ = QFileDialog.getSaveFileName(self, "Export Report as Word", f"{self.result.title}.docx", "Word (*.docx)")
|
|
1419
|
+
if not path:
|
|
1420
|
+
return
|
|
1421
|
+
try:
|
|
1422
|
+
from statstudio.io.docx import write_docx
|
|
1423
|
+
|
|
1424
|
+
blocks: list[tuple[str, object]] = []
|
|
1425
|
+
if self.result.summary:
|
|
1426
|
+
blocks.append(("paragraph", self.result.summary))
|
|
1427
|
+
for table in self.result.tables:
|
|
1428
|
+
blocks.append(("heading", table.title))
|
|
1429
|
+
if table.notes:
|
|
1430
|
+
blocks.append(("paragraph", table.notes))
|
|
1431
|
+
blocks.append(("table", table.frame))
|
|
1432
|
+
figures = self._visible_figures()
|
|
1433
|
+
if figures:
|
|
1434
|
+
blocks.append(("heading", "Figures"))
|
|
1435
|
+
for _ in figures:
|
|
1436
|
+
blocks.append(("image", None))
|
|
1437
|
+
write_docx(path, self.result.title, blocks, figures)
|
|
1438
|
+
except Exception as exc:
|
|
1439
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1440
|
+
|
|
1441
|
+
def export_pdf(self) -> None:
|
|
1442
|
+
path, _ = QFileDialog.getSaveFileName(self, "Export Report as PDF", f"{self.result.title}.pdf", "PDF (*.pdf)")
|
|
1443
|
+
if not path:
|
|
1444
|
+
return
|
|
1445
|
+
try:
|
|
1446
|
+
from PySide6.QtGui import QTextDocument
|
|
1447
|
+
from PySide6.QtPrintSupport import QPrinter
|
|
1448
|
+
|
|
1449
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
1450
|
+
visible = [plot for plot in self.result.plots if plot.include_in_report]
|
|
1451
|
+
figure_by_plot = {id(entry["plot"]): entry["figure"] for entry in self._plot_views}
|
|
1452
|
+
urls = []
|
|
1453
|
+
for plot in visible:
|
|
1454
|
+
figure = figure_by_plot.get(id(plot))
|
|
1455
|
+
if figure is None:
|
|
1456
|
+
urls.append("")
|
|
1457
|
+
continue
|
|
1458
|
+
image_path = Path(folder) / f"plot_{len(urls)}.png"
|
|
1459
|
+
figure.savefig(image_path, dpi=130, bbox_inches="tight")
|
|
1460
|
+
urls.append(image_path.as_uri())
|
|
1461
|
+
html = self.result.to_html(include_plots=True, plot_urls=urls)
|
|
1462
|
+
document = QTextDocument()
|
|
1463
|
+
document.setHtml(html)
|
|
1464
|
+
printer = QPrinter(QPrinter.PrinterMode.HighResolution)
|
|
1465
|
+
printer.setOutputFormat(QPrinter.OutputFormat.PdfFormat)
|
|
1466
|
+
printer.setOutputFileName(path)
|
|
1467
|
+
document.print_(printer)
|
|
1468
|
+
except Exception as exc:
|
|
1469
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1470
|
+
|
|
1471
|
+
|
|
1472
|
+
class SavedReportView(QWidget):
|
|
1473
|
+
minimize_requested = Signal()
|
|
1474
|
+
maximize_requested = Signal()
|
|
1475
|
+
delete_requested = Signal()
|
|
1476
|
+
|
|
1477
|
+
def __init__(
|
|
1478
|
+
self,
|
|
1479
|
+
title: str,
|
|
1480
|
+
html_text: str,
|
|
1481
|
+
parent: QWidget | None = None,
|
|
1482
|
+
rerun: Callable[[], None] | None = None,
|
|
1483
|
+
code: str = "",
|
|
1484
|
+
table_name: str = "",
|
|
1485
|
+
) -> None:
|
|
1486
|
+
super().__init__(parent)
|
|
1487
|
+
self.title = title
|
|
1488
|
+
self.html_text = html_text
|
|
1489
|
+
self.rerun = rerun
|
|
1490
|
+
self.code = code
|
|
1491
|
+
self.table_name = table_name
|
|
1492
|
+
layout = QVBoxLayout(self)
|
|
1493
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
1494
|
+
self.header = QFrame()
|
|
1495
|
+
self.header.setObjectName("documentHeader")
|
|
1496
|
+
toolbar = QHBoxLayout(self.header)
|
|
1497
|
+
toolbar.setContentsMargins(9, 4, 6, 4)
|
|
1498
|
+
toolbar.setSpacing(7)
|
|
1499
|
+
label = QLabel(title)
|
|
1500
|
+
label.setObjectName("documentTitle")
|
|
1501
|
+
toolbar.addWidget(label)
|
|
1502
|
+
help_button = QPushButton("Help")
|
|
1503
|
+
icons.set_button_icon(help_button, "help")
|
|
1504
|
+
help_button.setProperty("quiet", "true")
|
|
1505
|
+
help_button.setToolTip("Open help for saved reports")
|
|
1506
|
+
help_button.clicked.connect(self._show_help)
|
|
1507
|
+
toolbar.addWidget(help_button)
|
|
1508
|
+
toolbar.addStretch(1)
|
|
1509
|
+
if rerun:
|
|
1510
|
+
rerun_button = QPushButton("Re-run")
|
|
1511
|
+
rerun_button.clicked.connect(rerun)
|
|
1512
|
+
toolbar.addWidget(rerun_button)
|
|
1513
|
+
if code:
|
|
1514
|
+
copy_button = QPushButton("Copy Python")
|
|
1515
|
+
copy_button.clicked.connect(self.copy_python)
|
|
1516
|
+
toolbar.addWidget(copy_button)
|
|
1517
|
+
save_button = QPushButton("Save Python")
|
|
1518
|
+
save_button.clicked.connect(self.export_python)
|
|
1519
|
+
toolbar.addWidget(save_button)
|
|
1520
|
+
toolbar.addWidget(
|
|
1521
|
+
_export_button(
|
|
1522
|
+
self,
|
|
1523
|
+
[
|
|
1524
|
+
("HTML...", self.export_html),
|
|
1525
|
+
("PDF...", self.export_pdf),
|
|
1526
|
+
("Word...", self.export_word),
|
|
1527
|
+
],
|
|
1528
|
+
)
|
|
1529
|
+
)
|
|
1530
|
+
self.window_controls = WindowControls()
|
|
1531
|
+
self.window_controls.minimize_requested.connect(self.minimize_requested.emit)
|
|
1532
|
+
self.window_controls.maximize_requested.connect(self.maximize_requested.emit)
|
|
1533
|
+
self.window_controls.delete_requested.connect(self.delete_requested.emit)
|
|
1534
|
+
toolbar.addWidget(self.window_controls)
|
|
1535
|
+
layout.addWidget(self.header)
|
|
1536
|
+
self.browser = QTextBrowser()
|
|
1537
|
+
self.browser.setHtml(html_text)
|
|
1538
|
+
layout.addWidget(self.browser, 1)
|
|
1539
|
+
from statstudio.ui.dialogs.help_topics import install_context_help
|
|
1540
|
+
|
|
1541
|
+
install_context_help(self, "reports")
|
|
1542
|
+
|
|
1543
|
+
def _show_help(self) -> None:
|
|
1544
|
+
from statstudio.ui.dialogs.help_topics import open_help
|
|
1545
|
+
|
|
1546
|
+
open_help(self, "reports")
|
|
1547
|
+
|
|
1548
|
+
def _python_text(self) -> str:
|
|
1549
|
+
return _python_prelude(self.table_name, self.code) + self.code.strip() + "\n"
|
|
1550
|
+
|
|
1551
|
+
def copy_python(self) -> None:
|
|
1552
|
+
QApplication.clipboard().setText(self._python_text())
|
|
1553
|
+
|
|
1554
|
+
def export_python(self) -> None:
|
|
1555
|
+
path, _ = QFileDialog.getSaveFileName(self, "Save Python Script", f"{self.title}.py", "Python (*.py)")
|
|
1556
|
+
if not path:
|
|
1557
|
+
return
|
|
1558
|
+
try:
|
|
1559
|
+
Path(path).write_text(self._python_text(), encoding="utf-8")
|
|
1560
|
+
except Exception as exc:
|
|
1561
|
+
QMessageBox.critical(self, "Save failed", str(exc))
|
|
1562
|
+
|
|
1563
|
+
def export_html(self) -> None:
|
|
1564
|
+
path, _ = QFileDialog.getSaveFileName(self, "Export Report as HTML", f"{self.title}.html", "HTML (*.html)")
|
|
1565
|
+
if not path:
|
|
1566
|
+
return
|
|
1567
|
+
try:
|
|
1568
|
+
Path(path).write_text(self.html_text, encoding="utf-8")
|
|
1569
|
+
except Exception as exc:
|
|
1570
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1571
|
+
|
|
1572
|
+
def _embedded_pngs(self) -> list[bytes]:
|
|
1573
|
+
import base64
|
|
1574
|
+
import re
|
|
1575
|
+
|
|
1576
|
+
images = []
|
|
1577
|
+
for match in re.finditer(r"data:image/png;base64,([A-Za-z0-9+/=\s]+)", self.html_text):
|
|
1578
|
+
try:
|
|
1579
|
+
images.append(base64.b64decode(match.group(1)))
|
|
1580
|
+
except Exception:
|
|
1581
|
+
continue
|
|
1582
|
+
return images
|
|
1583
|
+
|
|
1584
|
+
def export_word(self) -> None:
|
|
1585
|
+
path, _ = QFileDialog.getSaveFileName(self, "Export Report as Word", f"{self.title}.docx", "Word (*.docx)")
|
|
1586
|
+
if not path:
|
|
1587
|
+
return
|
|
1588
|
+
try:
|
|
1589
|
+
from statstudio.io.docx import write_docx
|
|
1590
|
+
|
|
1591
|
+
images = self._embedded_pngs()
|
|
1592
|
+
blocks: list[tuple[str, object]] = [("paragraph", "Saved StatStudio report.")]
|
|
1593
|
+
if images:
|
|
1594
|
+
blocks.append(("heading", "Figures"))
|
|
1595
|
+
for data in images:
|
|
1596
|
+
blocks.append(("image_data", data))
|
|
1597
|
+
write_docx(path, self.title, blocks)
|
|
1598
|
+
except Exception as exc:
|
|
1599
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|
|
1600
|
+
|
|
1601
|
+
def export_pdf(self) -> None:
|
|
1602
|
+
path, _ = QFileDialog.getSaveFileName(self, "Export Report as PDF", f"{self.title}.pdf", "PDF (*.pdf)")
|
|
1603
|
+
if not path:
|
|
1604
|
+
return
|
|
1605
|
+
try:
|
|
1606
|
+
import base64
|
|
1607
|
+
import re
|
|
1608
|
+
|
|
1609
|
+
from PySide6.QtGui import QTextDocument
|
|
1610
|
+
from PySide6.QtPrintSupport import QPrinter
|
|
1611
|
+
|
|
1612
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
1613
|
+
counter = {"value": 0}
|
|
1614
|
+
|
|
1615
|
+
def replace(match):
|
|
1616
|
+
counter["value"] += 1
|
|
1617
|
+
image_path = Path(folder) / f"image_{counter['value']}.png"
|
|
1618
|
+
try:
|
|
1619
|
+
image_path.write_bytes(base64.b64decode(match.group(1)))
|
|
1620
|
+
except Exception:
|
|
1621
|
+
return ""
|
|
1622
|
+
return image_path.as_uri()
|
|
1623
|
+
|
|
1624
|
+
html = re.sub(r"data:image/png;base64,([A-Za-z0-9+/=\s]+)", replace, self.html_text)
|
|
1625
|
+
document = QTextDocument()
|
|
1626
|
+
document.setHtml(html)
|
|
1627
|
+
printer = QPrinter(QPrinter.PrinterMode.HighResolution)
|
|
1628
|
+
printer.setOutputFormat(QPrinter.OutputFormat.PdfFormat)
|
|
1629
|
+
printer.setOutputFileName(path)
|
|
1630
|
+
document.print_(printer)
|
|
1631
|
+
except Exception as exc:
|
|
1632
|
+
QMessageBox.critical(self, "Export failed", str(exc))
|