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,178 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+
7
+ def plot_row_ids(plot) -> list | None:
8
+ if plot is None or plot.data is None:
9
+ return None
10
+ if plot.row_ids is not None and len(plot.row_ids) == len(plot.data):
11
+ return list(plot.row_ids)
12
+ return list(plot.data.index)
13
+
14
+
15
+ def artist_row_ids(artist) -> list | None:
16
+ ids = getattr(artist, "_statstudio_row_ids", None)
17
+ return ids if ids is not None else None
18
+
19
+
20
+ def _match_offsets(offsets, plot) -> list:
21
+ params = plot.params or {}
22
+ x_name = params.get("x")
23
+ y_name = params.get("y")
24
+ if x_name not in plot.data.columns or y_name not in plot.data.columns:
25
+ return []
26
+ try:
27
+ x_values = pd.to_numeric(plot.data[x_name], errors="coerce").to_numpy(dtype=float)
28
+ y_values = pd.to_numeric(plot.data[y_name], errors="coerce").to_numpy(dtype=float)
29
+ except Exception:
30
+ return []
31
+ ids = plot_row_ids(plot)
32
+ if ids is None:
33
+ return []
34
+ positions = []
35
+ used: set[int] = set()
36
+ for offset in offsets:
37
+ try:
38
+ px, py = float(offset[0]), float(offset[1])
39
+ except Exception:
40
+ continue
41
+ for position, (vx, vy) in enumerate(zip(x_values, y_values)):
42
+ if position in used or not np.isfinite(vx) or not np.isfinite(vy):
43
+ continue
44
+ if np.isclose(vx, px) and np.isclose(vy, py):
45
+ used.add(position)
46
+ positions.append(ids[position])
47
+ break
48
+ return positions
49
+
50
+
51
+ def ids_for_indices(artist, plot, indices) -> list:
52
+ ids = artist_row_ids(artist)
53
+ if ids is not None:
54
+ rows = []
55
+ for index in indices:
56
+ try:
57
+ rows.append(ids[int(index)])
58
+ except Exception:
59
+ continue
60
+ if rows:
61
+ return rows
62
+ try:
63
+ offsets = [artist.get_offsets()[int(index)] for index in indices]
64
+ except Exception:
65
+ offsets = None
66
+ if offsets:
67
+ rows = _match_offsets(offsets, plot)
68
+ if rows:
69
+ return rows
70
+ fallback = plot_row_ids(plot)
71
+ if fallback is None:
72
+ return []
73
+ rows = []
74
+ for index in indices:
75
+ try:
76
+ rows.append(fallback[int(index)])
77
+ except Exception:
78
+ continue
79
+ return rows
80
+
81
+
82
+ def ids_for_event(event, plot) -> list:
83
+ indices = getattr(event, "ind", None)
84
+ if not indices:
85
+ return []
86
+ return ids_for_indices(getattr(event, "artist", None), plot, indices)
87
+
88
+
89
+ def hit_test(figure, event) -> tuple[object | None, list]:
90
+ """Return the collection and point indices under a mouse event."""
91
+ for ax in figure.axes:
92
+ if getattr(event, "inaxes", None) is not None and event.inaxes is not ax:
93
+ continue
94
+ for collection in ax.collections:
95
+ try:
96
+ contains, props = collection.contains(event)
97
+ except Exception:
98
+ continue
99
+ if not contains:
100
+ continue
101
+ ind = props.get("ind") if isinstance(props, dict) else None
102
+ if ind is None:
103
+ continue
104
+ return collection, [int(value) for value in np.atleast_1d(ind)]
105
+ return None, []
106
+
107
+
108
+ def ids_in_rect(figure, plot, xmin: float, xmax: float, ymin: float, ymax: float, axes=None) -> list:
109
+ low_x, high_x = sorted((float(xmin), float(xmax)))
110
+ low_y, high_y = sorted((float(ymin), float(ymax)))
111
+ rows: list = []
112
+ seen: set = set()
113
+ for ax in ([axes] if axes is not None else figure.axes):
114
+ for collection in ax.collections:
115
+ ids = artist_row_ids(collection)
116
+ if not ids:
117
+ continue
118
+ try:
119
+ offsets = collection.get_offsets()
120
+ except Exception:
121
+ continue
122
+ for position, (x_value, y_value) in enumerate(offsets):
123
+ if position >= len(ids):
124
+ break
125
+ try:
126
+ inside = low_x <= float(x_value) <= high_x and low_y <= float(y_value) <= high_y
127
+ except Exception:
128
+ continue
129
+ if inside:
130
+ row_id = ids[position]
131
+ if row_id not in seen:
132
+ seen.add(row_id)
133
+ rows.append(row_id)
134
+ return rows
135
+
136
+
137
+ def filtered_plot_data(data, row_ids, expression: str):
138
+ if data is None:
139
+ return data, row_ids
140
+ if not expression:
141
+ return data, (list(row_ids) if row_ids is not None else list(data.index))
142
+ from statstudio.core.formulas import evaluate_formula
143
+
144
+ mask = evaluate_formula(data, expression)
145
+ if not isinstance(mask, pd.Series):
146
+ raise ValueError("Filter must produce a boolean column expression.")
147
+ mask = mask.reindex(data.index, fill_value=False).fillna(False).astype(bool)
148
+ if len(mask) != len(data):
149
+ raise ValueError("Filter returned an unexpected number of rows.")
150
+ filtered = data.loc[mask]
151
+ if row_ids is not None and len(row_ids) == len(data):
152
+ ids_series = pd.Series(list(row_ids), index=data.index)
153
+ ids = ids_series.loc[filtered.index].tolist()
154
+ else:
155
+ ids = list(filtered.index)
156
+ return filtered, ids
157
+
158
+
159
+ def describe_row(plot, row_id) -> str:
160
+ styles = plot.row_styles or {}
161
+ state = styles.get(row_id) or {}
162
+ label = state.get("label") or f"Row {row_id}"
163
+ params = plot.params or {}
164
+ details: list[str] = []
165
+ if plot.data is not None:
166
+ try:
167
+ row = plot.data.loc[row_id]
168
+ if isinstance(row, pd.DataFrame):
169
+ row = row.iloc[0]
170
+ for key in ("x", "y", "column"):
171
+ name = params.get(key)
172
+ if name and name in row.index:
173
+ details.append(f"{name}={row[name]}")
174
+ except Exception:
175
+ details = []
176
+ if details:
177
+ return f"{label}: " + ", ".join(str(item) for item in details)
178
+ return str(label)
@@ -0,0 +1,437 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg
8
+ from matplotlib.figure import Figure
9
+ from PySide6.QtCore import Qt, Signal
10
+ from PySide6.QtWidgets import (
11
+ QApplication,
12
+ QComboBox,
13
+ QDoubleSpinBox,
14
+ QGridLayout,
15
+ QHBoxLayout,
16
+ QLabel,
17
+ QPushButton,
18
+ QSizePolicy,
19
+ QToolButton,
20
+ QVBoxLayout,
21
+ QWidget,
22
+ )
23
+
24
+ from statstudio.stats.profiler import ProfilerGoal, ProfilerSession
25
+
26
+
27
+ class InteractiveProfilerWidget(QWidget):
28
+ changed = Signal()
29
+
30
+ def __init__(self, session: ProfilerSession, parent: QWidget | None = None, points: int | None = None) -> None:
31
+ super().__init__(parent)
32
+ self.session = session
33
+ self.points = max(3, int(points or session.points or 9))
34
+ self.factors = list(session.factors)
35
+ self._axes: dict[Any, str] = {}
36
+ self._lines: dict[str, Any] = {}
37
+ self._markers: dict[str, Any] = {}
38
+ self._dots: dict[str, Any] = {}
39
+ self._controls: dict[str, Any] = {}
40
+ self._locks: dict[str, QToolButton] = {}
41
+ self._dragging: str | None = None
42
+ self._syncing = False
43
+ self.goal_combo: QComboBox | None = None
44
+ self.low_spin: QDoubleSpinBox | None = None
45
+ self.high_spin: QDoubleSpinBox | None = None
46
+ self.target_spin: QDoubleSpinBox | None = None
47
+ self.optimize_button: QPushButton | None = None
48
+ self.status_label: QLabel | None = None
49
+ self._columns = min(3, max(1, len(self.factors)))
50
+ self._rows = max(1, math.ceil(len(self.factors) / self._columns))
51
+ self._build()
52
+ self._redraw()
53
+
54
+ def _build(self) -> None:
55
+ layout = QVBoxLayout(self)
56
+ layout.setContentsMargins(0, 0, 0, 0)
57
+ layout.setSpacing(4)
58
+
59
+ top = QHBoxLayout()
60
+ hint = QLabel(
61
+ "Drag the red lines, change factor settings, or globally optimize all unlocked factors."
62
+ )
63
+ hint.setStyleSheet("color:#5a6270;")
64
+ self.value_label = QLabel()
65
+ self.value_label.setStyleSheet("font-weight:600;")
66
+ reset = QPushButton("Reset")
67
+ reset.clicked.connect(self.reset)
68
+ top.addWidget(hint)
69
+ top.addStretch(1)
70
+ top.addWidget(self.value_label)
71
+ top.addWidget(reset)
72
+ layout.addLayout(top)
73
+
74
+ if not self.factors:
75
+ empty = QLabel("No factors are available for profiling.")
76
+ empty.setStyleSheet("color:#a33;")
77
+ layout.addWidget(empty)
78
+ self.figure = Figure(figsize=(6, 2))
79
+ self.canvas = FigureCanvasQTAgg(self.figure)
80
+ layout.addWidget(self.canvas)
81
+ return
82
+
83
+ width = max(7.0, self._columns * 3.2)
84
+ height = max(3.2, self._rows * 2.7)
85
+ self.figure = Figure(figsize=(width, height))
86
+ self.canvas = FigureCanvasQTAgg(self.figure)
87
+ self.canvas.setMinimumHeight(max(300, self._rows * 220))
88
+ self.canvas.setMinimumWidth(420)
89
+ self.canvas.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
90
+ layout.addWidget(self.canvas, 1)
91
+ self._build_optimization_panel(layout)
92
+
93
+ controls = QGridLayout()
94
+ controls.setContentsMargins(0, 0, 0, 0)
95
+ controls.setHorizontalSpacing(8)
96
+ controls.setVerticalSpacing(4)
97
+
98
+ for index, factor in enumerate(self.factors):
99
+ axis = self.figure.add_subplot(self._rows, self._columns, index + 1)
100
+ self._axes[axis] = factor.name
101
+ axis.set_title(factor.name, fontsize=10, fontweight="bold")
102
+ axis.set_ylabel(self.session.response_label, fontsize=8)
103
+ axis.tick_params(labelsize=8)
104
+ axis.grid(True, alpha=0.22)
105
+ profile = self.session.profile(factor.name, self.points)
106
+ line, = axis.plot(
107
+ profile["x"],
108
+ profile["y"],
109
+ color="#1f4e79",
110
+ marker="o",
111
+ markersize=4,
112
+ linewidth=2,
113
+ )
114
+ marker = axis.axvline(
115
+ profile["current"],
116
+ color="#c0392b",
117
+ linewidth=2,
118
+ zorder=5,
119
+ )
120
+ dot, = axis.plot([], [], marker="o", color="#c0392b", markersize=6, zorder=6)
121
+ self._lines[factor.name] = line
122
+ self._markers[factor.name] = marker
123
+ self._dots[factor.name] = dot
124
+
125
+ if factor.kind == "continuous":
126
+ axis.set_xlim(factor.low, factor.high)
127
+ span = factor.high - factor.low
128
+ control = QDoubleSpinBox()
129
+ control.setRange(factor.low, factor.high)
130
+ control.setDecimals(6 if span and span < 10 else 4)
131
+ control.setSingleStep(max(span / 100.0, 10 ** (-control.decimals())))
132
+ control.setValue(float(factor.current))
133
+ control.valueChanged.connect(
134
+ lambda value, name=factor.name: self._control_changed(name, value)
135
+ )
136
+ else:
137
+ axis.set_xticks(range(len(factor.levels)))
138
+ labels = factor.levels or [str(factor.current)]
139
+ axis.set_xticklabels(
140
+ labels,
141
+ rotation=30 if any(len(label) > 5 for label in labels) else 0,
142
+ )
143
+ if len(labels) > 1:
144
+ axis.set_xlim(-0.35, len(labels) - 0.65)
145
+ else:
146
+ axis.set_xlim(-0.5, 0.5)
147
+ control = QComboBox()
148
+ control.addItems(factor.levels)
149
+ if factor.current in factor.levels:
150
+ control.setCurrentText(str(factor.current))
151
+ control.currentTextChanged.connect(
152
+ lambda value, name=factor.name: self._control_changed(name, value)
153
+ )
154
+
155
+ self._controls[factor.name] = control
156
+ lock = QToolButton()
157
+ lock.setText("Lock")
158
+ lock.setCheckable(True)
159
+ lock.setToolTip("Prevent this factor from being changed")
160
+ lock.toggled.connect(lambda checked, name=factor.name: self._lock_toggled(name, checked))
161
+ self._locks[factor.name] = lock
162
+
163
+ row = QWidget()
164
+ row_layout = QHBoxLayout(row)
165
+ row_layout.setContentsMargins(0, 0, 0, 0)
166
+ row_layout.setSpacing(4)
167
+ row_layout.addWidget(control, 1)
168
+ row_layout.addWidget(lock)
169
+ controls.addWidget(row, index // self._columns, index % self._columns)
170
+
171
+ layout.addLayout(controls)
172
+ self.figure.subplots_adjust(
173
+ left=0.09,
174
+ right=0.98,
175
+ top=0.9,
176
+ bottom=0.16,
177
+ hspace=0.55,
178
+ wspace=0.32,
179
+ )
180
+ self.canvas.mpl_connect("button_press_event", self._on_press)
181
+ self.canvas.mpl_connect("motion_notify_event", self._on_motion)
182
+ self.canvas.mpl_connect("button_release_event", self._on_release)
183
+ self._update_value_label()
184
+
185
+ def _build_optimization_panel(self, layout: QVBoxLayout) -> None:
186
+ panel = QWidget()
187
+ grid = QGridLayout(panel)
188
+ grid.setContentsMargins(0, 4, 0, 0)
189
+ grid.setHorizontalSpacing(6)
190
+ grid.setVerticalSpacing(3)
191
+
192
+ title = QLabel("Optimize Response")
193
+ title.setStyleSheet("font-weight:600;")
194
+ grid.addWidget(title, 0, 0)
195
+
196
+ self.status_label = QLabel()
197
+ self.status_label.setStyleSheet("color:#5a6270;")
198
+ grid.addWidget(self.status_label, 0, 1, 1, 5)
199
+
200
+ goal_caption = QLabel("Goal")
201
+ self.goal_combo = QComboBox()
202
+ self.goal_combo.addItems(["Maximize", "Minimize", "Target", "Within range"])
203
+
204
+ self.low_spin = QDoubleSpinBox()
205
+ self.high_spin = QDoubleSpinBox()
206
+ self.target_spin = QDoubleSpinBox()
207
+ for spin in (self.low_spin, self.high_spin, self.target_spin):
208
+ spin.setRange(-1e12, 1e12)
209
+ spin.setDecimals(6)
210
+ spin.setKeyboardTracking(False)
211
+
212
+ self.optimize_button = QPushButton("Optimize Response")
213
+ self.optimize_button.setToolTip(
214
+ "Globally optimize all unlocked factors for the selected response goal"
215
+ )
216
+
217
+ resolved = self.session.resolved_goal(self.session.response_goal)
218
+ default_low, default_high = self.session.prediction_bounds(self.points)
219
+ low = resolved.low if resolved.low is not None else default_low
220
+ high = resolved.high if resolved.high is not None else default_high
221
+ current = self.session.current_prediction()
222
+ target = resolved.target
223
+ if target is None:
224
+ target = current if np.isfinite(current) else (low + high) / 2.0
225
+ labels = {
226
+ "maximize": "Maximize",
227
+ "minimize": "Minimize",
228
+ "target": "Target",
229
+ "within": "Within range",
230
+ }
231
+ self.goal_combo.setCurrentText(labels.get(resolved.goal, "Maximize"))
232
+ self.low_spin.setValue(float(low))
233
+ self.high_spin.setValue(float(high))
234
+ self.target_spin.setValue(float(target))
235
+ span = high - low
236
+ step = max(abs(span) / 100.0, 1e-6)
237
+ for spin in (self.low_spin, self.high_spin, self.target_spin):
238
+ spin.setSingleStep(step)
239
+
240
+ grid.addWidget(goal_caption, 1, 0)
241
+ grid.addWidget(self.goal_combo, 1, 1)
242
+ grid.addWidget(QLabel("Low"), 1, 2)
243
+ grid.addWidget(self.low_spin, 1, 3)
244
+ grid.addWidget(QLabel("High"), 1, 4)
245
+ grid.addWidget(self.high_spin, 1, 5)
246
+ grid.addWidget(QLabel("Target"), 2, 0)
247
+ grid.addWidget(self.target_spin, 2, 1)
248
+ grid.addWidget(self.optimize_button, 2, 2, 1, 4)
249
+
250
+ self.goal_combo.currentTextChanged.connect(self._goal_changed)
251
+ self.optimize_button.clicked.connect(self._optimize_response)
252
+ self._goal_changed(self.goal_combo.currentText())
253
+ layout.addWidget(panel)
254
+
255
+ def _goal_key(self) -> str:
256
+ text = self.goal_combo.currentText() if self.goal_combo is not None else "Maximize"
257
+ return {
258
+ "Maximize": "maximize",
259
+ "Minimize": "minimize",
260
+ "Target": "target",
261
+ "Within range": "within",
262
+ }.get(text, "maximize")
263
+
264
+ def _current_goal(self) -> ProfilerGoal:
265
+ return ProfilerGoal(
266
+ self._goal_key(),
267
+ self.low_spin.value() if self.low_spin is not None else None,
268
+ self.high_spin.value() if self.high_spin is not None else None,
269
+ self.target_spin.value() if self.target_spin is not None else None,
270
+ )
271
+
272
+ def _goal_changed(self, _text: str) -> None:
273
+ goal = self._goal_key()
274
+ if self.target_spin is not None:
275
+ self.target_spin.setEnabled(goal == "target")
276
+ if self.low_spin is not None:
277
+ self.low_spin.setEnabled(goal == "within")
278
+ if self.high_spin is not None:
279
+ self.high_spin.setEnabled(goal == "within")
280
+ self._update_status_label()
281
+
282
+ def _optimize_response(self) -> None:
283
+ goal = self._current_goal()
284
+ if goal.goal == "target" and goal.target is None:
285
+ self._show_status("Optimize Response: enter a target value", error=True)
286
+ return
287
+ if goal.goal == "within" and (
288
+ goal.low is None or goal.high is None or goal.high <= goal.low
289
+ ):
290
+ self._show_status("Optimize Response: enter low < high", error=True)
291
+ return
292
+ if self.optimize_button is not None:
293
+ self.optimize_button.setEnabled(False)
294
+ QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
295
+ try:
296
+ self.session.optimize_response(goal)
297
+ except Exception as exc:
298
+ self._show_status(f"Optimize Response: {exc}", error=True)
299
+ return
300
+ finally:
301
+ QApplication.restoreOverrideCursor()
302
+ if self.optimize_button is not None:
303
+ self.optimize_button.setEnabled(True)
304
+ self._sync_controls()
305
+ self._redraw()
306
+ self.changed.emit()
307
+
308
+ def _control_changed(self, name: str, value: Any) -> None:
309
+ if self._syncing:
310
+ return
311
+ if self.session.set_value(name, value):
312
+ self._sync_controls()
313
+ self._redraw()
314
+ self.changed.emit()
315
+
316
+ def _lock_toggled(self, name: str, checked: bool) -> None:
317
+ factor = self.session.factor(name)
318
+ factor.locked = bool(checked)
319
+ control = self._controls.get(name)
320
+ if control is not None:
321
+ control.setEnabled(not checked)
322
+
323
+ def _on_press(self, event) -> None:
324
+ if getattr(event, "button", None) != 1:
325
+ return
326
+ name = self._axes.get(getattr(event, "inaxes", None))
327
+ if name is None or event.xdata is None:
328
+ return
329
+ factor = self.session.factor(name)
330
+ if factor.locked:
331
+ return
332
+ self._dragging = name
333
+ self._set_from_x(name, float(event.xdata))
334
+
335
+ def _on_motion(self, event) -> None:
336
+ if self._dragging is None or event.xdata is None:
337
+ return
338
+ self._set_from_x(self._dragging, float(event.xdata))
339
+
340
+ def _on_release(self, _event) -> None:
341
+ self._dragging = None
342
+
343
+ def _set_from_x(self, name: str, value: float) -> None:
344
+ factor = self.session.factor(name)
345
+ if factor.kind == "categorical":
346
+ if not factor.levels:
347
+ return
348
+ index = int(round(value))
349
+ index = min(len(factor.levels) - 1, max(0, index))
350
+ value = factor.levels[index]
351
+ if self.session.set_value(name, value):
352
+ self._sync_controls()
353
+ self._redraw()
354
+ self.changed.emit()
355
+
356
+ def _sync_controls(self) -> None:
357
+ self._syncing = True
358
+ try:
359
+ for name, control in self._controls.items():
360
+ factor = self.session.factor(name)
361
+ if isinstance(control, QDoubleSpinBox):
362
+ control.setValue(float(factor.current))
363
+ elif isinstance(control, QComboBox):
364
+ control.setCurrentText(str(factor.current))
365
+ control.setEnabled(not factor.locked)
366
+ finally:
367
+ self._syncing = False
368
+
369
+ def _redraw(self) -> None:
370
+ if not self.factors:
371
+ self.canvas.draw_idle()
372
+ return
373
+ profiles: dict[str, dict[str, Any]] = {}
374
+ all_values: list[float] = []
375
+ for factor in self.factors:
376
+ profile = self.session.profile(factor.name, self.points)
377
+ profiles[factor.name] = profile
378
+ all_values.extend(float(value) for value in profile["y"] if np.isfinite(value))
379
+ self._lines[factor.name].set_data(profile["x"], profile["y"])
380
+ marker = self._markers[factor.name]
381
+ marker.set_xdata([profile["current"], profile["current"]])
382
+ current = self.session.current_prediction()
383
+ if np.isfinite(current):
384
+ all_values.append(float(current))
385
+ if all_values:
386
+ low = min(all_values)
387
+ high = max(all_values)
388
+ if high <= low:
389
+ padding = max(abs(low) * 0.05, 1e-9)
390
+ else:
391
+ padding = (high - low) * 0.06
392
+ low -= padding
393
+ high += padding
394
+ else:
395
+ low, high = 0.0, 1.0
396
+ for factor in self.factors:
397
+ axis = next(ax for ax, name in self._axes.items() if name == factor.name)
398
+ axis.set_ylim(low, high)
399
+ profile = profiles[factor.name]
400
+ self._dots[factor.name].set_data([profile["current"]], [current])
401
+ self._update_value_label(current)
402
+ self._update_status_label()
403
+ self.canvas.draw_idle()
404
+
405
+ def _update_value_label(self, current: float | None = None) -> None:
406
+ value = self.session.current_prediction() if current is None else current
407
+ self.value_label.setText(f"{self.session.response_label}: {value:.6g}")
408
+
409
+ def _show_status(self, text: str, error: bool = False) -> None:
410
+ if self.status_label is None:
411
+ return
412
+ self.status_label.setText(text)
413
+ self.status_label.setStyleSheet("color:#a33;" if error else "color:#5a6270;")
414
+
415
+ def _update_status_label(self) -> None:
416
+ value = self.session.current_prediction()
417
+ if np.isfinite(value):
418
+ self._show_status(f"Predicted response: {value:.6g}")
419
+ else:
420
+ self._show_status("Predicted response: —")
421
+
422
+ def set_factor_value(self, name: str, value: Any) -> bool:
423
+ if not self.session.set_value(name, value):
424
+ return False
425
+ self._sync_controls()
426
+ self._redraw()
427
+ self.changed.emit()
428
+ return True
429
+
430
+ def reset(self) -> None:
431
+ self.session.reset()
432
+ self._sync_controls()
433
+ self._redraw()
434
+ self.changed.emit()
435
+
436
+ def snapshot_frame(self):
437
+ return self.session.snapshot_frame(self.points)
@@ -0,0 +1,82 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from PySide6.QtCore import QSettings
6
+
7
+ from statstudio.ui.theme import SETTINGS_APPLICATION, SETTINGS_ORGANIZATION
8
+
9
+ RECENT_PROJECTS_KEY = "recent/projects"
10
+ RECENT_COMMANDS_KEY = "recent/commands"
11
+ FAVORITE_COMMANDS_KEY = "hub/favorites"
12
+
13
+
14
+ def _settings() -> QSettings:
15
+ return QSettings(SETTINGS_ORGANIZATION, SETTINGS_APPLICATION)
16
+
17
+
18
+ def _as_list(value) -> list[str]:
19
+ if value is None:
20
+ return []
21
+ if isinstance(value, str):
22
+ return [value] if value else []
23
+ try:
24
+ return [str(item) for item in value if str(item)]
25
+ except TypeError:
26
+ return []
27
+
28
+
29
+ def recent_projects(limit: int = 8) -> list[str]:
30
+ paths = _as_list(_settings().value(RECENT_PROJECTS_KEY, []))
31
+ unique: list[str] = []
32
+ for path in paths:
33
+ if path not in unique:
34
+ unique.append(path)
35
+ return unique[:limit]
36
+
37
+
38
+ def remember_project(path: str | Path, limit: int = 8) -> None:
39
+ if not path:
40
+ return
41
+ value = str(Path(path).expanduser().resolve())
42
+ paths = [item for item in recent_projects(10000) if item != value]
43
+ paths.insert(0, value)
44
+ _settings().setValue(RECENT_PROJECTS_KEY, paths[:limit])
45
+
46
+
47
+ def forget_project(path: str | Path) -> None:
48
+ value = str(Path(path).expanduser().resolve())
49
+ paths = [item for item in recent_projects(10000) if item != value]
50
+ _settings().setValue(RECENT_PROJECTS_KEY, paths)
51
+
52
+
53
+ def recent_commands(limit: int = 12) -> list[str]:
54
+ values = _as_list(_settings().value(RECENT_COMMANDS_KEY, []))
55
+ unique: list[str] = []
56
+ for value in values:
57
+ if value not in unique:
58
+ unique.append(value)
59
+ return unique[:limit]
60
+
61
+
62
+ def remember_command(command_id: str, limit: int = 12) -> None:
63
+ if not command_id:
64
+ return
65
+ values = [item for item in recent_commands(10000) if item != command_id]
66
+ values.insert(0, command_id)
67
+ _settings().setValue(RECENT_COMMANDS_KEY, values[:limit])
68
+
69
+
70
+ def favorite_commands() -> list[str]:
71
+ return _as_list(_settings().value(FAVORITE_COMMANDS_KEY, []))
72
+
73
+
74
+ def toggle_favorite(command_id: str) -> bool:
75
+ values = favorite_commands()
76
+ if command_id in values:
77
+ values = [item for item in values if item != command_id]
78
+ _settings().setValue(FAVORITE_COMMANDS_KEY, values)
79
+ return False
80
+ values.append(command_id)
81
+ _settings().setValue(FAVORITE_COMMANDS_KEY, values)
82
+ return True
File without changes