staplot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. staplot/__init__.py +1 -0
  2. staplot/api.py +441 -0
  3. staplot/main.py +21 -0
  4. staplot/models/__init__.py +1 -0
  5. staplot/models/project.py +461 -0
  6. staplot/plots/__init__.py +14 -0
  7. staplot/plots/bar.py +104 -0
  8. staplot/plots/before_after.py +110 -0
  9. staplot/plots/bland_altman.py +73 -0
  10. staplot/plots/box.py +95 -0
  11. staplot/plots/distribution_plot.py +188 -0
  12. staplot/plots/grouped_bar.py +112 -0
  13. staplot/plots/heatmap.py +73 -0
  14. staplot/plots/histogram.py +76 -0
  15. staplot/plots/qq.py +61 -0
  16. staplot/plots/residuals.py +72 -0
  17. staplot/plots/roc_plot.py +40 -0
  18. staplot/plots/scatter.py +61 -0
  19. staplot/plots/significance.py +94 -0
  20. staplot/plots/styles.py +154 -0
  21. staplot/plots/survival.py +78 -0
  22. staplot/plots/volcano.py +110 -0
  23. staplot/stats/__init__.py +15 -0
  24. staplot/stats/anova.py +124 -0
  25. staplot/stats/chi_square.py +85 -0
  26. staplot/stats/correlation.py +71 -0
  27. staplot/stats/curve_fit.py +85 -0
  28. staplot/stats/descriptive.py +52 -0
  29. staplot/stats/distribution.py +223 -0
  30. staplot/stats/multiple_comparisons.py +104 -0
  31. staplot/stats/normality.py +67 -0
  32. staplot/stats/outliers.py +62 -0
  33. staplot/stats/power.py +130 -0
  34. staplot/stats/regression.py +95 -0
  35. staplot/stats/repeated_measures.py +114 -0
  36. staplot/stats/roc.py +196 -0
  37. staplot/stats/tests.py +142 -0
  38. staplot/stats/two_way_anova.py +88 -0
  39. staplot/ui/__init__.py +0 -0
  40. staplot/ui/analysis_dialog.py +406 -0
  41. staplot/ui/axis_dialog.py +104 -0
  42. staplot/ui/computed_column_dialog.py +261 -0
  43. staplot/ui/contingency_table_widget.py +158 -0
  44. staplot/ui/data_table_widget.py +277 -0
  45. staplot/ui/distribution_inspector.py +431 -0
  46. staplot/ui/figure_layout_widget.py +236 -0
  47. staplot/ui/graph_gallery.py +117 -0
  48. staplot/ui/graph_options_dialog.py +325 -0
  49. staplot/ui/grouped_table_widget.py +190 -0
  50. staplot/ui/layout_dialog.py +218 -0
  51. staplot/ui/main_window.py +1126 -0
  52. staplot/ui/multiple_comparisons_dialog.py +168 -0
  53. staplot/ui/navigator.py +88 -0
  54. staplot/ui/plot_canvas.py +251 -0
  55. staplot/ui/power_dialog.py +108 -0
  56. staplot/ui/report_dialog.py +255 -0
  57. staplot/ui/reshape_dialog.py +286 -0
  58. staplot/ui/results_widget.py +19 -0
  59. staplot/ui/standard_curve_dialog.py +150 -0
  60. staplot/ui/test_wizard.py +252 -0
  61. staplot/ui/transform_dialog.py +137 -0
  62. staplot/ui/undo_commands.py +86 -0
  63. staplot-0.1.0.dist-info/METADATA +85 -0
  64. staplot-0.1.0.dist-info/RECORD +68 -0
  65. staplot-0.1.0.dist-info/WHEEL +5 -0
  66. staplot-0.1.0.dist-info/entry_points.txt +2 -0
  67. staplot-0.1.0.dist-info/licenses/LICENSE +24 -0
  68. staplot-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,431 @@
