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.
Files changed (110) hide show
  1. statstudio/__init__.py +9 -0
  2. statstudio/__main__.py +3 -0
  3. statstudio/app.py +83 -0
  4. statstudio/cli.py +116 -0
  5. statstudio/core/__init__.py +3 -0
  6. statstudio/core/archive.py +27 -0
  7. statstudio/core/commands.py +67 -0
  8. statstudio/core/formula_catalog.py +74 -0
  9. statstudio/core/formulas.py +605 -0
  10. statstudio/core/joins.py +123 -0
  11. statstudio/core/project.py +358 -0
  12. statstudio/core/runtime.py +321 -0
  13. statstudio/core/scripting.py +594 -0
  14. statstudio/core/table.py +796 -0
  15. statstudio/core/transform.py +450 -0
  16. statstudio/feature_help.py +595 -0
  17. statstudio/io/__init__.py +3 -0
  18. statstudio/io/docx.py +201 -0
  19. statstudio/io/export.py +99 -0
  20. statstudio/io/file_import.py +199 -0
  21. statstudio/io/odbc.py +334 -0
  22. statstudio/io/sample_data.py +164 -0
  23. statstudio/io/table_io.py +118 -0
  24. statstudio/plots/__init__.py +19 -0
  25. statstudio/plots/advanced.py +651 -0
  26. statstudio/plots/basic.py +957 -0
  27. statstudio/plots/bayesian_plots.py +94 -0
  28. statstudio/plots/common.py +334 -0
  29. statstudio/plots/diagnostics.py +214 -0
  30. statstudio/plots/doe_plots.py +235 -0
  31. statstudio/plots/plotly_builders.py +719 -0
  32. statstudio/plots/predictive_plots.py +72 -0
  33. statstudio/plots/registry.py +251 -0
  34. statstudio/plugins.py +111 -0
  35. statstudio/resources/help_topics.json +13195 -0
  36. statstudio/resources/logo.ico +0 -0
  37. statstudio/resources/logo.png +0 -0
  38. statstudio/resources/statstudio.svg +8 -0
  39. statstudio/stats/__init__.py +42 -0
  40. statstudio/stats/bayesian.py +1094 -0
  41. statstudio/stats/bayesian_optimization.py +590 -0
  42. statstudio/stats/common.py +140 -0
  43. statstudio/stats/correlation.py +135 -0
  44. statstudio/stats/custom_doe.py +1714 -0
  45. statstudio/stats/descriptive.py +200 -0
  46. statstudio/stats/desirability.py +132 -0
  47. statstudio/stats/distributions.py +331 -0
  48. statstudio/stats/doe.py +1070 -0
  49. statstudio/stats/hypothesis.py +1305 -0
  50. statstudio/stats/multivariate.py +307 -0
  51. statstudio/stats/optimal_doe.py +264 -0
  52. statstudio/stats/power.py +194 -0
  53. statstudio/stats/predictive.py +605 -0
  54. statstudio/stats/profiler.py +379 -0
  55. statstudio/stats/quality.py +1218 -0
  56. statstudio/stats/regression.py +1600 -0
  57. statstudio/stats/results.py +235 -0
  58. statstudio/stats/simulator.py +95 -0
  59. statstudio/stats/survival.py +637 -0
  60. statstudio/stats/timeseries.py +643 -0
  61. statstudio/stats/tolerance.py +154 -0
  62. statstudio/ui/__init__.py +0 -0
  63. statstudio/ui/analysis_hub.py +271 -0
  64. statstudio/ui/command_catalog.py +460 -0
  65. statstudio/ui/command_palette.py +55 -0
  66. statstudio/ui/console.py +239 -0
  67. statstudio/ui/dialogs/__init__.py +0 -0
  68. statstudio/ui/dialogs/advanced_dialogs.py +392 -0
  69. statstudio/ui/dialogs/base.py +537 -0
  70. statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
  71. statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
  72. statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
  73. statstudio/ui/dialogs/doe_dialogs.py +220 -0
  74. statstudio/ui/dialogs/extended_dialogs.py +665 -0
  75. statstudio/ui/dialogs/graph_builder.py +139 -0
  76. statstudio/ui/dialogs/help_dialog.py +207 -0
  77. statstudio/ui/dialogs/help_topics.py +280 -0
  78. statstudio/ui/dialogs/lazy.py +184 -0
  79. statstudio/ui/dialogs/odbc_dialog.py +311 -0
  80. statstudio/ui/dialogs/plot_dialog.py +1385 -0
  81. statstudio/ui/dialogs/report_composer.py +218 -0
  82. statstudio/ui/dialogs/script_dialogs.py +267 -0
  83. statstudio/ui/dialogs/stats_dialogs.py +1688 -0
  84. statstudio/ui/dialogs/table_dialogs.py +997 -0
  85. statstudio/ui/dialogs/window.py +58 -0
  86. statstudio/ui/docks/__init__.py +0 -0
  87. statstudio/ui/formula_editor.py +121 -0
  88. statstudio/ui/icons.py +257 -0
  89. statstudio/ui/jobs.py +179 -0
  90. statstudio/ui/main_window.py +3934 -0
  91. statstudio/ui/plot_interaction.py +178 -0
  92. statstudio/ui/profiler_widget.py +437 -0
  93. statstudio/ui/recent.py +82 -0
  94. statstudio/ui/reports/__init__.py +0 -0
  95. statstudio/ui/reports/report_view.py +1632 -0
  96. statstudio/ui/script_jobs.py +35 -0
  97. statstudio/ui/scripts_panel.py +271 -0
  98. statstudio/ui/table_document.py +233 -0
  99. statstudio/ui/table_model.py +285 -0
  100. statstudio/ui/table_view.py +285 -0
  101. statstudio/ui/theme.py +645 -0
  102. statstudio/ui/welcome.py +453 -0
  103. statstudio/ui/window_controls.py +53 -0
  104. statstudio/ui/workers.py +53 -0
  105. statstudio-0.1.0.dist-info/METADATA +261 -0
  106. statstudio-0.1.0.dist-info/RECORD +110 -0
  107. statstudio-0.1.0.dist-info/WHEEL +5 -0
  108. statstudio-0.1.0.dist-info/entry_points.txt +5 -0
  109. statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
  110. statstudio-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1385 @@
