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,299 @@
1
+ from __future__ import annotations
2
+
3
+ import pandas as pd
4
+ from PySide6.QtCore import Qt
5
+ from PySide6.QtWidgets import QAbstractItemView, QComboBox, QTableWidget, QTableWidgetItem
6
+
7
+ from statstudio.core.table import DataTable
8
+ from statstudio.stats import bayesian_optimization
9
+ from statstudio.stats.results import AnalysisResult
10
+ from statstudio.ui.dialogs.base import BaseDialog, combo_value
11
+ from statstudio.ui.dialogs.stats_dialogs import numeric_columns
12
+
13
+
14
+ class BayesianOptimizationDialog(BaseDialog):
15
+ def __init__(self, table: DataTable, parent=None) -> None:
16
+ super().__init__(table, "Bayesian Optimization", parent)
17
+ self.add_label(
18
+ "Fits a Gaussian-process surrogate to the observed runs and recommends the next experiment. "
19
+ "Add the recommended run to the table and re-run to update the recommendation."
20
+ )
21
+ numeric = numeric_columns(table)
22
+ self.response_combo = self.add_combo("Response", numeric, default=numeric[-1] if numeric else None)
23
+ self.goal_combo = self.add_combo("Goal", ["Maximize", "Minimize"], default="Maximize")
24
+ self.factor_table = QTableWidget(0, 6)
25
+ self.factor_table.setHorizontalHeaderLabels(["Use", "Factor", "Type", "Low", "High", "Levels"])
26
+ self.factor_table.horizontalHeader().setStretchLastSection(True)
27
+ self.factor_table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
28
+ self.factor_table.setMaximumHeight(230)
29
+ self.add_row("Factors", self.factor_table)
30
+ self.response_combo.currentIndexChanged.connect(self._populate_factors)
31
+ self._populate_factors()
32
+
33
+ self.add_page("Acquisition")
34
+ self.acquisition_combo = self.add_combo(
35
+ "Acquisition",
36
+ ["Expected Improvement", "Probability of Improvement", "Upper Confidence Bound"],
37
+ default="Expected Improvement",
38
+ )
39
+ self._acquisition_form = self._form
40
+ self.xi_spin = self.add_float("Exploration xi", 0.01, 0.0, 1000.0, 4)
41
+ self.xi_spin.setToolTip("Exploration margin in standardized response units for EI and PI.")
42
+ self.kappa_spin = self.add_float("Exploration kappa", 2.0, 0.001, 1000.0, 3)
43
+ self.kappa_spin.setToolTip("Standard-deviation multiplier for the upper-confidence-bound acquisition.")
44
+ self.proposals_spin = self.add_int("Proposed runs", 1, 1, 20)
45
+ self.restarts_spin = self.add_int("GP restarts", 5, 0, 50)
46
+ self.seed_spin = self.add_int("Random seed", 42, 0, 2_000_000_000)
47
+ self.acquisition_combo.currentIndexChanged.connect(self._update_acquisition_controls)
48
+ self._update_acquisition_controls()
49
+
50
+ self.add_page("Advanced")
51
+ self.max_categories_spin = self.add_int("Max categorical combinations", 512, 1, 5_000)
52
+
53
+ def _label(self, value):
54
+ if pd.isna(value):
55
+ return ""
56
+ if isinstance(value, float) and value.is_integer():
57
+ return str(int(value))
58
+ return str(value).strip()
59
+
60
+ def _analysis_frame(self):
61
+ return self.table.analysis_df(honor_modeling=True)
62
+
63
+ def _numeric_bounds(self, column: str) -> tuple[str, str]:
64
+ frame = self._analysis_frame()
65
+ values = pd.to_numeric(frame[column], errors="coerce").dropna()
66
+ if values.empty:
67
+ return "", ""
68
+ return repr(float(values.min())), repr(float(values.max()))
69
+
70
+ def _factor_default(self, column: str) -> tuple[str, str, str, str]:
71
+ spec = self.table.specs.get(column)
72
+ frame = self._analysis_frame()
73
+ numeric = pd.api.types.is_numeric_dtype(frame[column])
74
+ continuous = numeric and (spec is None or spec.modeling_type == "continuous")
75
+ if continuous:
76
+ low, high = self._numeric_bounds(column)
77
+ return "Continuous", low, high, ""
78
+ values = sorted({self._label(value) for value in frame[column].dropna().unique()})
79
+ return "Categorical", "", "", ", ".join(value for value in values if value)
80
+
81
+ def _populate_factors(self, *_args) -> None:
82
+ response = combo_value(self.response_combo)
83
+ columns = [column for column in self.table.columns if column != response]
84
+ self.factor_table.setRowCount(len(columns))
85
+ numeric_response = response is not None
86
+ for row, column in enumerate(columns):
87
+ kind, low, high, levels = self._factor_default(column)
88
+ use = QTableWidgetItem("")
89
+ use.setFlags(
90
+ Qt.ItemFlag.ItemIsEnabled
91
+ | Qt.ItemFlag.ItemIsSelectable
92
+ | Qt.ItemFlag.ItemIsUserCheckable
93
+ )
94
+ use.setCheckState(Qt.CheckState.Checked if numeric_response and kind == "Continuous" else Qt.CheckState.Unchecked)
95
+ self.factor_table.setItem(row, 0, use)
96
+ name_item = QTableWidgetItem(column)
97
+ name_item.setFlags(name_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
98
+ self.factor_table.setItem(row, 1, name_item)
99
+ type_combo = QComboBox()
100
+ type_combo.addItems(["Continuous", "Categorical"])
101
+ type_combo.setCurrentText(kind)
102
+ type_combo.currentTextChanged.connect(
103
+ lambda _text, target=row: self._refresh_factor_type(target)
104
+ )
105
+ self.factor_table.setCellWidget(row, 2, type_combo)
106
+ self.factor_table.setItem(row, 3, QTableWidgetItem(low))
107
+ self.factor_table.setItem(row, 4, QTableWidgetItem(high))
108
+ self.factor_table.setItem(row, 5, QTableWidgetItem(levels))
109
+
110
+ def _refresh_factor_type(self, row: int) -> None:
111
+ name_item = self.factor_table.item(row, 1)
112
+ if name_item is None:
113
+ return
114
+ type_combo = self.factor_table.cellWidget(row, 2)
115
+ if not isinstance(type_combo, QComboBox):
116
+ return
117
+ if type_combo.currentText() == "Continuous":
118
+ low, high = self._numeric_bounds(name_item.text())
119
+ self.factor_table.setItem(row, 3, QTableWidgetItem(low))
120
+ self.factor_table.setItem(row, 4, QTableWidgetItem(high))
121
+ self.factor_table.setItem(row, 5, QTableWidgetItem(""))
122
+ else:
123
+ values = sorted(
124
+ {self._label(value) for value in self._analysis_frame()[name_item.text()].dropna().unique()}
125
+ )
126
+ self.factor_table.setItem(row, 3, QTableWidgetItem(""))
127
+ self.factor_table.setItem(row, 4, QTableWidgetItem(""))
128
+ levels_item = QTableWidgetItem(", ".join(value for value in values if value))
129
+ levels_item.setData(Qt.ItemDataRole.UserRole, [value for value in values if value])
130
+ self.factor_table.setItem(row, 5, levels_item)
131
+
132
+ def _update_acquisition_controls(self, *_args) -> None:
133
+ acquisition = combo_value(self.acquisition_combo) or "Expected Improvement"
134
+ xi_enabled = acquisition in {"Expected Improvement", "Probability of Improvement"}
135
+ kappa_enabled = acquisition == "Upper Confidence Bound"
136
+ for widget, enabled in ((self.xi_spin, xi_enabled), (self.kappa_spin, kappa_enabled)):
137
+ widget.setEnabled(enabled)
138
+ label = self._acquisition_form.labelForField(widget)
139
+ if label is not None:
140
+ label.setEnabled(enabled)
141
+
142
+ def _set_combo(self, combo: QComboBox, value) -> None:
143
+ if value is None:
144
+ return
145
+ index = combo.findData(value)
146
+ if index < 0:
147
+ index = combo.findText(str(value))
148
+ if index >= 0:
149
+ combo.setCurrentIndex(index)
150
+
151
+ def apply_params(self, params: dict | None) -> None:
152
+ params = dict(params or {})
153
+ response = params.pop("response", None)
154
+ goal = params.pop("goal", None)
155
+ acquisition = params.pop("acquisition", None)
156
+ proposals = params.pop("proposals", None)
157
+ xi = params.pop("xi", None)
158
+ kappa = params.pop("kappa", None)
159
+ restarts = params.pop("restarts", None)
160
+ seed = params.pop("seed", None)
161
+ max_categories = params.pop("max_categorical_combinations", None)
162
+ factors = params.pop("factors", []) or []
163
+ factor_types = params.pop("factor_types", {}) or {}
164
+ bounds = params.pop("bounds", {}) or {}
165
+ levels = params.pop("levels", {}) or {}
166
+ factor_names = {str(name) for name in factors}
167
+
168
+ self._set_combo(self.response_combo, response)
169
+ self._set_combo(self.goal_combo, str(goal).title() if goal else None)
170
+ acquisition_labels = {
171
+ "expected_improvement": "Expected Improvement",
172
+ "probability_improvement": "Probability of Improvement",
173
+ "upper_confidence_bound": "Upper Confidence Bound",
174
+ }
175
+ self._set_combo(self.acquisition_combo, acquisition_labels.get(str(acquisition), acquisition))
176
+ for widget, value in (
177
+ (self.proposals_spin, proposals),
178
+ (self.xi_spin, xi),
179
+ (self.kappa_spin, kappa),
180
+ (self.restarts_spin, restarts),
181
+ (self.seed_spin, seed),
182
+ (self.max_categories_spin, max_categories),
183
+ ):
184
+ if value is not None:
185
+ widget.setValue(value)
186
+
187
+ self._populate_factors()
188
+ for row in range(self.factor_table.rowCount()):
189
+ use = self.factor_table.item(row, 0)
190
+ if use is not None:
191
+ use.setCheckState(Qt.CheckState.Unchecked)
192
+ for row in range(self.factor_table.rowCount()):
193
+ name_item = self.factor_table.item(row, 1)
194
+ if name_item is None:
195
+ continue
196
+ name = name_item.text()
197
+ if name not in factor_types and name not in factor_names:
198
+ continue
199
+ use = self.factor_table.item(row, 0)
200
+ if use is not None:
201
+ use.setCheckState(Qt.CheckState.Checked)
202
+ type_combo = self.factor_table.cellWidget(row, 2)
203
+ if isinstance(type_combo, QComboBox) and name in factor_types:
204
+ kind = str(factor_types[name]).lower()
205
+ type_combo.setCurrentText("Categorical" if kind in {"categorical", "nominal", "ordinal"} else "Continuous")
206
+ if name in bounds:
207
+ low, high = bounds[name]
208
+ self.factor_table.setItem(row, 3, QTableWidgetItem(repr(float(low))))
209
+ self.factor_table.setItem(row, 4, QTableWidgetItem(repr(float(high))))
210
+ if name in levels:
211
+ values = [str(level) for level in levels[name]]
212
+ levels_item = QTableWidgetItem(", ".join(values))
213
+ levels_item.setData(Qt.ItemDataRole.UserRole, values)
214
+ self.factor_table.setItem(row, 5, levels_item)
215
+ self._update_acquisition_controls()
216
+
217
+ @staticmethod
218
+ def _float(text: str, label: str) -> float:
219
+ try:
220
+ return float(text.strip())
221
+ except (TypeError, ValueError) as exc:
222
+ raise ValueError(f"Invalid {label}: {text!r}") from exc
223
+
224
+ def _request(self):
225
+ response = combo_value(self.response_combo) or ""
226
+ if not response:
227
+ raise ValueError("Choose a numeric response.")
228
+ factors: list[str] = []
229
+ factor_types: dict[str, str] = {}
230
+ bounds: dict[str, list[float]] = {}
231
+ levels: dict[str, list[str]] = {}
232
+ for row in range(self.factor_table.rowCount()):
233
+ use = self.factor_table.item(row, 0)
234
+ name_item = self.factor_table.item(row, 1)
235
+ if use is None or name_item is None or use.checkState() != Qt.CheckState.Checked:
236
+ continue
237
+ name = name_item.text()
238
+ if name == response:
239
+ raise ValueError("The response cannot also be a factor.")
240
+ type_combo = self.factor_table.cellWidget(row, 2)
241
+ kind = type_combo.currentText().lower() if isinstance(type_combo, QComboBox) else "continuous"
242
+ factors.append(name)
243
+ factor_types[name] = "categorical" if kind == "categorical" else "continuous"
244
+ if factor_types[name] == "continuous":
245
+ low = self.factor_table.item(row, 3)
246
+ high = self.factor_table.item(row, 4)
247
+ bounds[name] = [
248
+ self._float(low.text() if low else "", f"lower bound for {name}"),
249
+ self._float(high.text() if high else "", f"upper bound for {name}"),
250
+ ]
251
+ else:
252
+ levels_item = self.factor_table.item(row, 5)
253
+ stored = levels_item.data(Qt.ItemDataRole.UserRole) if levels_item is not None else None
254
+ text = levels_item.text() if levels_item is not None else ""
255
+ if isinstance(stored, list) and text == ", ".join(str(value) for value in stored):
256
+ values = [str(value) for value in stored]
257
+ else:
258
+ values = [value.strip() for value in text.split(",") if value.strip()]
259
+ if values:
260
+ levels[name] = values
261
+ if not factors:
262
+ raise ValueError("Select at least one factor.")
263
+ acquisition = combo_value(self.acquisition_combo) or "Expected Improvement"
264
+ acquisition_key = {
265
+ "Expected Improvement": "expected_improvement",
266
+ "Probability of Improvement": "probability_improvement",
267
+ "Upper Confidence Bound": "upper_confidence_bound",
268
+ }[acquisition]
269
+ return (
270
+ self.df,
271
+ response,
272
+ factors,
273
+ {
274
+ "goal": "maximize" if combo_value(self.goal_combo) == "Maximize" else "minimize",
275
+ "acquisition": acquisition_key,
276
+ "proposals": self.proposals_spin.value(),
277
+ "xi": self.xi_spin.value(),
278
+ "kappa": self.kappa_spin.value(),
279
+ "factor_types": factor_types,
280
+ "bounds": bounds,
281
+ "levels": levels,
282
+ "restarts": self.restarts_spin.value(),
283
+ "max_categorical_combinations": self.max_categories_spin.value(),
284
+ "seed": self.seed_spin.value(),
285
+ },
286
+ )
287
+
288
+ def make_job(self):
289
+ df, response, factors, kwargs = self._request()
290
+ return lambda token, progress: bayesian_optimization.bayesian_optimize(
291
+ df,
292
+ response,
293
+ factors,
294
+ **kwargs,
295
+ )
296
+
297
+ def compute(self) -> AnalysisResult:
298
+ df, response, factors, kwargs = self._request()
299
+ return self.finish(bayesian_optimization.bayesian_optimize(df, response, factors, **kwargs))