1
+ """Distribution Inspector — unified normality, shape, fitting, and test-advisor dialog."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+
7
+ import matplotlib
8
+ matplotlib.use("QtAgg")
9
+
10
+ from qtpy.QtWidgets import (
11
+ QDialog, QVBoxLayout, QHBoxLayout, QTabWidget, QWidget,
12
+ QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView,
13
+ QComboBox, QLabel, QPushButton, QGroupBox, QFormLayout,
14
+ QSplitter, QTextEdit, QApplication,
15
+ )
16
+ from qtpy.QtCore import Qt, Signal
17
+ from qtpy.QtGui import QColor, QFont, QImage
18
+
19
+ from ..models.project import DataTable
20
+ from ..plots import styles
21
+ from .plot_canvas import StyledCanvas
22
+
23
+
24
+ # ── colour helpers ──────────────────────────────────────────────────
25
+
26
+ _GREEN = QColor("#d4edda")
27
+ _RED = QColor("#f8d7da")
28
+ _YELLOW = QColor("#fff3cd")
29
+ _GRAY = QColor("#f0f0f0")
30
+
31
+
32
+ def _verdict_color(is_normal: bool) -> QColor:
33
+ return _GREEN if is_normal else _RED
34
+
35
+
36
+ # ── DistributionInspector ───────────────────────────────────────────
37
+
38
+ class DistributionInspector(QDialog):
39
+ """
40
+ All-in-one dialog for:
41
+ • Normality tests + shape stats per column (Summary tab)
42
+ • Histogram + KDE + Q-Q panel per column (Visual tab)
43
+ • Distribution fitting ranked by AIC (in Visual tab)
44
+ • Automatic test recommendation + one-click run (Summary tab)
45
+ """
46
+
47
+ # Emitted when the user clicks "Run recommended test" for a column
48
+ run_test_requested = Signal(int) # analysis-dialog tab index
49
+
50
+ def __init__(self, tables: list, parent=None):
51
+ super().__init__(parent)
52
+ self.setWindowTitle("Distribution Inspector")
53
+ self.setMinimumSize(860, 620)
54
+ self._tables = [t for t in tables if isinstance(t, DataTable) and t.columns]
55
+ self._result = None # AnalysisResult from last run
56
+ self._dist_fig = None # current detail figure
57
+
58
+ layout = QVBoxLayout(self)
59
+
60
+ # ── Table selector ────────────────────────────────────────────
61
+ top = QHBoxLayout()
62
+ top.addWidget(QLabel("Table:"))
63
+ self._table_cb = QComboBox()
64
+ self._table_cb.addItems([t.name for t in self._tables])
65
+ self._table_cb.currentIndexChanged.connect(self._clear_results)
66
+ top.addWidget(self._table_cb)
67
+ top.addStretch()
68
+ run_btn = QPushButton("Run Distribution Check")
69
+ run_btn.setDefault(True)
70
+ run_btn.clicked.connect(self._run)
71
+ top.addWidget(run_btn)
72
+ layout.addLayout(top)
73
+
74
+ # ── Tabs ──────────────────────────────────────────────────────
75
+ self._tabs = QTabWidget()
76
+ layout.addWidget(self._tabs)
77
+
78
+ # Tab 1 — Summary table
79
+ self._tab_summary = QWidget()
80
+ self._tabs.addTab(self._tab_summary, "Summary & Advisor")
81
+ self._build_summary_tab()
82
+
83
+ # Tab 2 — Per-column visual
84
+ self._tab_visual = QWidget()
85
+ self._tabs.addTab(self._tab_visual, "Visual Details")
86
+ self._build_visual_tab()
87
+
88
+ # Tab 3 — Raw text report
89
+ self._tab_text = QWidget()
90
+ self._tabs.addTab(self._tab_text, "Text Report")
91
+ self._build_text_tab()
92
+
93
+ # ── Footer buttons ─────────────────────────────────────────────
94
+ foot = QHBoxLayout()
95
+ copy_btn = QPushButton("Copy Report")
96
+ copy_btn.clicked.connect(self._copy_report)
97
+ foot.addWidget(copy_btn)
98
+ copy_img_btn = QPushButton("Copy Plot")
99
+ copy_img_btn.clicked.connect(self._copy_plot)
100
+ foot.addWidget(copy_img_btn)
101
+ foot.addStretch()
102
+ close_btn = QPushButton("Close")
103
+ close_btn.clicked.connect(self.reject)
104
+ foot.addWidget(close_btn)
105
+ layout.addLayout(foot)
106
+
107
+ # ------------------------------------------------------------------
108
+ # Tab builders
109
+ # ------------------------------------------------------------------
110
+ def _build_summary_tab(self):
111
+ layout = QVBoxLayout(self._tab_summary)
112
+
113
+ # Instructions label
114
+ info = QLabel(
115
+ "Run a distribution check to see normality results and test recommendations per column."
116
+ )
117
+ info.setWordWrap(True)
118
+ layout.addWidget(info)
119
+
120
+ # Summary table
121
+ self._summary_tbl = QTableWidget(0, 7)
122
+ self._summary_tbl.setHorizontalHeaderLabels([
123
+ "Column", "n", "Shapiro-Wilk p", "Skewness",
124
+ "Kurtosis", "Verdict", "Recommended test (2 groups)",
125
+ ])
126
+ self._summary_tbl.horizontalHeader().setSectionResizeMode(
127
+ QHeaderView.ResizeMode.ResizeToContents
128
+ )
129
+ self._summary_tbl.horizontalHeader().setSectionResizeMode(
130
+ 6, QHeaderView.ResizeMode.Stretch
131
+ )
132
+ self._summary_tbl.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
133
+ self._summary_tbl.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
134
+ self._summary_tbl.verticalHeader().setVisible(False)
135
+ layout.addWidget(self._summary_tbl)
136
+
137
+ # Advisor panel (shows detail for selected row)
138
+ grp = QGroupBox("Test Advisor")
139
+ adv_layout = QVBoxLayout(grp)
140
+ self._advisor_label = QLabel("Select a column in the table above.")
141
+ self._advisor_label.setWordWrap(True)
142
+ bold = QFont(); bold.setBold(True)
143
+ self._advisor_label.setFont(bold)
144
+ adv_layout.addWidget(self._advisor_label)
145
+
146
+ btn_row = QHBoxLayout()
147
+ self._run_rec_btn = QPushButton("Run recommended test…")
148
+ self._run_rec_btn.setEnabled(False)
149
+ self._run_rec_btn.clicked.connect(self._open_recommended_test)
150
+ btn_row.addWidget(self._run_rec_btn)
151
+ btn_row.addStretch()
152
+ adv_layout.addLayout(btn_row)
153
+ layout.addWidget(grp)
154
+
155
+ self._summary_tbl.itemSelectionChanged.connect(self._on_summary_select)
156
+
157
+ def _build_visual_tab(self):
158
+ layout = QVBoxLayout(self._tab_visual)
159
+
160
+ sel_row = QHBoxLayout()
161
+ sel_row.addWidget(QLabel("Column:"))
162
+ self._col_cb = QComboBox()
163
+ self._col_cb.currentTextChanged.connect(self._update_visual)
164
+ sel_row.addWidget(self._col_cb)
165
+ sel_row.addStretch()
166
+ layout.addLayout(sel_row)
167
+
168
+ splitter = QSplitter(Qt.Orientation.Vertical)
169
+
170
+ # Matplotlib canvas (histogram + QQ)
171
+ self._detail_canvas_widget = QWidget()
172
+ self._detail_canvas_layout = QVBoxLayout(self._detail_canvas_widget)
173
+ self._detail_canvas_layout.setContentsMargins(0, 0, 0, 0)
174
+ self._placeholder_label = QLabel(
175
+ "Run Distribution Check to see plots.", alignment=Qt.AlignmentFlag.AlignCenter
176
+ )
177
+ self._detail_canvas_layout.addWidget(self._placeholder_label)
178
+ self._mpl_canvas = None
179
+ splitter.addWidget(self._detail_canvas_widget)
180
+
181
+ # Fitting table
182
+ fit_grp = QGroupBox("Distribution fitting (ranked by AIC — lower is better)")
183
+ fit_v = QVBoxLayout(fit_grp)
184
+ self._fit_tbl = QTableWidget(0, 5)
185
+ self._fit_tbl.setHorizontalHeaderLabels(
186
+ ["Distribution", "AIC", "BIC", "KS p-value", "Fit OK?"]
187
+ )
188
+ self._fit_tbl.horizontalHeader().setSectionResizeMode(
189
+ QHeaderView.ResizeMode.Stretch
190
+ )
191
+ self._fit_tbl.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
192
+ self._fit_tbl.setMaximumHeight(160)
193
+ fit_v.addWidget(self._fit_tbl)
194
+ splitter.addWidget(fit_grp)
195
+ splitter.setSizes([400, 160])
196
+
197
+ layout.addWidget(splitter)
198
+
199
+ def _build_text_tab(self):
200
+ layout = QVBoxLayout(self._tab_text)
201
+ self._text_box = QTextEdit()
202
+ self._text_box.setReadOnly(True)
203
+ mono = QFont("Courier New", 8)
204
+ mono.setStyleHint(QFont.StyleHint.Monospace)
205
+ self._text_box.setFont(mono)
206
+ layout.addWidget(self._text_box)
207
+
208
+ # ------------------------------------------------------------------
209
+ # Run analysis
210
+ # ------------------------------------------------------------------
211
+ def _current_table(self) -> DataTable | None:
212
+ idx = self._table_cb.currentIndex()
213
+ return self._tables[idx] if 0 <= idx < len(self._tables) else None
214
+
215
+ def _clear_results(self):
216
+ self._result = None
217
+ self._summary_tbl.setRowCount(0)
218
+ self._fit_tbl.setRowCount(0)
219
+ self._text_box.clear()
220
+ self._advisor_label.setText("Select a column in the table above.")
221
+ self._run_rec_btn.setEnabled(False)
222
+ self._col_cb.clear()
223
+
224
+ def _run(self):
225
+ t = self._current_table()
226
+ if t is None:
227
+ return
228
+ from ..stats.distribution import run_distribution_check
229
+ from ..plots.distribution_plot import plot_distribution_grid
230
+
231
+ self._result = run_distribution_check(t)
232
+ self._populate_summary()
233
+ self._populate_col_selector()
234
+ self._text_box.setPlainText(self._result.summary_text)
235
+ self._tabs.setCurrentIndex(0)
236
+
237
+ # ------------------------------------------------------------------
238
+ # Summary tab population
239
+ # ------------------------------------------------------------------
240
+ def _populate_summary(self):
241
+ if self._result is None:
242
+ return
243
+ details = self._result.details
244
+ self._summary_tbl.setRowCount(0)
245
+
246
+ for col_name, info in details.items():
247
+ row = self._summary_tbl.rowCount()
248
+ self._summary_tbl.insertRow(row)
249
+
250
+ n = info.get("n", 0)
251
+ sw_p = info.get("shapiro_p", float("nan"))
252
+ skew = info.get("skewness", float("nan"))
253
+ kurt = info.get("kurtosis", float("nan"))
254
+ is_normal = info.get("is_normal", True)
255
+ rec = info.get("rec_2groups", "—")
256
+ error = info.get("error")
257
+
258
+ items = [
259
+ col_name,
260
+ str(n),
261
+ f"{sw_p:.4f}" if sw_p == sw_p else "—",
262
+ f"{skew:+.3f}" if skew == skew else "—",
263
+ f"{kurt:+.3f}" if kurt == kurt else "—",
264
+ "Normal" if is_normal else "Non-normal",
265
+ "—" if error else rec,
266
+ ]
267
+ for c_idx, text in enumerate(items):
268
+ itm = QTableWidgetItem(text)
269
+ itm.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
270
+ itm.setFlags(itm.flags() & ~Qt.ItemFlag.ItemIsEditable)
271
+ self._summary_tbl.setItem(row, c_idx, itm)
272
+
273
+ # Colour rows
274
+ bg = _verdict_color(is_normal) if not error else _GRAY
275
+ for c_idx in range(self._summary_tbl.columnCount()):
276
+ self._summary_tbl.item(row, c_idx).setBackground(bg)
277
+
278
+ # ------------------------------------------------------------------
279
+ # Visual tab helpers
280
+ # ------------------------------------------------------------------
281
+ def _populate_col_selector(self):
282
+ self._col_cb.blockSignals(True)
283
+ self._col_cb.clear()
284
+ if self._result:
285
+ self._col_cb.addItems(list(self._result.details.keys()))
286
+ self._col_cb.blockSignals(False)
287
+ if self._col_cb.count():
288
+ self._update_visual(self._col_cb.currentText())
289
+
290
+ def _update_visual(self, col_name: str):
291
+ if not self._result or not col_name:
292
+ return
293
+ t = self._current_table()
294
+ if t is None:
295
+ return
296
+
297
+ info = self._result.details.get(col_name, {})
298
+ if info.get("error"):
299
+ return
300
+
301
+ # ── Histogram + QQ plot ───────────────────────────────────────
302
+ from ..stats.distribution import fit_distributions
303
+ from ..plots.distribution_plot import plot_distribution
304
+
305
+ # Reconstruct fits list with actual scipy params
306
+ arr = next(c.valid_values() for c in t.columns if c.name == col_name)
307
+ fits = fit_distributions(arr)
308
+
309
+ fig = plot_distribution(t, col_name, fits=fits)
310
+ self._dist_fig = fig
311
+ self._set_canvas(fig)
312
+
313
+ # ── Fitting table ─────────────────────────────────────────────
314
+ self._fit_tbl.setRowCount(0)
315
+ for fit in fits[:5]:
316
+ r = self._fit_tbl.rowCount()
317
+ self._fit_tbl.insertRow(r)
318
+ ok_str = "Yes" if fit["ks_p"] >= 0.05 else "No"
319
+ for c_idx, txt in enumerate([
320
+ fit["distribution"],
321
+ f"{fit['aic']:.1f}",
322
+ f"{fit['bic']:.1f}",
323
+ f"{fit['ks_p']:.4f}",
324
+ ok_str,
325
+ ]):
326
+ itm = QTableWidgetItem(txt)
327
+ itm.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
328
+ self._fit_tbl.setItem(r, c_idx, itm)
329
+ if c_idx == 4:
330
+ itm.setBackground(_GREEN if ok_str == "Yes" else _RED)
331
+ if r == 0: # highlight best row
332
+ for c_idx in range(self._fit_tbl.columnCount()):
333
+ self._fit_tbl.item(r, c_idx).setFont(
334
+ QFont("", -1, QFont.Weight.Bold)
335
+ )
336
+
337
+ def _set_canvas(self, fig):
338
+ """Replace the current matplotlib canvas with *fig*."""
339
+ # Remove old canvas
340
+ if self._mpl_canvas is not None:
341
+ self._detail_canvas_layout.removeWidget(self._mpl_canvas)
342
+ self._mpl_canvas.setParent(None)
343
+ self._mpl_canvas = None
344
+ # Remove placeholder
345
+ if self._placeholder_label is not None:
346
+ self._detail_canvas_layout.removeWidget(self._placeholder_label)
347
+ self._placeholder_label.setParent(None)
348
+ self._placeholder_label = None
349
+
350
+ canvas = StyledCanvas(fig)
351
+ canvas.setMinimumHeight(260)
352
+ self._detail_canvas_layout.addWidget(canvas)
353
+ self._mpl_canvas = canvas
354
+ canvas.draw()
355
+
356
+ # ------------------------------------------------------------------
357
+ # Advisor panel
358
+ # ------------------------------------------------------------------
359
+ def _on_summary_select(self):
360
+ rows = self._summary_tbl.selectedItems()
361
+ if not rows:
362
+ return
363
+ row = self._summary_tbl.row(rows[0])
364
+ col_n = self._summary_tbl.item(row, 0).text()
365
+ if self._result is None:
366
+ return
367
+ info = self._result.details.get(col_n, {})
368
+ if info.get("error"):
369
+ self._advisor_label.setText(f"{col_n}: insufficient data.")
370
+ self._run_rec_btn.setEnabled(False)
371
+ return
372
+
373
+ is_normal = info.get("is_normal", True)
374
+ rec2 = info.get("rec_2groups", "—")
375
+ rec3 = info.get("rec_3groups", "—")
376
+ rec_corr = info.get("rec_correlation", "—")
377
+ best_fit = info.get("best_fit", "—")
378
+ sw_p = info.get("shapiro_p", float("nan"))
379
+ verdict = "normally distributed" if is_normal else "NOT normally distributed"
380
+
381
+ msg = (
382
+ f"{col_n}: {verdict} (Shapiro-Wilk p = {sw_p:.4f})\n\n"
383
+ f" 2-group comparison : {rec2}\n"
384
+ f" 3+ groups : {rec3}\n"
385
+ f" Best-fit distribution: {best_fit}"
386
+ )
387
+ self._advisor_label.setText(msg)
388
+ self._run_rec_btn.setEnabled(True)
389
+ # Store the recommended analysis-dialog tab index
390
+ self._run_rec_btn._tab_idx = 0 if is_normal else 0 # always t-test/MW tab
391
+ self._run_rec_btn._nonpar = not is_normal
392
+
393
+ # Also update the visual tab to show this column
394
+ self._col_cb.setCurrentText(col_n)
395
+ if self._tabs.currentIndex() != 0:
396
+ self._update_visual(col_n)
397
+
398
+ def _open_recommended_test(self):
399
+ btn = self._run_rec_btn
400
+ nonpar = getattr(btn, "_nonpar", False)
401
+ # Emit signal with tab 0 (t-test tab); MainWindow sets non-parametric checkbox
402
+ self.run_test_requested.emit(0)
403
+ # Pass the non-parametric preference via a custom attribute the parent can read
404
+ self._nonpar_recommendation = nonpar
405
+ self.accept()
406
+
407
+ # ------------------------------------------------------------------
408
+ # Export helpers
409
+ # ------------------------------------------------------------------
410
+ def _copy_report(self):
411
+ QApplication.clipboard().setText(self._text_box.toPlainText())
412
+
413
+ @styles.styled
414
+ def _copy_plot(self):
415
+ if self._dist_fig is None:
416
+ return
417
+ buf = io.BytesIO()
418
+ self._dist_fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
419
+ buf.seek(0)
420
+ img = QImage()
421
+ img.loadFromData(buf.read())
422
+ QApplication.clipboard().setImage(img)
423
+
424
+ # ------------------------------------------------------------------
425
+ # Public getters (for MainWindow integration)
426
+ # ------------------------------------------------------------------
427
+ def get_result(self):
428
+ return self._result
429
+
430
+ def nonpar_recommended(self) -> bool:
431
+ return getattr(self, "_nonpar_recommendation", False)
@@ -0,0 +1,236 @@
1
+ """
2
+ Multi-panel figure layout dialog.
3
+ Lets the user pick N graphs from the project and arrange them in a grid,
4
+ then export as a single publication-quality figure.
5
+ """
6
+
7
+ import math
8
+
9
+ import matplotlib
10
+ matplotlib.use("QtAgg")
11
+ from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
12
+ from matplotlib.figure import Figure
13
+ import matplotlib.pyplot as plt
14
+
15
+ from qtpy.QtWidgets import (
16
+ QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, QComboBox,
17
+ QSpinBox, QListWidget, QListWidgetItem, QPushButton, QLabel,
18
+ QFileDialog, QAbstractItemView, QWidget, QSplitter, QMessageBox,
19
+ )
20
+ from qtpy.QtCore import Qt
21
+
22
+ from ..models.project import GraphConfig, Project
23
+ from .. import plots as plot_lib
24
+ from ..plots import styles
25
+
26
+
27
+ class FigureLayoutDialog(QDialog):
28
+ """Compose a multi-panel figure from the project's existing graphs."""
29
+
30
+ def __init__(self, project: Project, render_fn, parent=None):
31
+ """render_fn(gc) -> matplotlib Figure (same logic as MainWindow._render_graph)."""
32
+ super().__init__(parent)
33
+ self.setWindowTitle("Multi-Panel Figure Layout")
34
+ self.resize(1000, 680)
35
+ self._project = project
36
+ self._render_fn = render_fn
37
+
38
+ root = QHBoxLayout(self)
39
+ splitter = QSplitter(Qt.Orientation.Horizontal)
40
+ root.addWidget(splitter)
41
+
42
+ # --- Left panel: graph picker + layout controls ---
43
+ left = QWidget()
44
+ left_layout = QVBoxLayout(left)
45
+ left_layout.setContentsMargins(6, 6, 6, 6)
46
+
47
+ left_layout.addWidget(QLabel("Available graphs (select to add):"))
48
+ self._graph_list = QListWidget()
49
+ self._graph_list.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection)
50
+ for gc in project.graphs:
51
+ item = QListWidgetItem(gc.name)
52
+ item.setData(Qt.ItemDataRole.UserRole, gc)
53
+ self._graph_list.addItem(item)
54
+ left_layout.addWidget(self._graph_list)
55
+
56
+ form = QFormLayout()
57
+ self._cols_spin = QSpinBox(); self._cols_spin.setRange(1, 6); self._cols_spin.setValue(2)
58
+ form.addRow("Columns:", self._cols_spin)
59
+ self._figw_spin = QSpinBox(); self._figw_spin.setRange(4, 24); self._figw_spin.setValue(10)
60
+ form.addRow("Figure width (in):", self._figw_spin)
61
+ self._figh_spin = QSpinBox(); self._figh_spin.setRange(3, 20); self._figh_spin.setValue(8)
62
+ form.addRow("Figure height (in):", self._figh_spin)
63
+ left_layout.addLayout(form)
64
+
65
+ btn_row = QHBoxLayout()
66
+ preview_btn = QPushButton("Preview")
67
+ preview_btn.clicked.connect(self._preview)
68
+ export_btn = QPushButton("Export…")
69
+ export_btn.clicked.connect(self._export)
70
+ btn_row.addWidget(preview_btn)
71
+ btn_row.addWidget(export_btn)
72
+ left_layout.addLayout(btn_row)
73
+
74
+ splitter.addWidget(left)
75
+
76
+ # --- Right panel: preview canvas ---
77
+ right = QWidget()
78
+ right_layout = QVBoxLayout(right)
79
+ right_layout.setContentsMargins(0, 0, 0, 0)
80
+ self._preview_fig = Figure(figsize=(8, 6))
81
+ self._canvas = FigureCanvasQTAgg(self._preview_fig)
82
+ right_layout.addWidget(self._canvas)
83
+ splitter.addWidget(right)
84
+ splitter.setSizes([260, 740])
85
+
86
+ # ------------------------------------------------------------------
87
+ def _selected_graphs(self) -> list[GraphConfig]:
88
+ return [
89
+ item.data(Qt.ItemDataRole.UserRole)
90
+ for item in self._graph_list.selectedItems()
91
+ ]
92
+
93
+ @styles.styled
94
+ def _build_figure(self, figsize: tuple | None = None) -> Figure | None:
95
+ graphs = self._selected_graphs()
96
+ if not graphs:
97
+ QMessageBox.information(self, "No graphs", "Select at least one graph from the list.")
98
+ return None
99
+
100
+ n = len(graphs)
101
+ ncols = min(self._cols_spin.value(), n)
102
+ nrows = math.ceil(n / ncols)
103
+ fw = self._figw_spin.value() if figsize is None else figsize[0]
104
+ fh = self._figh_spin.value() if figsize is None else figsize[1]
105
+
106
+ fig, axes = plt.subplots(nrows, ncols, figsize=(fw, fh), squeeze=False)
107
+ plt.close(fig) # we'll redraw manually
108
+
109
+ fig = Figure(figsize=(fw, fh))
110
+ for idx, gc in enumerate(graphs):
111
+ row, col = divmod(idx, ncols)
112
+ ax_main = fig.add_subplot(nrows, ncols, idx + 1)
113
+ try:
114
+ src_fig = self._render_fn(gc)
115
+ if src_fig is not None and src_fig.get_axes():
116
+ src_ax = src_fig.get_axes()[0]
117
+ # Copy lines, collections, patches into ax_main
118
+ import matplotlib
119
+ for line in src_ax.get_lines():
120
+ ax_main.add_line(
121
+ matplotlib.lines.Line2D(
122
+ line.get_xdata(), line.get_ydata(),
123
+ color=line.get_color(), linewidth=line.get_linewidth(),
124
+ linestyle=line.get_linestyle(), alpha=line.get_alpha() or 1,
125
+ )
126
+ )
127
+ # Simpler: use the title and axis labels
128
+ ax_main.set_title(src_ax.get_title(), fontsize=9)
129
+ ax_main.set_xlabel(src_ax.get_xlabel(), fontsize=8)
130
+ ax_main.set_ylabel(src_ax.get_ylabel(), fontsize=8)
131
+ ax_main.autoscale()
132
+ plt.close(src_fig)
133
+ except Exception as e:
134
+ ax_main.text(0.5, 0.5, f"Error:\n{e}", ha="center", va="center",
135
+ transform=ax_main.transAxes, fontsize=7)
136
+
137
+ # Hide unused axes
138
+ for idx in range(n, nrows * ncols):
139
+ row, col = divmod(idx, ncols)
140
+ fig.add_subplot(nrows, ncols, idx + 1).set_visible(False)
141
+
142
+ fig.tight_layout(pad=1.5)
143
+ return fig
144
+
145
+ @styles.styled
146
+ def _preview(self):
147
+ """Render a live preview by drawing each sub-figure into subplots."""
148
+ graphs = self._selected_graphs()
149
+ if not graphs:
150
+ QMessageBox.information(self, "No graphs", "Select at least one graph.")
151
+ return
152
+
153
+ n = len(graphs)
154
+ ncols = min(self._cols_spin.value(), n)
155
+ nrows = math.ceil(n / ncols)
156
+ fw = self._figw_spin.value()
157
+ fh = self._figh_spin.value()
158
+
159
+ self._preview_fig.clear()
160
+ self._preview_fig.set_size_inches(fw, fh)
161
+
162
+ for idx, gc in enumerate(graphs):
163
+ ax = self._preview_fig.add_subplot(nrows, ncols, idx + 1)
164
+ try:
165
+ src_fig = self._render_fn(gc)
166
+ if src_fig and src_fig.get_axes():
167
+ src_ax = src_fig.get_axes()[0]
168
+ # Efficient preview: copy rendered image via buffer
169
+ import io
170
+ buf = io.BytesIO()
171
+ src_fig.savefig(buf, format="png", dpi=72, bbox_inches="tight")
172
+ buf.seek(0)
173
+ import matplotlib.image as mpimg
174
+ img = mpimg.imread(buf)
175
+ ax.imshow(img, aspect="auto")
176
+ ax.set_title(gc.name, fontsize=8)
177
+ ax.axis("off")
178
+ plt.close(src_fig)
179
+ except Exception as exc:
180
+ ax.text(0.5, 0.5, str(exc), ha="center", va="center",
181
+ transform=ax.transAxes, fontsize=7, wrap=True)
182
+ ax.axis("off")
183
+
184
+ self._preview_fig.tight_layout(pad=0.5)
185
+ self._canvas.figure = self._preview_fig
186
+ self._preview_fig.set_canvas(self._canvas)
187
+ self._canvas.draw()
188
+
189
+ @styles.styled
190
+ def _export(self):
191
+ graphs = self._selected_graphs()
192
+ if not graphs:
193
+ QMessageBox.information(self, "No graphs", "Select at least one graph.")
194
+ return
195
+ path, _ = QFileDialog.getSaveFileName(
196
+ self, "Export Figure", "",
197
+ "PNG (*.png);;SVG (*.svg);;PDF (*.pdf);;TIFF (*.tiff)",
198
+ )
199
+ if not path:
200
+ return
201
+
202
+ n = len(graphs)
203
+ ncols = min(self._cols_spin.value(), n)
204
+ nrows = math.ceil(n / ncols)
205
+ fw, fh = self._figw_spin.value(), self._figh_spin.value()
206
+
207
+ fig, axes = plt.subplots(nrows, ncols, figsize=(fw, fh), squeeze=False)
208
+ for idx, gc in enumerate(graphs):
209
+ row, col = divmod(idx, ncols)
210
+ ax = axes[row][col]
211
+ try:
212
+ src_fig = self._render_fn(gc)
213
+ if src_fig and src_fig.get_axes():
214
+ import io
215
+ buf = io.BytesIO()
216
+ src_fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
217
+ buf.seek(0)
218
+ import matplotlib.image as mpimg
219
+ img = mpimg.imread(buf)
220
+ ax.imshow(img, aspect="auto")
221
+ ax.set_title(gc.name, fontsize=9)
222
+ ax.axis("off")
223
+ plt.close(src_fig)
224
+ except Exception as exc:
225
+ ax.text(0.5, 0.5, str(exc), ha="center", va="center",
226
+ transform=ax.transAxes, fontsize=7)
227
+ ax.axis("off")
228
+
229
+ for idx in range(n, nrows * ncols):
230
+ row, col = divmod(idx, ncols)
231
+ axes[row][col].set_visible(False)
232
+
233
+ fig.tight_layout(pad=1.0)
234
+ fig.savefig(path, dpi=300, bbox_inches="tight")
235
+ plt.close(fig)
236
+ QMessageBox.information(self, "Exported", f"Figure saved to:\n{path}")