1
+ from __future__ import annotations
2
+
3
+ import pandas as pd
4
+ from scipy import stats as scipy_stats
5
+ from PySide6.QtCore import Qt, QTimer
6
+ from PySide6.QtGui import QColor
7
+ from PySide6.QtWidgets import (
8
+ QAbstractItemView,
9
+ QCheckBox,
10
+ QColorDialog,
11
+ QComboBox,
12
+ QDialogButtonBox,
13
+ QDoubleSpinBox,
14
+ QFormLayout,
15
+ QHBoxLayout,
16
+ QLabel,
17
+ QLineEdit,
18
+ QPushButton,
19
+ QScrollArea,
20
+ QSlider,
21
+ QSpinBox,
22
+ QTableWidget,
23
+ QTableWidgetItem,
24
+ QVBoxLayout,
25
+ QWidget,
26
+ )
27
+
28
+ from statstudio.core.table import DataTable
29
+ from statstudio import plugins
30
+ from statstudio.plots.registry import PLOT_DEFINITIONS, build_figure
31
+ from statstudio.stats.results import AnalysisResult, PlotSpec
32
+ from statstudio.ui.dialogs.base import (
33
+ BaseDialog,
34
+ ColumnDragList,
35
+ ColumnDropCombo,
36
+ ColumnDropZone,
37
+ )
38
+ from statstudio.ui.dialogs.graph_builder import GraphBuilderCanvas
39
+ from statstudio.ui.dialogs.window import IndependentDialog
40
+
41
+
42
+ def _float_or_none(value: str) -> float | None:
43
+ value = (value or "").strip()
44
+ if not value:
45
+ return None
46
+ try:
47
+ return float(value)
48
+ except ValueError:
49
+ return None
50
+
51
+
52
+ def _float_list(text: str) -> list[float]:
53
+ values = []
54
+ for part in text.replace(";", ",").split(","):
55
+ part = part.strip()
56
+ if not part:
57
+ continue
58
+ try:
59
+ values.append(float(part))
60
+ except ValueError:
61
+ continue
62
+ return values
63
+
64
+
65
+ class _ColorButton(QPushButton):
66
+ def __init__(self, color_value: str | None = None, parent=None) -> None:
67
+ super().__init__(parent)
68
+ self._color = str(color_value) if color_value else ""
69
+ self.clicked.connect(self._choose)
70
+ self._refresh()
71
+
72
+ def color(self) -> str:
73
+ return self._color
74
+
75
+ def set_color(self, value: str | None) -> None:
76
+ self._color = str(value) if value else ""
77
+ self._refresh()
78
+
79
+ def _choose(self) -> None:
80
+ initial = QColor(self._color) if self._color else QColor("#3c78b4")
81
+ selected = QColorDialog.getColor(initial, self, "Select color")
82
+ if selected.isValid():
83
+ self.set_color(selected.name())
84
+
85
+ def _refresh(self) -> None:
86
+ self.setText(self._color.upper() if self._color else "Default")
87
+ if self._color:
88
+ self.setStyleSheet(f"QPushButton {{ border-left: 14px solid {self._color}; }}")
89
+ else:
90
+ self.setStyleSheet("")
91
+
92
+
93
+ class PlotDialog(BaseDialog):
94
+ """Drag-and-drop graph dialog: one plot type with X/Y/Color/Size roles."""
95
+
96
+ def help_topic(self) -> str:
97
+ kind = str(self.kind_combo.currentData() or "Auto")
98
+ if kind in {
99
+ "histogram", "density", "box", "violin", "strip", "variability", "dotplot", "bar", "pie"
100
+ }:
101
+ return "basic-plots"
102
+ if kind in {"scatter", "bubble", "scatter3d", "line", "line3d", "area"}:
103
+ return "xy-plots"
104
+ if kind in {
105
+ "correlation_heatmap", "heatmap", "pairplot", "parallel_coordinates",
106
+ "contour", "surface", "mosaic", "pareto"
107
+ }:
108
+ return "multivariate-plots"
109
+ return "graph-builder"
110
+
111
+ def __init__(self, table: DataTable, parent=None, default_kind: str | None = None) -> None:
112
+ super().__init__(table, "Graph Builder", parent)
113
+ self._tabs.clear()
114
+ self.definitions = {**PLOT_DEFINITIONS, **plugins.registry.plot_definitions()}
115
+ self.kind_by_label = {definition["label"]: kind for kind, definition in self.definitions.items()}
116
+ self._syncing = False
117
+ self._preview_figure = None
118
+ self._preview_canvas = None
119
+ self._preview_timer = QTimer(self)
120
+ self._preview_timer.setSingleShot(True)
121
+ self._preview_timer.setInterval(120)
122
+ self._preview_timer.timeout.connect(self._update_preview)
123
+ self._build_main_page()
124
+ self._role_widgets = {
125
+ "x": self.canvas.x_zone,
126
+ "y": self.canvas.y_zone,
127
+ "y2": self.canvas.y2_zone,
128
+ "size": self.canvas.size_zone,
129
+ "group": self.canvas.group_zone,
130
+ "shape": self.canvas.shape_zone,
131
+ "z": self.z_zone,
132
+ "facet": self.facet_zone,
133
+ "row": self.row_zone,
134
+ "column": self.column_zone,
135
+ "category": self.category_zone,
136
+ "count": self.count_zone,
137
+ "error_column": self.error_zone,
138
+ "columns": self.columns_zone,
139
+ }
140
+ self._canvas_roles = {"x", "y", "y2", "group", "size", "shape"}
141
+ self.kind_combo.currentIndexChanged.connect(self._kind_changed)
142
+ for zone in self._role_widgets.values():
143
+ zone.columns_changed.connect(self._roles_edited)
144
+ self._set_editor_kind(default_kind or "Auto")
145
+ self._update_roles()
146
+ self._connect_preview_signals()
147
+ self.finished.connect(lambda _result: self._clear_preview())
148
+ self._update_preview()
149
+ self.resize(1280, 820)
150
+
151
+ # ------------------------------------------------------------------
152
+ # UI construction
153
+ # ------------------------------------------------------------------
154
+ def _build_main_page(self) -> None:
155
+ page = QWidget()
156
+ row = QHBoxLayout(page)
157
+
158
+ left = QVBoxLayout()
159
+ left.setSpacing(4)
160
+ columns_label = QLabel("Columns")
161
+ columns_label.setStyleSheet("font-weight:600;")
162
+ left.addWidget(columns_label)
163
+ self.column_palette = ColumnDragList(self.table.columns)
164
+ self.column_palette.setFixedWidth(190)
165
+ left.addWidget(self.column_palette, 1)
166
+ left_widget = QWidget()
167
+ left_widget.setLayout(left)
168
+ left_widget.setFixedWidth(210)
169
+ row.addWidget(left_widget, 0)
170
+
171
+ center = QVBoxLayout()
172
+ form = QFormLayout()
173
+ self.kind_combo = QComboBox()
174
+ self.kind_combo.addItem("Auto", "Auto")
175
+ for kind, definition in self.definitions.items():
176
+ self.kind_combo.addItem(definition["label"], kind)
177
+ form.addRow("Plot type", self.kind_combo)
178
+ center.addLayout(form)
179
+
180
+ self.canvas = GraphBuilderCanvas()
181
+ self.canvas.set_allowed_columns(self.table.columns)
182
+ self.x_zone = self.canvas.x_zone
183
+ self.y_zone = self.canvas.y_zone
184
+ self.y2_zone = self.canvas.y2_zone
185
+ self.group_zone = self.canvas.group_zone
186
+ self.size_zone = self.canvas.size_zone
187
+ self.shape_zone = self.canvas.shape_zone
188
+ center.addWidget(self.canvas, 1)
189
+ center.addWidget(self._build_more_variables_row(), 0)
190
+
191
+ self.preview_status = QLabel("Preview")
192
+ self.preview_status.setWordWrap(True)
193
+ self.preview_status.setStyleSheet("color:#5a6270;")
194
+ center.addWidget(self.preview_status)
195
+ row.addLayout(center, 1)
196
+ self._tabs.addTab(page, "Graph")
197
+ self._tabs.tabBar().hide()
198
+
199
+ def _build_more_variables_row(self) -> QWidget:
200
+ self._more_scroll = QScrollArea()
201
+ self._more_scroll.setWidgetResizable(True)
202
+ self._more_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
203
+ self._more_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
204
+ self._more_scroll.setFixedHeight(86)
205
+ container = QWidget()
206
+ self._more_layout = QHBoxLayout(container)
207
+ self._more_layout.setContentsMargins(2, 2, 2, 2)
208
+ self._more_layout.setSpacing(8)
209
+ self._more_layout.addStretch(1)
210
+ self._more_scroll.setWidget(container)
211
+ self._zone_wrappers: dict[ColumnDropZone, tuple[QWidget, QLabel]] = {}
212
+ self.z_zone = self._add_row_zone("Z / third axis")
213
+ self.facet_zone = self._add_row_zone("Facet / page")
214
+ self.row_zone = self._add_row_zone("Row variable")
215
+ self.column_zone = self._add_row_zone("Column variable")
216
+ self.category_zone = self._add_row_zone("Category")
217
+ self.count_zone = self._add_row_zone("Count")
218
+ self.error_zone = self._add_row_zone("Bar error values")
219
+ self.columns_zone = self._add_row_zone("Variables", width=240, multi=True)
220
+ return self._more_scroll
221
+
222
+ def _add_row_zone(self, label: str, *, width: int = 170, multi: bool = False) -> ColumnDropZone:
223
+ wrapper = QWidget()
224
+ layout = QVBoxLayout(wrapper)
225
+ layout.setContentsMargins(0, 0, 0, 0)
226
+ layout.setSpacing(2)
227
+ label_widget = QLabel(label)
228
+ label_widget.setStyleSheet("color:#5a6270; font-size:11px;")
229
+ label_widget.setFixedWidth(width)
230
+ zone = ColumnDropZone("(drag columns)", multi=multi)
231
+ zone.setFixedWidth(width)
232
+ zone.allowed_columns = set(self.table.columns)
233
+ layout.addWidget(label_widget)
234
+ layout.addWidget(zone)
235
+ self._more_layout.insertWidget(self._more_layout.count() - 1, wrapper)
236
+ self._zone_wrappers[zone] = (wrapper, label_widget)
237
+ return zone
238
+
239
+ def _connect_preview_signals(self) -> None:
240
+ for combo in self.findChildren(QComboBox):
241
+ combo.currentIndexChanged.connect(self._schedule_preview)
242
+ for spin in self.findChildren(QSpinBox):
243
+ spin.valueChanged.connect(self._schedule_preview)
244
+ for box in self.findChildren(QCheckBox):
245
+ box.stateChanged.connect(self._schedule_preview)
246
+ for edit in self.findChildren(QLineEdit):
247
+ edit.textChanged.connect(self._schedule_preview)
248
+
249
+ # ------------------------------------------------------------------
250
+ # Kind / roles
251
+ # ------------------------------------------------------------------
252
+ def _raw_roles(self) -> dict:
253
+ return {key: list(widget.columns()) for key, widget in self._role_widgets.items()}
254
+
255
+ def _live_roles(self) -> dict:
256
+ kind = self._editor_kind()
257
+ if kind == "Auto":
258
+ allowed = {"x", "y", "y2", "group"}
259
+ else:
260
+ allowed = set(self.definitions.get(kind, {}).get("roles", ["x", "y"]))
261
+ return {key: values for key, values in self._raw_roles().items() if key in allowed}
262
+
263
+ def _roles_edited(self, *_args) -> None:
264
+ if self._syncing:
265
+ return
266
+ self._update_roles()
267
+ self._schedule_preview()
268
+
269
+ def _kind_changed(self, *_args) -> None:
270
+ if self._syncing:
271
+ return
272
+ self._update_roles()
273
+ self._schedule_preview()
274
+
275
+ def _set_editor_kind(self, kind: str) -> None:
276
+ position = self.kind_combo.findData(kind)
277
+ if position < 0:
278
+ position = self.kind_combo.findData("Auto")
279
+ if position < 0:
280
+ position = 0
281
+ blocked = self.kind_combo.blockSignals(True)
282
+ self.kind_combo.setCurrentIndex(position)
283
+ self.kind_combo.blockSignals(blocked)
284
+
285
+ def _editor_kind(self) -> str:
286
+ data = self.kind_combo.currentData()
287
+ return str(data) if data else "Auto"
288
+
289
+ def _current_kind(self) -> str:
290
+ if self._editor_kind() != "Auto":
291
+ return self._editor_kind()
292
+ return self._infer_kind()
293
+
294
+ def _is_numeric(self, column: str | None) -> bool:
295
+ return bool(
296
+ column
297
+ and column in self.table.data.columns
298
+ and pd.api.types.is_numeric_dtype(self.table.data[column])
299
+ )
300
+
301
+ def _infer_kind(self) -> str:
302
+ raw = self._raw_roles()
303
+ return self._infer_kind_from_roles({"x": raw.get("x"), "y": raw.get("y")})
304
+
305
+ def _infer_kind_from_roles(self, roles: dict) -> str:
306
+ x_columns = roles.get("x") or []
307
+ y_columns = roles.get("y") or []
308
+ z_columns = roles.get("z") or []
309
+ if z_columns and x_columns and y_columns:
310
+ return "contour"
311
+ if not x_columns or not y_columns:
312
+ return "histogram"
313
+ if self._is_numeric(x_columns[0]) and self._is_numeric(y_columns[0]):
314
+ return "scatter"
315
+ return "bar"
316
+
317
+ def _element_kind(self, element: dict) -> str:
318
+ kind = element.get("kind") or "Auto"
319
+ if kind != "Auto":
320
+ return str(kind)
321
+ return self._infer_kind_from_roles(element.get("roles") or {})
322
+
323
+ def _set_row_visible(self, widget, visible: bool) -> None:
324
+ wrapper = self._zone_wrappers.get(widget)
325
+ if wrapper is not None:
326
+ wrapper[0].setVisible(visible)
327
+ wrapper[1].setVisible(visible)
328
+ return
329
+ widget.setVisible(visible)
330
+ form = getattr(self, "_form", None)
331
+ label = form.labelForField(widget) if form is not None else None
332
+ if label is not None:
333
+ label.setVisible(visible)
334
+
335
+ def _update_roles(self, *_args) -> None:
336
+ if not hasattr(self, "canvas"):
337
+ return
338
+ editor_kind = self._editor_kind()
339
+ if editor_kind == "Auto":
340
+ canvas_roles = {"x", "y", "y2", "group"}
341
+ option_roles: set[str] = set()
342
+ else:
343
+ roles = set(self.definitions.get(editor_kind, {}).get("roles", ["x", "y"]))
344
+ canvas_roles = roles & self._canvas_roles
345
+ option_roles = roles - self._canvas_roles
346
+ for role in self._canvas_roles:
347
+ self.canvas.set_role_visible(role, role in canvas_roles)
348
+ for role, widget in self._role_widgets.items():
349
+ if role in self._canvas_roles:
350
+ continue
351
+ self._set_row_visible(widget, role in option_roles)
352
+ kind = self._current_kind()
353
+ self.canvas.y_zone.set_multi(kind != "variability")
354
+
355
+ # ------------------------------------------------------------------
356
+ # Preview lifecycle
357
+ # ------------------------------------------------------------------
358
+ def _schedule_preview(self, *_args) -> None:
359
+ self._preview_timer.start()
360
+
361
+ def _close_preview_figure(self) -> None:
362
+ if self._preview_figure is not None:
363
+ try:
364
+ import matplotlib.pyplot as plt
365
+
366
+ plt.close(self._preview_figure)
367
+ except Exception:
368
+ pass
369
+ self._preview_figure = None
370
+
371
+ def _clear_preview(self) -> None:
372
+ self._close_preview_figure()
373
+ self._preview_canvas = None
374
+ if hasattr(self, "canvas"):
375
+ self.canvas.set_status("")
376
+ self.canvas.show_placeholder()
377
+
378
+ def _update_preview(self) -> None:
379
+ if not hasattr(self, "canvas"):
380
+ return
381
+ roles = self._live_roles()
382
+ has_roles = any(roles.values())
383
+ if not has_roles and self._editor_kind() == "Auto":
384
+ self._close_preview_figure()
385
+ self._preview_canvas = None
386
+ self.canvas.show_placeholder()
387
+ self.canvas.set_status("")
388
+ self.preview_status.setText("Preview")
389
+ self.preview_status.setStyleSheet("color:#5a6270;")
390
+ return
391
+ element = {"kind": self._editor_kind(), "roles": roles, "options": {}}
392
+ try:
393
+ plots, _notes = self._plots_for_element(element)
394
+ except Exception as exc:
395
+ self._show_preview_error(str(exc))
396
+ return
397
+ if not plots:
398
+ self._show_preview_error("No preview is available for this graph.")
399
+ return
400
+ try:
401
+ figure = build_figure(plots[0])
402
+ except Exception as exc:
403
+ self._show_preview_error(str(exc))
404
+ return
405
+ self._close_preview_figure()
406
+ self._preview_figure = figure
407
+ self._preview_canvas = self.canvas.set_figure(figure)
408
+ self.canvas.set_status("")
409
+ if len(plots) > 1:
410
+ self.preview_status.setText(f"Preview: showing 1 of {len(plots)} plots")
411
+ else:
412
+ self.preview_status.setText("Preview")
413
+ self.preview_status.setStyleSheet("color:#5a6270;")
414
+
415
+ def _show_preview_error(self, message: str) -> None:
416
+ self._close_preview_figure()
417
+ self._preview_canvas = None
418
+ self.canvas.show_placeholder()
419
+ self.canvas.set_status(message)
420
+ self.preview_status.setText(f"Preview unavailable: {message}")
421
+ self.preview_status.setStyleSheet("color:#a33;")
422
+
423
+ # ------------------------------------------------------------------
424
+ # Replay
425
+ # ------------------------------------------------------------------
426
+ @staticmethod
427
+ def _set_zone_value(zone: ColumnDropZone, value) -> None:
428
+ if value is None:
429
+ zone.clear()
430
+ elif isinstance(value, (list, tuple, set)):
431
+ zone.set_columns([str(column) for column in value])
432
+ else:
433
+ zone.set_column(str(value))
434
+
435
+ def apply_params(self, params: dict | None) -> None:
436
+ params = dict(params or {})
437
+ kind = params.get("kind")
438
+ self._syncing = True
439
+ try:
440
+ if kind:
441
+ self._set_editor_kind(kind)
442
+ x_value = params.get("x_columns") or params.get("x")
443
+ y_value = params.get("y_columns") or params.get("y")
444
+ if kind in {"box", "violin", "strip"}:
445
+ x_value = x_value or params.get("group")
446
+ y_value = y_value or params.get("column")
447
+ if kind == "bar" and "error_column" not in params:
448
+ legacy_error = params.get("error")
449
+ if isinstance(legacy_error, str) and legacy_error in self.table.data.columns:
450
+ params["error_column"] = legacy_error
451
+ self._set_zone_value(self.canvas.x_zone, x_value)
452
+ self._set_zone_value(self.canvas.y_zone, y_value)
453
+ for key, zone in self._role_widgets.items():
454
+ if key in {"x", "y", "columns"} or key not in params:
455
+ continue
456
+ self._set_zone_value(zone, params[key])
457
+ if "columns" in params:
458
+ self._set_zone_value(self.columns_zone, params.get("columns"))
459
+ finally:
460
+ self._syncing = False
461
+ self._update_roles()
462
+ self._schedule_preview()
463
+
464
+ # ------------------------------------------------------------------
465
+ # Computation
466
+ # ------------------------------------------------------------------
467
+ def _row_styles(self, index) -> dict:
468
+ try:
469
+ return {row_id: self.table.row_state(row_id) for row_id in index}
470
+ except Exception:
471
+ return {}
472
+
473
+ @staticmethod
474
+ def _job_suffix(x_columns: list[str], y_columns: list[str], x_name: str | None, y_name: str | None) -> str:
475
+ if len(x_columns) <= 1 and len(y_columns) <= 1:
476
+ return ""
477
+ if len(x_columns) > 1 and len(y_columns) > 1:
478
+ return f" \u2014 {x_name} vs {y_name}"
479
+ if len(x_columns) > 1:
480
+ return f" \u2014 {x_name}"
481
+ return f" \u2014 {y_name}"
482
+
483
+ @staticmethod
484
+ def _role_one(element: dict, key: str) -> str | None:
485
+ values = (element.get("roles") or {}).get(key) or []
486
+ return values[0] if values else None
487
+
488
+ def _plots_for_element(self, element: dict) -> tuple[list[PlotSpec], list[str]]:
489
+ kind = self._element_kind(element)
490
+ roles = element.get("roles") or {}
491
+ data = self.table.plot_df()
492
+ x_columns = [column for column in roles.get("x", []) if column in data.columns]
493
+ y_columns = [column for column in roles.get("y", []) if column in data.columns]
494
+ y2 = self._role_one(element, "y2")
495
+ z = self._role_one(element, "z")
496
+ size = self._role_one(element, "size")
497
+ group = self._role_one(element, "group")
498
+ shape = self._role_one(element, "shape")
499
+ facet = self._role_one(element, "facet")
500
+ row_name = self._role_one(element, "row")
501
+ column_name = self._role_one(element, "column")
502
+ category = self._role_one(element, "category")
503
+ count = self._role_one(element, "count")
504
+ error_column = self._role_one(element, "error_column")
505
+ params: dict = {}
506
+ if shape:
507
+ params["shape"] = shape
508
+ bins = 0
509
+ distribution_label = "None"
510
+ method = "pearson"
511
+ error_label = "Standard deviation"
512
+ jobs: list[tuple[dict, str, pd.DataFrame]] = []
513
+ matrix_columns = [column for column in roles.get("columns", []) if column in data.columns]
514
+
515
+ if kind in {"histogram", "density"}:
516
+ values = x_columns or y_columns
517
+ if not values:
518
+ raise ValueError("Choose a value column.")
519
+ for value_column in values:
520
+ job_params = dict(params)
521
+ job_params.update({"column": value_column, "group": group})
522
+ if kind == "histogram":
523
+ job_params["bins"] = bins if bins > 0 else "auto"
524
+ distribution_map = {
525
+ "Normal": "norm",
526
+ "Lognormal": "lognorm",
527
+ "Weibull": "weibull_min",
528
+ "Gamma": "gamma",
529
+ "Exponential": "expon",
530
+ "Beta": "beta",
531
+ "Uniform": "uniform",
532
+ }
533
+ distribution = distribution_map.get(distribution_label)
534
+ if distribution:
535
+ values_array = pd.to_numeric(data[value_column], errors="coerce").dropna().to_numpy(dtype=float)
536
+ if len(values_array) >= 3:
537
+ try:
538
+ scipy_distribution = getattr(scipy_stats, distribution)
539
+ if distribution == "norm":
540
+ fit_args = (float(values_array.mean()), float(values_array.std(ddof=1)))
541
+ else:
542
+ fit_args = tuple(float(value) for value in scipy_distribution.fit(values_array))
543
+ job_params["distribution"] = distribution
544
+ job_params["scipy_distribution"] = distribution
545
+ job_params["fit_args"] = fit_args
546
+ except Exception:
547
+ pass
548
+ elif kind == "density":
549
+ job_params["bins"] = bins if bins > 0 else "auto"
550
+ suffix = self._job_suffix(values, [], value_column, None)
551
+ jobs.append((job_params, suffix, data))
552
+ elif kind in {"box", "violin", "strip"}:
553
+ if not y_columns:
554
+ raise ValueError("Choose a value (Y) column.")
555
+ categories = x_columns
556
+ if categories:
557
+ for category_column in categories:
558
+ for value_column in y_columns:
559
+ job_params = dict(params)
560
+ job_params.update({"column": value_column, "x": category_column})
561
+ suffix = self._job_suffix(categories, y_columns, category_column, value_column)
562
+ jobs.append((job_params, suffix, data))
563
+ else:
564
+ for value_column in y_columns:
565
+ job_params = dict(params)
566
+ job_params.update({"column": value_column})
567
+ suffix = self._job_suffix([], y_columns, None, value_column)
568
+ jobs.append((job_params, suffix, data))
569
+ elif kind in {"scatter", "bubble", "area", "line", "bar", "dotplot"}:
570
+ if not x_columns or not y_columns:
571
+ raise ValueError("Choose X and Y columns.")
572
+ for x_column in x_columns:
573
+ for y_column in y_columns:
574
+ job_params = dict(params)
575
+ job_params.update({"x": x_column, "y": y_column})
576
+ if kind in {"scatter", "bubble", "bar", "dotplot"}:
577
+ job_params["group"] = group
578
+ if kind in {"scatter", "bubble"}:
579
+ job_params["shape"] = shape
580
+ if kind == "bubble":
581
+ job_params["size"] = size
582
+ if kind in {"scatter", "line", "bar"} and y2 and y2 in data.columns and y2 != y_column:
583
+ job_params["y2"] = y2
584
+ if kind == "bar" and error_column and error_column in data.columns:
585
+ job_params["error_column"] = error_column
586
+ if kind == "area":
587
+ job_params["group"] = group
588
+ suffix = self._job_suffix(x_columns, y_columns, x_column, y_column)
589
+ jobs.append((job_params, suffix, data))
590
+ elif kind == "variability":
591
+ if not x_columns or not y_columns:
592
+ raise ValueError("Choose one or more X columns and one Y column.")
593
+ error_by_label = {
594
+ "Standard deviation": "sd",
595
+ "Standard error": "se",
596
+ "95% CI": "ci",
597
+ "Range": "range",
598
+ "None": "none",
599
+ }
600
+ job_params = dict(params)
601
+ job_params.update(
602
+ {
603
+ "x": list(x_columns),
604
+ "y": y_columns[0],
605
+ "group": group,
606
+ "error": error_by_label.get(error_label, "sd"),
607
+ }
608
+ )
609
+ jobs.append((job_params, "", data))
610
+ elif kind in {"scatter3d", "line3d"}:
611
+ if not x_columns or not y_columns or not z:
612
+ raise ValueError("Choose X, Y, and Z columns.")
613
+ job_params = dict(params)
614
+ job_params.update({"x": x_columns[0], "y": y_columns[0], "z": z, "group": group})
615
+ if kind == "scatter3d":
616
+ job_params["size"] = size
617
+ jobs.append((job_params, "", data))
618
+ elif kind in {"heatmap", "contour", "surface"}:
619
+ if not x_columns or not y_columns or not z:
620
+ raise ValueError("Choose X, Y, and Z columns.")
621
+ job_params = dict(params)
622
+ job_params.update({"x": x_columns[0], "y": y_columns[0], "z": z})
623
+ jobs.append((job_params, "", data))
624
+ elif kind == "pie":
625
+ category_column = category or (x_columns[0] if x_columns else None)
626
+ if not category_column:
627
+ raise ValueError("Choose a category column.")
628
+ job_params = dict(params)
629
+ job_params.update({"category": category_column})
630
+ if count:
631
+ job_params["count"] = count
632
+ jobs.append((job_params, "", data))
633
+ elif kind == "parallel_coordinates":
634
+ if len(matrix_columns) < 2:
635
+ raise ValueError("Check at least two variables.")
636
+ job_params = dict(params)
637
+ job_params.update({"columns": matrix_columns, "group": group})
638
+ jobs.append((job_params, "", data))
639
+ elif kind == "correlation_heatmap":
640
+ numeric_columns = [column for column in matrix_columns if pd.api.types.is_numeric_dtype(data[column])]
641
+ if len(numeric_columns) < 2:
642
+ raise ValueError("Check at least two numeric variables.")
643
+ job_params = dict(params)
644
+ job_params.update({"columns": numeric_columns, "method": method})
645
+ jobs.append((job_params, "", data))
646
+ elif kind == "pairplot":
647
+ numeric_columns = [column for column in matrix_columns if pd.api.types.is_numeric_dtype(data[column])]
648
+ if len(numeric_columns) < 2:
649
+ raise ValueError("Check at least two numeric variables.")
650
+ job_params = dict(params)
651
+ job_params.update({"columns": numeric_columns})
652
+ jobs.append((job_params, "", data))
653
+ elif kind == "mosaic":
654
+ if not row_name or not column_name:
655
+ raise ValueError("Choose row and column variables.")
656
+ job_params = dict(params)
657
+ job_params.update({"row": row_name, "column": column_name})
658
+ jobs.append((job_params, "", data))
659
+ elif kind == "pareto":
660
+ category_column = category or (x_columns[0] if x_columns else None)
661
+ if not category_column:
662
+ raise ValueError("Choose a category column.")
663
+ job_params = dict(params)
664
+ if count:
665
+ job_params.update({"category": category_column, "count": count})
666
+ jobs.append((job_params, "", data))
667
+ else:
668
+ counts = (
669
+ data[category_column]
670
+ .fillna("(missing)")
671
+ .astype(str)
672
+ .value_counts()
673
+ .rename_axis(category_column)
674
+ .reset_index(name="Count")
675
+ )
676
+ counts["Cumulative Percent"] = counts["Count"] / counts["Count"].sum() * 100
677
+ counts["Cumulative Percent"] = counts["Cumulative Percent"].cumsum()
678
+ job_params.update(
679
+ {"category": category_column, "count": "Count", "cumulative": "Cumulative Percent"}
680
+ )
681
+ jobs.append((job_params, "", counts))
682
+ else:
683
+ raise ValueError("Unsupported plot type.")
684
+
685
+ facet_levels = []
686
+ notes = []
687
+ if facet and facet in data.columns:
688
+ levels = list(pd.unique(data[facet]))
689
+ facet_levels = levels[:12]
690
+ if len(levels) > 12:
691
+ notes.append(f"Facet levels truncated to the first 12 of {len(levels)}.")
692
+ entries: list[tuple[dict, pd.DataFrame, str]] = []
693
+ for job_params, suffix, job_data in jobs:
694
+ if facet_levels and facet in job_data.columns:
695
+ for level in facet_levels:
696
+ if pd.isna(level):
697
+ chunk = job_data[job_data[facet].isna()]
698
+ level_label = "(missing)"
699
+ else:
700
+ chunk = job_data[job_data[facet] == level]
701
+ level_label = level
702
+ entries.append(
703
+ (dict(job_params), chunk, f"{kind.title()}{suffix} \u2014 {facet} = {level_label}")
704
+ )
705
+ else:
706
+ entries.append((dict(job_params), job_data, f"{kind.title()}{suffix}"))
707
+
708
+ plots = [
709
+ PlotSpec(
710
+ kind=kind,
711
+ params=job_params,
712
+ title=job_title,
713
+ data=chunk,
714
+ row_ids=list(chunk.index),
715
+ row_styles=self._row_styles(chunk.index),
716
+ )
717
+ for job_params, chunk, job_title in entries
718
+ ]
719
+ return plots, notes
720
+
721
+ def compute(self) -> AnalysisResult:
722
+ element = {
723
+ "kind": self._editor_kind(),
724
+ "roles": self._live_roles(),
725
+ "options": {},
726
+ }
727
+ if not any((element["roles"] or {}).values()):
728
+ raise ValueError("Choose columns for at least one graph role.")
729
+ plots, notes = self._plots_for_element(element)
730
+ if not plots:
731
+ raise ValueError("No plot could be built from the selected columns.")
732
+ if len(plots) > 12:
733
+ notes.append(f"Plot count truncated to the first 12 of {len(plots)}.")
734
+ plots = plots[:12]
735
+ first = plots[0]
736
+ roles = element["roles"]
737
+ result_params = dict(first.params)
738
+ result_params["kind"] = first.kind
739
+ if roles.get("x"):
740
+ result_params["x_columns"] = list(roles["x"])
741
+ result_params.setdefault("x", roles["x"][0])
742
+ if roles.get("y"):
743
+ result_params["y_columns"] = list(roles["y"])
744
+ result_params.setdefault("y", roles["y"][0])
745
+ if first.kind == "variability":
746
+ result_params["x"] = list(roles.get("x") or [])
747
+ if first.kind in {"correlation_heatmap", "pairplot", "parallel_coordinates"}:
748
+ result_params["columns"] = list(roles.get("columns") or [])
749
+ result_params["title"] = ""
750
+ result = AnalysisResult(
751
+ title="Graph",
752
+ analysis_type="plot",
753
+ source_table=self.table.name,
754
+ params=result_params,
755
+ )
756
+ result.plots.extend(plots)
757
+ result.summary = f"Graph of {self.table.name}."
758
+ if len(result.plots) > 1:
759
+ result.summary += f" {len(result.plots)} plots."
760
+ if notes:
761
+ result.notes = " ".join(dict.fromkeys(notes))
762
+ return result
763
+
764
+
765
+ class PlotEditDialog(IndependentDialog):
766
+ """Edit every display setting of an existing plot without rebuilding the analysis."""
767
+
768
+ MANAGED = (
769
+ "x_label",
770
+ "y_label",
771
+ "z_label",
772
+ "x_label_size",
773
+ "y_label_size",
774
+ "x_min",
775
+ "x_max",
776
+ "y_min",
777
+ "y_max",
778
+ "x_scale",
779
+ "y_scale",
780
+ "log_x",
781
+ "log_y",
782
+ "ref_lines",
783
+ "ref_lines_x",
784
+ "annotations",
785
+ "legend_position",
786
+ "marker_size",
787
+ "bubble_scale",
788
+ "jitter",
789
+ "show_points",
790
+ "smooth",
791
+ "smooth_method",
792
+ "bins",
793
+ "method",
794
+ "error",
795
+ "error_column",
796
+ "y1_show_points",
797
+ "y1_show_line",
798
+ "y2_show_points",
799
+ "y2_show_line",
800
+ "y1_color",
801
+ "y2_color",
802
+ "y1_line_width",
803
+ "y2_line_width",
804
+ "y2_marker_size",
805
+ "distribution",
806
+ "scipy_distribution",
807
+ "fit_args",
808
+ )
809
+
810
+ _DISTRIBUTION_TO_SCIPY = {
811
+ "Normal": "norm",
812
+ "Lognormal": "lognorm",
813
+ "Weibull": "weibull_min",
814
+ "Gamma": "gamma",
815
+ "Exponential": "expon",
816
+ "Beta": "beta",
817
+ "Uniform": "uniform",
818
+ }
819
+
820
+ _SCIPY_TO_LABEL = {
821
+ "norm": "Normal",
822
+ "normal": "Normal",
823
+ "lognorm": "Lognormal",
824
+ "lognormal": "Lognormal",
825
+ "weibull_min": "Weibull",
826
+ "gamma": "Gamma",
827
+ "expon": "Exponential",
828
+ "beta": "Beta",
829
+ "uniform": "Uniform",
830
+ }
831
+
832
+ _ERROR_TO_KEY = {
833
+ "Standard deviation": "sd",
834
+ "Standard error": "se",
835
+ "95% CI": "ci",
836
+ "Range": "range",
837
+ "None": "none",
838
+ }
839
+
840
+ _KEY_TO_ERROR = {value: key for key, value in _ERROR_TO_KEY.items()}
841
+
842
+ def __init__(self, plot: PlotSpec, parent=None) -> None:
843
+ super().__init__(parent)
844
+ self.setWindowTitle("Edit Plot")
845
+ self.resize(560, 720)
846
+ self.plot = plot
847
+ self.original = dict(plot.params or {})
848
+ params = self.original
849
+ outer = QVBoxLayout(self)
850
+ scroll = QScrollArea()
851
+ scroll.setWidgetResizable(True)
852
+ container = QWidget()
853
+ form = QFormLayout(container)
854
+ form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
855
+ scroll.setWidget(container)
856
+ outer.addWidget(scroll, 1)
857
+
858
+ self.title_edit = QLineEdit(plot.title or "")
859
+ self.x_label_edit = QLineEdit(str(params.get("x_label", "")))
860
+ self.y_label_edit = QLineEdit(str(params.get("y_label", "")))
861
+ self.z_label_edit = QLineEdit(str(params.get("z_label", "")))
862
+ self.x_label_size_spin = QSpinBox()
863
+ self.x_label_size_spin.setRange(0, 40)
864
+ self.x_label_size_spin.setSpecialValueText("Auto")
865
+ self.x_label_size_spin.setValue(int(params.get("x_label_size", 0) or 0))
866
+ self.y_label_size_spin = QSpinBox()
867
+ self.y_label_size_spin.setRange(0, 40)
868
+ self.y_label_size_spin.setSpecialValueText("Auto")
869
+ self.y_label_size_spin.setValue(int(params.get("y_label_size", 0) or 0))
870
+ self.x_min_edit = QLineEdit("" if params.get("x_min") is None else str(params["x_min"]))
871
+ self.x_max_edit = QLineEdit("" if params.get("x_max") is None else str(params["x_max"]))
872
+ self.y_min_edit = QLineEdit("" if params.get("y_min") is None else str(params["y_min"]))
873
+ self.y_max_edit = QLineEdit("" if params.get("y_max") is None else str(params["y_max"]))
874
+ self.x_scale_combo = QComboBox()
875
+ self.x_scale_combo.addItems(["Auto", "Linear", "Log"])
876
+ self.y_scale_combo = QComboBox()
877
+ self.y_scale_combo.addItems(["Auto", "Linear", "Log"])
878
+ for combo, key, log_key in (
879
+ (self.x_scale_combo, "x_scale", "log_x"),
880
+ (self.y_scale_combo, "y_scale", "log_y"),
881
+ ):
882
+ value = params.get(key) or ("log" if params.get(log_key) else "auto")
883
+ combo.setCurrentText({"log": "Log", "linear": "Linear"}.get(str(value).lower(), "Auto"))
884
+ self.ref_lines_edit = QLineEdit(", ".join(str(value) for value in (params.get("ref_lines") or [])))
885
+ self.ref_lines_x_edit = QLineEdit(", ".join(str(value) for value in (params.get("ref_lines_x") or [])))
886
+ self.annotations_edit = QLineEdit(
887
+ "; ".join(
888
+ f'{item.get("x")},{item.get("y")},{item.get("text")}'
889
+ for item in (params.get("annotations") or [])
890
+ if isinstance(item, dict)
891
+ )
892
+ )
893
+ self.legend_combo = QComboBox()
894
+ self.legend_combo.addItems(["Best", "Upper right", "Upper left", "Lower right", "Lower left", "Outside right"])
895
+ self.legend_combo.setCurrentText(str(params.get("legend_position") or "Best"))
896
+ self.marker_spin = QSpinBox()
897
+ self.marker_spin.setRange(1, 500)
898
+ try:
899
+ self.marker_spin.setValue(int(params.get("marker_size", 28)))
900
+ except (TypeError, ValueError):
901
+ self.marker_spin.setValue(28)
902
+ self.bubble_scale_slider = QSlider(Qt.Orientation.Horizontal)
903
+ self.bubble_scale_slider.setRange(25, 400)
904
+ self.bubble_scale_slider.setSingleStep(5)
905
+ try:
906
+ bubble_scale = int(round(float(params.get("bubble_scale", 1.0)) * 100))
907
+ except (TypeError, ValueError):
908
+ bubble_scale = 100
909
+ self.bubble_scale_slider.setValue(max(25, min(400, bubble_scale)))
910
+ self.bubble_scale_value = QLabel(f"{self.bubble_scale_slider.value()}%")
911
+ self.bubble_scale_slider.valueChanged.connect(
912
+ lambda value: self.bubble_scale_value.setText(f"{value}%")
913
+ )
914
+ self.bubble_scale_container = QWidget()
915
+ bubble_layout = QHBoxLayout(self.bubble_scale_container)
916
+ bubble_layout.setContentsMargins(0, 0, 0, 0)
917
+ bubble_layout.addWidget(self.bubble_scale_slider, 1)
918
+ bubble_layout.addWidget(self.bubble_scale_value)
919
+ self.y1_points_check = QCheckBox()
920
+ self.y1_points_check.setChecked(bool(params.get("y1_show_points", plot.kind == "scatter")))
921
+ self.y1_line_check = QCheckBox()
922
+ self.y1_line_check.setChecked(bool(params.get("y1_show_line", plot.kind == "line")))
923
+ self.y1_color_button = _ColorButton(params.get("y1_color"))
924
+ self.y1_color_clear = QPushButton("Clear")
925
+ self.y1_line_width_spin = QDoubleSpinBox()
926
+ self.y1_line_width_spin.setRange(0.5, 6.0)
927
+ self.y1_line_width_spin.setSingleStep(0.1)
928
+ self.y1_line_width_spin.setValue(float(params.get("y1_line_width", 1.8) or 1.8))
929
+ self.y2_points_check = QCheckBox()
930
+ self.y2_points_check.setChecked(bool(params.get("y2_show_points", True)))
931
+ self.y2_line_check = QCheckBox()
932
+ self.y2_line_check.setChecked(bool(params.get("y2_show_line", True)))
933
+ self.y2_color_button = _ColorButton(params.get("y2_color"))
934
+ self.y2_color_clear = QPushButton("Clear")
935
+ self.y2_line_width_spin = QDoubleSpinBox()
936
+ self.y2_line_width_spin.setRange(0.5, 6.0)
937
+ self.y2_line_width_spin.setSingleStep(0.1)
938
+ self.y2_line_width_spin.setValue(float(params.get("y2_line_width", 1.8) or 1.8))
939
+ self.y2_marker_size_spin = QSpinBox()
940
+ self.y2_marker_size_spin.setRange(1, 30)
941
+ self.y2_marker_size_spin.setValue(int(params.get("y2_marker_size", 5) or 5))
942
+ self.y1_color_clear.clicked.connect(lambda: self.y1_color_button.set_color(""))
943
+ self.y2_color_clear.clicked.connect(lambda: self.y2_color_button.set_color(""))
944
+ self.y1_color_row = QWidget()
945
+ y1_color_layout = QHBoxLayout(self.y1_color_row)
946
+ y1_color_layout.setContentsMargins(0, 0, 0, 0)
947
+ y1_color_layout.addWidget(self.y1_color_button, 1)
948
+ y1_color_layout.addWidget(self.y1_color_clear)
949
+ self.y2_color_row = QWidget()
950
+ y2_color_layout = QHBoxLayout(self.y2_color_row)
951
+ y2_color_layout.setContentsMargins(0, 0, 0, 0)
952
+ y2_color_layout.addWidget(self.y2_color_button, 1)
953
+ y2_color_layout.addWidget(self.y2_color_clear)
954
+ self.bins_spin = QSpinBox()
955
+ self.bins_spin.setRange(0, 500)
956
+ bins = params.get("bins", "auto")
957
+ try:
958
+ self.bins_spin.setValue(int(bins) if bins not in (None, "auto") else 0)
959
+ except (TypeError, ValueError):
960
+ self.bins_spin.setValue(0)
961
+ self.jitter_check = QCheckBox()
962
+ self.jitter_check.setChecked(bool(params.get("jitter")))
963
+ self.show_points_check = QCheckBox()
964
+ self.show_points_check.setChecked(bool(params.get("show_points", True)))
965
+ self.smooth_check = QCheckBox()
966
+ self.smooth_check.setChecked(bool(params.get("smooth")))
967
+ self.smooth_combo = QComboBox()
968
+ self.smooth_combo.addItems(["Linear", "LOWESS", "Spline", "Moving average"])
969
+ method = str(params.get("smooth_method") or "linear")
970
+ self.smooth_combo.setCurrentText(next((label for label in ["Linear", "LOWESS", "Spline", "Moving average"] if label.lower() == method.lower()), "Linear"))
971
+
972
+ self.method_combo = QComboBox()
973
+ self.method_combo.addItems(["pearson", "spearman", "kendall"])
974
+ self.method_combo.setCurrentText(str(params.get("method") or "pearson"))
975
+ self.variability_error_combo = QComboBox()
976
+ self.variability_error_combo.addItems(list(self._ERROR_TO_KEY))
977
+ self.variability_error_combo.setCurrentText(
978
+ self._KEY_TO_ERROR.get(str(params.get("error") or "sd"), "Standard deviation")
979
+ )
980
+ self.error_column_combo = ColumnDropCombo()
981
+ self.error_column_combo.addItem("(none)", None)
982
+ data = getattr(plot, "data", None)
983
+ data_columns = list(getattr(data, "columns", []))
984
+ for column in data_columns:
985
+ self.error_column_combo.addItem(column, column)
986
+ error_column = params.get("error_column") or params.get("error")
987
+ if not isinstance(error_column, str) or error_column not in data_columns:
988
+ error_column = None
989
+ error_index = self.error_column_combo.findData(error_column)
990
+ if error_index >= 0:
991
+ self.error_column_combo.setCurrentIndex(error_index)
992
+ self.distribution_combo = QComboBox()
993
+ self.distribution_combo.addItems(["None", *self._DISTRIBUTION_TO_SCIPY])
994
+ self.distribution_combo.setCurrentText(
995
+ self._SCIPY_TO_LABEL.get(
996
+ str(params.get("scipy_distribution") or params.get("distribution") or ""),
997
+ "None",
998
+ )
999
+ )
1000
+
1001
+ for label, widget in (
1002
+ ("Title", self.title_edit),
1003
+ ("X axis title", self.x_label_edit),
1004
+ ("Y axis title", self.y_label_edit),
1005
+ ("Z axis title", self.z_label_edit),
1006
+ ("X title size (0 = auto)", self.x_label_size_spin),
1007
+ ("Y title size (0 = auto)", self.y_label_size_spin),
1008
+ ("X minimum (blank = auto)", self.x_min_edit),
1009
+ ("X maximum (blank = auto)", self.x_max_edit),
1010
+ ("Y minimum (blank = auto)", self.y_min_edit),
1011
+ ("Y maximum (blank = auto)", self.y_max_edit),
1012
+ ("X scale", self.x_scale_combo),
1013
+ ("Y scale", self.y_scale_combo),
1014
+ ("Horizontal reference lines (Y)", self.ref_lines_edit),
1015
+ ("Vertical reference lines (X)", self.ref_lines_x_edit),
1016
+ ("Annotations: x,y,text; ...", self.annotations_edit),
1017
+ ("Legend position", self.legend_combo),
1018
+ ("Marker size", self.marker_spin),
1019
+ ("Histogram bins (0 = auto)", self.bins_spin),
1020
+ ):
1021
+ form.addRow(label, widget)
1022
+ self.bubble_scale_label = QLabel("Bubble size (%)")
1023
+ form.addRow(self.bubble_scale_label, self.bubble_scale_container)
1024
+ self.jitter_check.setText("Jitter points")
1025
+ self.show_points_check.setText("Show data points")
1026
+ self.smooth_check.setText("Add smoother")
1027
+ self.y1_points_check.setText("Y1 points")
1028
+ self.y1_line_check.setText("Y1 line")
1029
+ self.y2_points_check.setText("Y2 points")
1030
+ self.y2_line_check.setText("Y2 line")
1031
+ form.addRow("", self.jitter_check)
1032
+ form.addRow("", self.show_points_check)
1033
+ form.addRow("", self.smooth_check)
1034
+ form.addRow("", self.y1_points_check)
1035
+ form.addRow("", self.y1_line_check)
1036
+ self.y1_color_label = QLabel("Y1 color")
1037
+ form.addRow(self.y1_color_label, self.y1_color_row)
1038
+ self.y1_line_width_label = QLabel("Y1 line width")
1039
+ form.addRow(self.y1_line_width_label, self.y1_line_width_spin)
1040
+ form.addRow("", self.y2_points_check)
1041
+ form.addRow("", self.y2_line_check)
1042
+ self.y2_color_label = QLabel("Y2 color")
1043
+ form.addRow(self.y2_color_label, self.y2_color_row)
1044
+ self.y2_line_width_label = QLabel("Y2 line width")
1045
+ form.addRow(self.y2_line_width_label, self.y2_line_width_spin)
1046
+ self.y2_marker_size_label = QLabel("Y2 marker size")
1047
+ form.addRow(self.y2_marker_size_label, self.y2_marker_size_spin)
1048
+ form.addRow("Smoother", self.smooth_combo)
1049
+ self._has_y2 = plot.kind in {"scatter", "line", "bar"} and bool(params.get("y2"))
1050
+ self._has_y1 = plot.kind in {"scatter", "line"}
1051
+ self.bubble_scale_label.setVisible(plot.kind == "bubble")
1052
+ self.bubble_scale_container.setVisible(plot.kind == "bubble")
1053
+ for widget in (
1054
+ self.y1_points_check,
1055
+ self.y1_line_check,
1056
+ self.y1_color_label,
1057
+ self.y1_color_row,
1058
+ self.y1_line_width_label,
1059
+ self.y1_line_width_spin,
1060
+ ):
1061
+ widget.setVisible(self._has_y1)
1062
+ for widget in (
1063
+ self.y2_points_check,
1064
+ self.y2_line_check,
1065
+ self.y2_color_label,
1066
+ self.y2_color_row,
1067
+ self.y2_line_width_label,
1068
+ self.y2_line_width_spin,
1069
+ self.y2_marker_size_label,
1070
+ self.y2_marker_size_spin,
1071
+ ):
1072
+ widget.setVisible(self._has_y2)
1073
+
1074
+ self.method_label = QLabel("Correlation method")
1075
+ form.addRow(self.method_label, self.method_combo)
1076
+ self.variability_label = QLabel("Variability error bars")
1077
+ form.addRow(self.variability_label, self.variability_error_combo)
1078
+ self.error_column_label = QLabel("Bar error values")
1079
+ form.addRow(self.error_column_label, self.error_column_combo)
1080
+ self.distribution_label = QLabel("Distribution fit")
1081
+ form.addRow(self.distribution_label, self.distribution_combo)
1082
+ if plot.kind != "correlation_heatmap":
1083
+ self.method_label.hide()
1084
+ self.method_combo.hide()
1085
+ if plot.kind != "variability":
1086
+ self.variability_label.hide()
1087
+ self.variability_error_combo.hide()
1088
+ if plot.kind != "bar":
1089
+ self.error_column_label.hide()
1090
+ self.error_column_combo.hide()
1091
+ if plot.kind != "histogram":
1092
+ self.distribution_label.hide()
1093
+ self.distribution_combo.hide()
1094
+
1095
+ buttons = QDialogButtonBox(
1096
+ QDialogButtonBox.StandardButton.Ok
1097
+ | QDialogButtonBox.StandardButton.Cancel
1098
+ | QDialogButtonBox.StandardButton.Reset
1099
+ )
1100
+ buttons.accepted.connect(self.accept)
1101
+ buttons.rejected.connect(self.reject)
1102
+ buttons.button(QDialogButtonBox.StandardButton.Reset).clicked.connect(self._reset)
1103
+ from statstudio.ui.dialogs.help_topics import add_help_button, install_context_help
1104
+
1105
+ add_help_button(buttons, self)
1106
+ install_context_help(self)
1107
+ outer.addWidget(buttons)
1108
+ self.result: tuple[str, dict] | None = None
1109
+
1110
+ def _reset(self) -> None:
1111
+ for edit in (
1112
+ self.title_edit,
1113
+ self.x_label_edit,
1114
+ self.y_label_edit,
1115
+ self.z_label_edit,
1116
+ self.x_min_edit,
1117
+ self.x_max_edit,
1118
+ self.y_min_edit,
1119
+ self.y_max_edit,
1120
+ self.ref_lines_edit,
1121
+ self.ref_lines_x_edit,
1122
+ self.annotations_edit,
1123
+ ):
1124
+ edit.clear()
1125
+ self.x_label_size_spin.setValue(0)
1126
+ self.y_label_size_spin.setValue(0)
1127
+ self.x_scale_combo.setCurrentText("Auto")
1128
+ self.y_scale_combo.setCurrentText("Auto")
1129
+ self.legend_combo.setCurrentText("Best")
1130
+ self.marker_spin.setValue(28)
1131
+ self.bubble_scale_slider.setValue(100)
1132
+ self.y1_points_check.setChecked(self.plot.kind == "scatter")
1133
+ self.y1_line_check.setChecked(self.plot.kind == "line")
1134
+ self.y1_color_button.set_color("")
1135
+ self.y1_line_width_spin.setValue(1.8)
1136
+ self.y2_points_check.setChecked(True)
1137
+ self.y2_line_check.setChecked(True)
1138
+ self.y2_color_button.set_color("")
1139
+ self.y2_line_width_spin.setValue(1.8)
1140
+ self.y2_marker_size_spin.setValue(5)
1141
+ self.bins_spin.setValue(0)
1142
+ self.jitter_check.setChecked(False)
1143
+ self.show_points_check.setChecked(True)
1144
+ self.smooth_check.setChecked(False)
1145
+ self.smooth_combo.setCurrentText("Linear")
1146
+ self.method_combo.setCurrentText("pearson")
1147
+ self.variability_error_combo.setCurrentText("Standard deviation")
1148
+ self.error_column_combo.setCurrentIndex(0)
1149
+ self.distribution_combo.setCurrentText("None")
1150
+ self.accept()
1151
+
1152
+ def _fit_distribution(self, scipy_name: str, column: str | None) -> tuple[float, ...] | None:
1153
+ data = getattr(self.plot, "data", None)
1154
+ if data is None or not column or column not in data.columns:
1155
+ return None
1156
+ values = pd.to_numeric(data[column], errors="coerce").dropna().to_numpy(dtype=float)
1157
+ if len(values) < 3:
1158
+ return None
1159
+ try:
1160
+ distribution = getattr(scipy_stats, scipy_name)
1161
+ if scipy_name == "norm":
1162
+ return (float(values.mean()), float(values.std(ddof=1)))
1163
+ return tuple(float(value) for value in distribution.fit(values))
1164
+ except Exception:
1165
+ return None
1166
+
1167
+ def accept(self) -> None:
1168
+ params = dict(self.original)
1169
+ for key in self.MANAGED:
1170
+ params.pop(key, None)
1171
+ for key, edit in (
1172
+ ("x_label", self.x_label_edit),
1173
+ ("y_label", self.y_label_edit),
1174
+ ("z_label", self.z_label_edit),
1175
+ ):
1176
+ value = edit.text().strip()
1177
+ if value:
1178
+ params[key] = value
1179
+ if self.x_label_size_spin.value() > 0:
1180
+ params["x_label_size"] = self.x_label_size_spin.value()
1181
+ if self.y_label_size_spin.value() > 0:
1182
+ params["y_label_size"] = self.y_label_size_spin.value()
1183
+ for key, edit in (
1184
+ ("x_min", self.x_min_edit),
1185
+ ("x_max", self.x_max_edit),
1186
+ ("y_min", self.y_min_edit),
1187
+ ("y_max", self.y_max_edit),
1188
+ ):
1189
+ value = _float_or_none(edit.text())
1190
+ if value is not None:
1191
+ params[key] = value
1192
+ for combo, key, log_key in (
1193
+ (self.x_scale_combo, "x_scale", "log_x"),
1194
+ (self.y_scale_combo, "y_scale", "log_y"),
1195
+ ):
1196
+ scale = combo.currentText().lower()
1197
+ if scale == "log":
1198
+ params[key] = "log"
1199
+ params[log_key] = True
1200
+ elif scale == "linear":
1201
+ params[key] = "linear"
1202
+ ref_lines = _float_list(self.ref_lines_edit.text())
1203
+ if ref_lines:
1204
+ params["ref_lines"] = ref_lines
1205
+ ref_lines_x = _float_list(self.ref_lines_x_edit.text())
1206
+ if ref_lines_x:
1207
+ params["ref_lines_x"] = ref_lines_x
1208
+ annotations = []
1209
+ for part in self.annotations_edit.text().split(";"):
1210
+ fields = [field.strip() for field in part.split(",")]
1211
+ if len(fields) >= 3:
1212
+ try:
1213
+ annotations.append({"x": float(fields[0]), "y": float(fields[1]), "text": ",".join(fields[2:])})
1214
+ except ValueError:
1215
+ continue
1216
+ if annotations:
1217
+ params["annotations"] = annotations
1218
+ legend_position = self.legend_combo.currentText()
1219
+ if legend_position and legend_position != "Best":
1220
+ params["legend_position"] = legend_position
1221
+ if self.marker_spin.value() != 28:
1222
+ params["marker_size"] = self.marker_spin.value()
1223
+ if self.plot.kind == "bubble":
1224
+ bubble_scale = self.bubble_scale_slider.value() / 100.0
1225
+ if abs(bubble_scale - 1.0) > 1e-9:
1226
+ params["bubble_scale"] = bubble_scale
1227
+ else:
1228
+ params.pop("bubble_scale", None)
1229
+ if self._has_y1:
1230
+ default_line = self.plot.kind == "line"
1231
+ default_points = self.plot.kind == "scatter"
1232
+ if self.y1_points_check.isChecked() != default_points:
1233
+ params["y1_show_points"] = self.y1_points_check.isChecked()
1234
+ else:
1235
+ params.pop("y1_show_points", None)
1236
+ if self.y1_line_check.isChecked() != default_line:
1237
+ params["y1_show_line"] = self.y1_line_check.isChecked()
1238
+ else:
1239
+ params.pop("y1_show_line", None)
1240
+ if self.y1_color_button.color():
1241
+ params["y1_color"] = self.y1_color_button.color()
1242
+ if abs(self.y1_line_width_spin.value() - 1.8) > 1e-9:
1243
+ params["y1_line_width"] = self.y1_line_width_spin.value()
1244
+ if self._has_y2:
1245
+ if not self.y2_points_check.isChecked():
1246
+ params["y2_show_points"] = False
1247
+ else:
1248
+ params.pop("y2_show_points", None)
1249
+ if not self.y2_line_check.isChecked():
1250
+ params["y2_show_line"] = False
1251
+ else:
1252
+ params.pop("y2_show_line", None)
1253
+ if self.y2_color_button.color():
1254
+ params["y2_color"] = self.y2_color_button.color()
1255
+ if abs(self.y2_line_width_spin.value() - 1.8) > 1e-9:
1256
+ params["y2_line_width"] = self.y2_line_width_spin.value()
1257
+ if self.y2_marker_size_spin.value() != 5:
1258
+ params["y2_marker_size"] = self.y2_marker_size_spin.value()
1259
+ bins = self.bins_spin.value()
1260
+ if bins > 0:
1261
+ params["bins"] = bins
1262
+ if self.jitter_check.isChecked():
1263
+ params["jitter"] = True
1264
+ if not self.show_points_check.isChecked():
1265
+ params["show_points"] = False
1266
+ if self.smooth_check.isChecked():
1267
+ params["smooth"] = True
1268
+ params["smooth_method"] = self.smooth_combo.currentText().lower()
1269
+ if self.plot.kind == "correlation_heatmap":
1270
+ params["method"] = self.method_combo.currentText()
1271
+ if self.plot.kind == "variability":
1272
+ params["error"] = self._ERROR_TO_KEY.get(self.variability_error_combo.currentText(), "sd")
1273
+ if self.plot.kind == "bar":
1274
+ error_column = self.error_column_combo.currentData()
1275
+ if error_column:
1276
+ params["error_column"] = error_column
1277
+ if self.plot.kind == "histogram":
1278
+ label = self.distribution_combo.currentText()
1279
+ scipy_name = self._DISTRIBUTION_TO_SCIPY.get(label)
1280
+ if scipy_name:
1281
+ column = params.get("column") or params.get("x")
1282
+ fit_args = self._fit_distribution(scipy_name, column)
1283
+ if fit_args is not None:
1284
+ params["distribution"] = scipy_name
1285
+ params["scipy_distribution"] = scipy_name
1286
+ params["fit_args"] = fit_args
1287
+ self.result = (self.title_edit.text().strip(), params)
1288
+ super().accept()
1289
+
1290
+
1291
+ class ColumnSwitcherDialog(IndependentDialog):
1292
+ """Swap the columns used by any role in existing plot specifications."""
1293
+
1294
+ ROLE_KEYS = (
1295
+ "column",
1296
+ "x",
1297
+ "y",
1298
+ "y2",
1299
+ "z",
1300
+ "size",
1301
+ "group",
1302
+ "shape",
1303
+ "facet",
1304
+ "row",
1305
+ "category",
1306
+ "count",
1307
+ "error_column",
1308
+ )
1309
+
1310
+ ROLE_LABELS = {
1311
+ "column": "Value",
1312
+ "x": "X",
1313
+ "y": "Y",
1314
+ "y2": "Y2",
1315
+ "z": "Z",
1316
+ "size": "Size",
1317
+ "group": "Group",
1318
+ "shape": "Shape",
1319
+ "facet": "Facet",
1320
+ "row": "Row",
1321
+ "category": "Category",
1322
+ "count": "Count",
1323
+ "error_column": "Error",
1324
+ }
1325
+
1326
+ def __init__(self, table: DataTable, plots: list[PlotSpec], parent=None) -> None:
1327
+ super().__init__(parent)
1328
+ self.setWindowTitle("Column Switcher")
1329
+ self.resize(560, 420)
1330
+ self.table = table
1331
+ self.plots = plots
1332
+ layout = QVBoxLayout(self)
1333
+ layout.addWidget(QLabel("Choose a new column for any graph role. The plot page re-renders when you apply."))
1334
+ self.widget = QTableWidget()
1335
+ self.widget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
1336
+ self.widget.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
1337
+ self.widget.setColumnCount(3)
1338
+ self.widget.setHorizontalHeaderLabels(["Graph", "Role", "Column"])
1339
+ self._rows: list[tuple[int, str, ColumnDropCombo]] = []
1340
+ rows: list[tuple[str, str, int, str]] = []
1341
+ for plot_index, plot in enumerate(plots):
1342
+ for key in self.ROLE_KEYS:
1343
+ value = plot.params.get(key)
1344
+ if isinstance(value, str) and value in table.columns:
1345
+ rows.append((plot.title or plot.kind.title(), self.ROLE_LABELS.get(key, key), plot_index, key))
1346
+ self.widget.setRowCount(len(rows))
1347
+ for row, (title, role_label, plot_index, key) in enumerate(rows):
1348
+ self.widget.setItem(row, 0, QTableWidgetItem(title))
1349
+ self.widget.setItem(row, 1, QTableWidgetItem(role_label))
1350
+ combo = ColumnDropCombo()
1351
+ for column in table.columns:
1352
+ combo.addItem(column, column)
1353
+ current = self.plots[plot_index].params.get(key)
1354
+ index = combo.findData(current)
1355
+ if index >= 0:
1356
+ combo.setCurrentIndex(index)
1357
+ self.widget.setCellWidget(row, 2, combo)
1358
+ self._rows.append((plot_index, key, combo))
1359
+ self.widget.resizeColumnsToContents()
1360
+ self.widget.setColumnWidth(0, 200)
1361
+ row = QHBoxLayout()
1362
+ self.column_palette = ColumnDragList(table.columns)
1363
+ self.column_palette.setFixedWidth(170)
1364
+ row.addWidget(self.column_palette, 0)
1365
+ row.addWidget(self.widget, 1)
1366
+ layout.addLayout(row, 1)
1367
+ buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
1368
+ buttons.accepted.connect(self.accept)
1369
+ buttons.rejected.connect(self.reject)
1370
+ from statstudio.ui.dialogs.help_topics import add_help_button, install_context_help
1371
+
1372
+ add_help_button(buttons, self)
1373
+ install_context_help(self)
1374
+ layout.addWidget(buttons)
1375
+ self.result: list[dict] | None = None
1376
+ if not rows:
1377
+ self.widget.setRowCount(1)
1378
+ self.widget.setItem(0, 0, QTableWidgetItem("No switchable graph roles were found."))
1379
+
1380
+ def accept(self) -> None:
1381
+ params_list = [dict(plot.params) for plot in self.plots]
1382
+ for plot_index, key, combo in self._rows:
1383
+ params_list[plot_index][key] = combo.currentData()
1384
+ self.result = params_list
1385
+ super().accept()