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,590 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import math
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Sequence
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ from scipy.optimize import differential_evolution
11
+ from scipy.stats import norm
12
+ from sklearn.gaussian_process import GaussianProcessRegressor
13
+ from sklearn.gaussian_process.kernels import ConstantKernel, Matern, WhiteKernel
14
+
15
+ from statstudio.stats.results import AnalysisResult
16
+
17
+
18
+ @dataclass
19
+ class _FactorSpec:
20
+ name: str
21
+ kind: str
22
+ low: float | None = None
23
+ high: float | None = None
24
+ levels: list[str] = field(default_factory=list)
25
+
26
+
27
+ def _label(value: Any) -> str | None:
28
+ if pd.isna(value):
29
+ return None
30
+ if isinstance(value, (float, np.floating)) and float(value).is_integer():
31
+ return str(int(value))
32
+ return str(value).strip()
33
+
34
+
35
+ def _goal(value: str | None) -> str:
36
+ key = str(value or "maximize").strip().lower()
37
+ if key in {"max", "maximize", "maximum", "higher"}:
38
+ return "maximize"
39
+ if key in {"min", "minimize", "minimum", "lower"}:
40
+ return "minimize"
41
+ raise ValueError("Optimization goal must be maximize or minimize.")
42
+
43
+
44
+ def _acquisition(value: str | None) -> str:
45
+ key = str(value or "ei").strip().lower().replace("-", "_").replace(" ", "_")
46
+ if key in {"ei", "expected_improvement", "expectedimprovement"}:
47
+ return "expected_improvement"
48
+ if key in {"pi", "probability_improvement", "probability_of_improvement"}:
49
+ return "probability_improvement"
50
+ if key in {"ucb", "upper_confidence_bound"}:
51
+ return "upper_confidence_bound"
52
+ raise ValueError("Acquisition must be expected_improvement, probability_improvement, or upper_confidence_bound.")
53
+
54
+
55
+ def _prepare(
56
+ df: pd.DataFrame,
57
+ response: str,
58
+ factors: Sequence[str],
59
+ factor_types: dict[str, str] | None,
60
+ bounds: dict[str, Sequence[float]] | None,
61
+ levels: dict[str, Sequence[Any]] | None,
62
+ ) -> tuple[pd.DataFrame, list[_FactorSpec]]:
63
+ if response not in df.columns:
64
+ raise KeyError(response)
65
+ names = [str(name) for name in dict.fromkeys(factors) if str(name)]
66
+ if not names:
67
+ raise ValueError("Choose at least one factor.")
68
+ if response in names:
69
+ raise ValueError("The response cannot also be a factor.")
70
+ reserved = {
71
+ "Run",
72
+ "Predicted",
73
+ "Predicted SD",
74
+ "Predicted Response",
75
+ "Projected Improvement",
76
+ "Expected Improvement",
77
+ "Probability Improvement",
78
+ "Acquisition",
79
+ "Observed",
80
+ "Observed Response",
81
+ "Residual",
82
+ }
83
+ conflicts = [name for name in names if name in reserved]
84
+ if conflicts:
85
+ raise ValueError(f"Factor names conflict with result columns: {', '.join(conflicts)}.")
86
+ missing = [name for name in names if name not in df.columns]
87
+ if missing:
88
+ raise KeyError(f"Missing factor columns: {', '.join(missing)}")
89
+
90
+ frame = df.loc[:, [response, *names]].copy()
91
+ frame[response] = pd.to_numeric(frame[response], errors="coerce")
92
+ factor_types = factor_types or {}
93
+ bounds = bounds or {}
94
+ levels = levels or {}
95
+ specs: list[_FactorSpec] = []
96
+
97
+ for name in names:
98
+ requested = str(factor_types.get(name, "")).strip().lower()
99
+ numeric = pd.api.types.is_numeric_dtype(frame[name])
100
+ if requested in {"categorical", "nominal", "ordinal", "cat"}:
101
+ kind = "categorical"
102
+ elif requested in {"continuous", "numeric", "cont"}:
103
+ kind = "continuous"
104
+ else:
105
+ kind = "continuous" if numeric else "categorical"
106
+
107
+ if kind == "continuous":
108
+ values = pd.to_numeric(frame[name], errors="coerce")
109
+ finite = values[np.isfinite(values)]
110
+ if finite.empty:
111
+ raise ValueError(f"Factor {name!r} has no numeric values.")
112
+ observed_low = float(finite.min())
113
+ observed_high = float(finite.max())
114
+ if name in bounds:
115
+ low, high = (float(value) for value in bounds[name])
116
+ else:
117
+ low, high = observed_low, observed_high
118
+ if not (math.isfinite(low) and math.isfinite(high) and low < high):
119
+ raise ValueError(f"Factor {name!r} needs finite lower and upper bounds with lower < upper.")
120
+ frame[name] = values
121
+ specs.append(_FactorSpec(name, "continuous", low, high))
122
+ else:
123
+ labels = frame[name].map(_label)
124
+ provided = [str(value) for value in (levels.get(name) or []) if str(value).strip()]
125
+ if provided:
126
+ all_levels = list(dict.fromkeys(provided))
127
+ frame = frame.loc[labels.isin(all_levels)]
128
+ labels = labels.loc[frame.index]
129
+ else:
130
+ all_levels = sorted(pd.unique(labels.dropna()).tolist())
131
+ if len(all_levels) < 2:
132
+ raise ValueError(f"Categorical factor {name!r} needs at least two levels.")
133
+ frame[name] = labels
134
+ specs.append(_FactorSpec(name, "categorical", levels=all_levels))
135
+
136
+ frame = frame.replace([np.inf, -np.inf], np.nan)
137
+ frame = frame.dropna(subset=[response, *names])
138
+ if len(frame) < 5:
139
+ raise ValueError("At least five complete observations are required for Bayesian optimization.")
140
+ if float(frame[response].std(ddof=0)) == 0:
141
+ raise ValueError("The response column must vary.")
142
+ return frame, specs
143
+
144
+
145
+ def _encode_frame(frame: pd.DataFrame, specs: Sequence[_FactorSpec]) -> np.ndarray:
146
+ columns: list[np.ndarray] = []
147
+ for spec in specs:
148
+ if spec.kind == "continuous":
149
+ values = pd.to_numeric(frame[spec.name], errors="coerce").to_numpy(dtype=float)
150
+ columns.append((values - float(spec.low)) / (float(spec.high) - float(spec.low)))
151
+ else:
152
+ labels = frame[spec.name].map(_label)
153
+ for level in spec.levels:
154
+ columns.append((labels == level).to_numpy(dtype=float))
155
+ return np.column_stack(columns)
156
+
157
+
158
+ def _encode_settings(settings: dict[str, Any], specs: Sequence[_FactorSpec]) -> np.ndarray:
159
+ values: list[float] = []
160
+ for spec in specs:
161
+ if spec.kind == "continuous":
162
+ low = float(spec.low)
163
+ high = float(spec.high)
164
+ values.append((float(settings[spec.name]) - low) / (high - low))
165
+ else:
166
+ label = _label(settings[spec.name])
167
+ values.extend(1.0 if label == level else 0.0 for level in spec.levels)
168
+ return np.asarray(values, dtype=float)
169
+
170
+
171
+ def _settings_from_vector(
172
+ continuous: Sequence[_FactorSpec],
173
+ categorical: Sequence[_FactorSpec],
174
+ vector: Sequence[float],
175
+ levels: dict[str, str],
176
+ ) -> dict[str, Any]:
177
+ settings: dict[str, Any] = {}
178
+ for spec, value in zip(continuous, vector):
179
+ low = float(spec.low)
180
+ high = float(spec.high)
181
+ settings[spec.name] = low + float(np.clip(value, 0.0, 1.0)) * (high - low)
182
+ for spec in categorical:
183
+ settings[spec.name] = levels[spec.name]
184
+ return settings
185
+
186
+
187
+ def _categorical_combinations(
188
+ specs: Sequence[_FactorSpec],
189
+ maximum: int,
190
+ ) -> list[dict[str, str]]:
191
+ if not specs:
192
+ return [{}]
193
+ count = math.prod(len(spec.levels) for spec in specs)
194
+ if count > maximum:
195
+ raise ValueError(
196
+ f"The selected categorical factors create {count} combinations, above the limit of {maximum}. "
197
+ "Reduce the factors or raise the maximum in Advanced."
198
+ )
199
+ keys = [spec.name for spec in specs]
200
+ return [dict(zip(keys, values)) for values in itertools.product(*(spec.levels for spec in specs))]
201
+
202
+
203
+ def _fit_surrogate(frame: pd.DataFrame, specs: Sequence[_FactorSpec], restarts: int, seed: int):
204
+ x = _encode_frame(frame, specs)
205
+ y = frame.iloc[:, 0].to_numpy(dtype=float)
206
+ dimensions = x.shape[1]
207
+ kernel = (
208
+ ConstantKernel(1.0, (1e-3, 1e3))
209
+ * Matern(length_scale=np.ones(dimensions), length_scale_bounds=(1e-3, 1e3), nu=2.5)
210
+ + WhiteKernel(noise_level=1e-6, noise_level_bounds=(1e-10, 1e0))
211
+ )
212
+ model = GaussianProcessRegressor(
213
+ kernel=kernel,
214
+ normalize_y=True,
215
+ n_restarts_optimizer=max(0, int(restarts)),
216
+ random_state=int(seed),
217
+ alpha=1e-10,
218
+ )
219
+ model.fit(x, y)
220
+ return model, x, y
221
+
222
+
223
+ def _acquisition_values(
224
+ model: GaussianProcessRegressor,
225
+ x: np.ndarray,
226
+ *,
227
+ sign: float,
228
+ y_center: float,
229
+ y_scale: float,
230
+ best_scaled: float,
231
+ acquisition: str,
232
+ xi: float,
233
+ kappa: float,
234
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
235
+ mean, standard_deviation = model.predict(np.atleast_2d(x), return_std=True)
236
+ mean = np.asarray(mean, dtype=float).reshape(-1)
237
+ standard_deviation = np.maximum(np.asarray(standard_deviation, dtype=float).reshape(-1) / y_scale, 1e-12)
238
+ signed_mean = sign * (mean - y_center) / y_scale
239
+ improvement = signed_mean - best_scaled - xi
240
+ z = improvement / standard_deviation
241
+ expected_improvement = np.maximum(
242
+ improvement * norm.cdf(z) + standard_deviation * norm.pdf(z),
243
+ 0.0,
244
+ )
245
+ probability_improvement = norm.cdf(z)
246
+ upper_confidence = signed_mean + kappa * standard_deviation
247
+ if acquisition == "expected_improvement":
248
+ score = expected_improvement
249
+ elif acquisition == "probability_improvement":
250
+ score = probability_improvement
251
+ else:
252
+ score = upper_confidence
253
+ return mean, standard_deviation * y_scale, expected_improvement, probability_improvement, score
254
+
255
+
256
+ def _candidate_distance(first: dict[str, Any], second: dict[str, Any], specs: Sequence[_FactorSpec]) -> float:
257
+ total = 0.0
258
+ for spec in specs:
259
+ if spec.kind == "continuous":
260
+ value = (float(first[spec.name]) - float(second[spec.name])) / (float(spec.high) - float(spec.low))
261
+ total += value**2
262
+ elif _label(first[spec.name]) != _label(second[spec.name]):
263
+ total += 1.0
264
+ return math.sqrt(total / max(1, len(specs)))
265
+
266
+
267
+ def _select_candidates(
268
+ candidates: Sequence[dict[str, Any]],
269
+ proposals: int,
270
+ specs: Sequence[_FactorSpec],
271
+ ) -> list[dict[str, Any]]:
272
+ ordered = sorted(candidates, key=lambda item: item["score"], reverse=True)
273
+ selected: list[dict[str, Any]] = []
274
+ for candidate in ordered:
275
+ if all(_candidate_distance(candidate["settings"], item["settings"], specs) >= 0.05 for item in selected):
276
+ selected.append(candidate)
277
+ if len(selected) >= proposals:
278
+ return selected
279
+ for candidate in ordered:
280
+ if candidate in selected:
281
+ continue
282
+ selected.append(candidate)
283
+ if len(selected) >= proposals:
284
+ break
285
+ return selected
286
+
287
+
288
+ def _surface_frame(
289
+ model: GaussianProcessRegressor,
290
+ specs: Sequence[_FactorSpec],
291
+ base_settings: dict[str, Any],
292
+ *,
293
+ sign: float,
294
+ y_center: float,
295
+ y_scale: float,
296
+ best_scaled: float,
297
+ acquisition: str,
298
+ xi: float,
299
+ kappa: float,
300
+ points: int = 25,
301
+ ) -> pd.DataFrame | None:
302
+ continuous = [spec for spec in specs if spec.kind == "continuous"]
303
+ if len(continuous) < 2:
304
+ return None
305
+ first, second = continuous[:2]
306
+ first_values = np.linspace(float(first.low), float(first.high), points)
307
+ second_values = np.linspace(float(second.low), float(second.high), points)
308
+ rows: list[dict[str, Any]] = []
309
+ for first_value in first_values:
310
+ for second_value in second_values:
311
+ settings = dict(base_settings)
312
+ settings[first.name] = float(first_value)
313
+ settings[second.name] = float(second_value)
314
+ encoded = _encode_settings(settings, specs)
315
+ mean, standard_deviation, expected_improvement, probability_improvement, score = _acquisition_values(
316
+ model,
317
+ encoded,
318
+ sign=sign,
319
+ y_center=y_center,
320
+ y_scale=y_scale,
321
+ best_scaled=best_scaled,
322
+ acquisition=acquisition,
323
+ xi=xi,
324
+ kappa=kappa,
325
+ )
326
+ rows.append(
327
+ {
328
+ first.name: float(first_value),
329
+ second.name: float(second_value),
330
+ "Predicted": float(mean[0]),
331
+ "Predicted SD": float(standard_deviation[0]),
332
+ "Expected Improvement": float(expected_improvement[0] * y_scale),
333
+ "Probability Improvement": float(probability_improvement[0]),
334
+ "Acquisition": float(score[0]),
335
+ }
336
+ )
337
+ return pd.DataFrame(rows)
338
+
339
+
340
+ def bayesian_optimize(
341
+ df: pd.DataFrame,
342
+ response: str,
343
+ factors: Sequence[str],
344
+ *,
345
+ goal: str = "maximize",
346
+ acquisition: str = "expected_improvement",
347
+ proposals: int = 1,
348
+ xi: float = 0.01,
349
+ kappa: float = 2.0,
350
+ factor_types: dict[str, str] | None = None,
351
+ bounds: dict[str, Sequence[float]] | None = None,
352
+ levels: dict[str, Sequence[Any]] | None = None,
353
+ restarts: int = 5,
354
+ max_categorical_combinations: int = 512,
355
+ seed: int = 42,
356
+ ) -> AnalysisResult:
357
+ goal = _goal(goal)
358
+ acquisition = _acquisition(acquisition)
359
+ proposals = int(proposals)
360
+ if proposals < 1:
361
+ raise ValueError("At least one proposal is required.")
362
+ if proposals > 20:
363
+ raise ValueError("At most 20 proposals can be requested.")
364
+ xi = float(xi)
365
+ kappa = float(kappa)
366
+ if not math.isfinite(xi) or xi < 0:
367
+ raise ValueError("xi must be finite and non-negative.")
368
+ if not math.isfinite(kappa) or kappa <= 0:
369
+ raise ValueError("kappa must be finite and positive.")
370
+ if int(restarts) < 0:
371
+ raise ValueError("Restarts cannot be negative.")
372
+ if int(max_categorical_combinations) < 1:
373
+ raise ValueError("The categorical-combination limit must be positive.")
374
+
375
+ frame, specs = _prepare(df, response, factors, factor_types, bounds, levels)
376
+ continuous = [spec for spec in specs if spec.kind == "continuous"]
377
+ categorical = [spec for spec in specs if spec.kind == "categorical"]
378
+ combinations = _categorical_combinations(categorical, int(max_categorical_combinations))
379
+ model, encoded, y = _fit_surrogate(frame, specs, int(restarts), int(seed))
380
+
381
+ sign = 1.0 if goal == "maximize" else -1.0
382
+ y_center = float(np.mean(y))
383
+ y_scale = float(np.std(y, ddof=0)) or 1.0
384
+ best_scaled = float(np.max(sign * (y - y_center) / y_scale))
385
+ best_index = int(np.argmax(sign * (y - y_center) / y_scale))
386
+ best_observed = float(y[best_index])
387
+
388
+ def evaluate(settings: dict[str, Any]) -> dict[str, Any]:
389
+ encoded_settings = _encode_settings(settings, specs)
390
+ mean, standard_deviation, expected_improvement, probability_improvement, score = _acquisition_values(
391
+ model,
392
+ encoded_settings,
393
+ sign=sign,
394
+ y_center=y_center,
395
+ y_scale=y_scale,
396
+ best_scaled=best_scaled,
397
+ acquisition=acquisition,
398
+ xi=xi,
399
+ kappa=kappa,
400
+ )
401
+ return {
402
+ "settings": settings,
403
+ "predicted": float(mean[0]),
404
+ "predicted_sd": float(standard_deviation[0]),
405
+ "expected_improvement": float(expected_improvement[0] * y_scale),
406
+ "probability_improvement": float(probability_improvement[0]),
407
+ "score": float(score[0]),
408
+ }
409
+
410
+ candidates: list[dict[str, Any]] = []
411
+ rng = np.random.default_rng(int(seed))
412
+ random_count = max(8, min(64, 2048 // max(1, len(combinations))))
413
+ for combination_index, combination in enumerate(combinations):
414
+ if continuous:
415
+ def objective(vector: np.ndarray, levels_for_combination=combination) -> float:
416
+ settings = _settings_from_vector(continuous, categorical, vector, levels_for_combination)
417
+ return -evaluate(settings)["score"]
418
+
419
+ try:
420
+ outcome = differential_evolution(
421
+ objective,
422
+ [(0.0, 1.0)] * len(continuous),
423
+ seed=int(seed) + combination_index,
424
+ maxiter=100,
425
+ popsize=8,
426
+ tol=1e-6,
427
+ polish=True,
428
+ workers=1,
429
+ )
430
+ candidates.append(
431
+ evaluate(_settings_from_vector(continuous, categorical, outcome.x, combination))
432
+ )
433
+ except Exception:
434
+ pass
435
+ for _ in range(random_count):
436
+ vector = rng.random(len(continuous))
437
+ candidates.append(evaluate(_settings_from_vector(continuous, categorical, vector, combination)))
438
+ else:
439
+ candidates.append(evaluate(dict(combination)))
440
+
441
+ if not candidates:
442
+ raise ValueError("Bayesian optimization could not generate any candidates.")
443
+ selected = _select_candidates(candidates, proposals, specs)
444
+
445
+ factor_names = [spec.name for spec in specs]
446
+ best_settings = {
447
+ spec.name: (
448
+ float(frame.iloc[best_index][spec.name])
449
+ if spec.kind == "continuous"
450
+ else _label(frame.iloc[best_index][spec.name])
451
+ )
452
+ for spec in specs
453
+ }
454
+ observed_mean, observed_sd, _, _, _ = _acquisition_values(
455
+ model,
456
+ encoded,
457
+ sign=sign,
458
+ y_center=y_center,
459
+ y_scale=y_scale,
460
+ best_scaled=best_scaled,
461
+ acquisition=acquisition,
462
+ xi=xi,
463
+ kappa=kappa,
464
+ )
465
+ observed_frame = frame.loc[:, [*factor_names, response]].copy()
466
+ observed_frame["Predicted"] = observed_mean
467
+ observed_frame["Predicted SD"] = observed_sd
468
+ observed_frame["Residual"] = observed_frame[response].to_numpy(dtype=float) - observed_mean
469
+ observed_plot = observed_frame.rename(columns={response: "Observed"})
470
+
471
+ recommendation_rows: list[dict[str, Any]] = []
472
+ for index, candidate in enumerate(selected, start=1):
473
+ row: dict[str, Any] = {"Run": index}
474
+ for spec in specs:
475
+ value = candidate["settings"][spec.name]
476
+ row[spec.name] = float(value) if spec.kind == "continuous" else str(value)
477
+ projected = sign * (candidate["predicted"] - best_observed)
478
+ row["Predicted Response"] = candidate["predicted"]
479
+ row["Predicted SD"] = candidate["predicted_sd"]
480
+ row["Projected Improvement"] = projected
481
+ row["Expected Improvement"] = candidate["expected_improvement"]
482
+ row["Probability Improvement"] = candidate["probability_improvement"]
483
+ row["Acquisition"] = candidate["score"]
484
+ recommendation_rows.append(row)
485
+ recommendation_frame = pd.DataFrame(recommendation_rows)
486
+
487
+ best_row: dict[str, Any] = {"Response": response}
488
+ for spec in specs:
489
+ best_row[spec.name] = best_settings[spec.name]
490
+ best_row["Observed Response"] = best_observed
491
+ best_row["Predicted Response"] = float(observed_mean[best_index])
492
+ best_row["Predicted SD"] = float(observed_sd[best_index])
493
+
494
+ kernel = model.kernel_
495
+ model_rows = [
496
+ ("Observations", len(frame)),
497
+ ("Factors", len(specs)),
498
+ ("Continuous factors", len(continuous)),
499
+ ("Categorical factors", len(categorical)),
500
+ ("Goal", goal.title()),
501
+ ("Acquisition", acquisition.replace("_", " ").title()),
502
+ ("xi", xi),
503
+ ("kappa", kappa),
504
+ ("Kernel", str(kernel)),
505
+ ("Log marginal likelihood", float(model.log_marginal_likelihood_value_)),
506
+ ("Random seed", int(seed)),
507
+ ]
508
+ model_frame = pd.DataFrame(model_rows, columns=["Metric", "Value"])
509
+
510
+ result = AnalysisResult(
511
+ title=f"Bayesian Optimization: {response}",
512
+ analysis_type="bayesian_optimization",
513
+ params={
514
+ "response": response,
515
+ "factors": factor_names,
516
+ "factor_types": {spec.name: spec.kind for spec in specs},
517
+ "bounds": {spec.name: [float(spec.low), float(spec.high)] for spec in continuous},
518
+ "levels": {spec.name: list(spec.levels) for spec in categorical},
519
+ "goal": goal,
520
+ "acquisition": acquisition,
521
+ "proposals": proposals,
522
+ "xi": xi,
523
+ "kappa": kappa,
524
+ "restarts": int(restarts),
525
+ "max_categorical_combinations": int(max_categorical_combinations),
526
+ "seed": int(seed),
527
+ },
528
+ )
529
+ if len(recommendation_frame) < int(proposals):
530
+ result.notes = (
531
+ f"Requested {int(proposals)} distinct proposed runs, but only "
532
+ f"{len(recommendation_frame)} distinct settings were available."
533
+ )
534
+ result.add_table("Recommended Runs", recommendation_frame)
535
+ result.add_table("Current Best", pd.DataFrame([best_row]))
536
+ result.add_table("Surrogate Model", model_frame)
537
+ result.add_table("Observed Data", observed_frame.head(200))
538
+ result.add_plot(
539
+ "actual_predicted",
540
+ {"actual": "Observed", "predicted": "Predicted", "identity": True},
541
+ title="Observed vs Predicted",
542
+ data=observed_plot,
543
+ )
544
+ if len(recommendation_frame) > 1:
545
+ result.add_plot(
546
+ "bar",
547
+ {"x": "Run", "y": "Predicted Response"},
548
+ title="Recommended Runs",
549
+ data=recommendation_frame,
550
+ )
551
+ surface = _surface_frame(
552
+ model,
553
+ specs,
554
+ selected[0]["settings"],
555
+ sign=sign,
556
+ y_center=y_center,
557
+ y_scale=y_scale,
558
+ best_scaled=best_scaled,
559
+ acquisition=acquisition,
560
+ xi=xi,
561
+ kappa=kappa,
562
+ )
563
+ if surface is not None:
564
+ continuous_names = [spec.name for spec in continuous]
565
+ result.add_plot(
566
+ "contour",
567
+ {"x": continuous_names[0], "y": continuous_names[1], "z": "Predicted"},
568
+ title="Predicted Response Surface",
569
+ data=surface,
570
+ )
571
+ result.add_plot(
572
+ "contour",
573
+ {"x": continuous_names[0], "y": continuous_names[1], "z": "Acquisition"},
574
+ title="Acquisition Surface",
575
+ data=surface,
576
+ )
577
+ result.add_model("gp", model)
578
+ first = selected[0]
579
+ result.summary = (
580
+ f"Recommended next run predicts {first['predicted']:.6g} for {response} "
581
+ f"with expected improvement {first['expected_improvement']:.6g} and "
582
+ f"P(improvement) = {first['probability_improvement']:.3f}."
583
+ )
584
+ result.notes = (
585
+ "Bayesian optimization uses a Gaussian-process surrogate and an acquisition function. "
586
+ "Recommendations are restricted to the stated factor bounds and observed categorical levels. "
587
+ "Add the new run to the table and re-run the analysis to update the recommendation. "
588
+ "The surrogate is a local approximation and does not guarantee a global optimum."
589
+ )
590
+ return result