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,1714 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import math
5
+ from dataclasses import asdict, dataclass, field
6
+ from typing import Any, Sequence
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import statsmodels.api as sm
11
+ import statsmodels.formula.api as smf
12
+ from scipy import stats as _scipy_stats
13
+ from statsmodels.stats.anova import anova_lm
14
+
15
+ from statstudio.core.table import DataTable
16
+ from statstudio.stats.common import display_formula, p_stars
17
+ from statstudio.stats.profiler import ProfilerFactor, ProfilerGoal, ProfilerSession
18
+ from statstudio.stats.results import AnalysisResult
19
+
20
+ CRITERIA = ("D", "A", "I")
21
+ MAX_CANDIDATES = 12000
22
+ CONTINUOUS_LEVELS = (-1.0, -2.0 / 3.0, -1.0 / 3.0, 0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0)
23
+ MOMENT_LEVELS = tuple(float(value) for value in np.linspace(-1.0, 1.0, 11))
24
+
25
+
26
+ @dataclass
27
+ class CustomFactor:
28
+ name: str
29
+ role: str = "continuous"
30
+ low: float = -1.0
31
+ high: float = 1.0
32
+ levels: list[str] = field(default_factory=list)
33
+ units: str = ""
34
+
35
+ def __post_init__(self) -> None:
36
+ self.name = str(self.name).strip()
37
+ self.role = str(self.role).strip().lower()
38
+ if self.role in {"nominal", "categorical"}:
39
+ self.role = "categorical"
40
+ elif self.role in {"block", "blocking"}:
41
+ self.role = "blocking"
42
+ elif self.role != "continuous":
43
+ raise ValueError(f"Unknown factor role: {self.role}")
44
+ self.levels = [str(level).strip() for level in self.levels if str(level).strip()]
45
+ self.units = str(self.units or "")
46
+
47
+ @property
48
+ def center(self) -> float:
49
+ return (float(self.low) + float(self.high)) / 2
50
+
51
+ @property
52
+ def half_range(self) -> float:
53
+ return (float(self.high) - float(self.low)) / 2
54
+
55
+ def actual(self, coded: float) -> float:
56
+ return self.center + float(coded) * self.half_range
57
+
58
+ def coded(self, actual: float) -> float:
59
+ if self.half_range == 0:
60
+ return 0.0
61
+ return (float(actual) - self.center) / self.half_range
62
+
63
+ def to_dict(self) -> dict[str, Any]:
64
+ payload = asdict(self)
65
+ payload["center"] = self.center
66
+ payload["half_range"] = self.half_range
67
+ return payload
68
+
69
+ @classmethod
70
+ def from_dict(cls, payload: dict[str, Any]) -> "CustomFactor":
71
+ known = {item.name for item in cls.__dataclass_fields__.values()} # type: ignore[attr-defined]
72
+ return cls(**{key: value for key, value in payload.items() if key in known})
73
+
74
+
75
+ @dataclass
76
+ class ResponseSpec:
77
+ name: str
78
+ goal: str = "None"
79
+ lower: float | None = None
80
+ upper: float | None = None
81
+ target: float | None = None
82
+ importance: float = 1.0
83
+ units: str = ""
84
+
85
+ def __post_init__(self) -> None:
86
+ self.name = str(self.name).strip()
87
+ self.goal = str(self.goal or "None").strip().title()
88
+ self.importance = float(self.importance)
89
+ self.units = str(self.units or "")
90
+
91
+ def to_dict(self) -> dict[str, Any]:
92
+ return asdict(self)
93
+
94
+ @classmethod
95
+ def from_dict(cls, payload: dict[str, Any]) -> "ResponseSpec":
96
+ known = {item.name for item in cls.__dataclass_fields__.values()} # type: ignore[attr-defined]
97
+ return cls(**{key: value for key, value in payload.items() if key in known})
98
+
99
+
100
+ @dataclass
101
+ class LinearConstraint:
102
+ coefficients: dict[str, float] = field(default_factory=dict)
103
+ relation: str = "<="
104
+ bound: float = 0.0
105
+
106
+ def __post_init__(self) -> None:
107
+ self.coefficients = {str(name): float(value) for name, value in self.coefficients.items()}
108
+ self.relation = str(self.relation or "<=").strip()
109
+ if self.relation not in {"<=", ">=", "="}:
110
+ raise ValueError("Constraint relation must be <=, >=, or =.")
111
+ self.bound = float(self.bound)
112
+
113
+ def to_dict(self) -> dict[str, Any]:
114
+ return asdict(self)
115
+
116
+ @classmethod
117
+ def from_dict(cls, payload: dict[str, Any]) -> "LinearConstraint":
118
+ known = {item.name for item in cls.__dataclass_fields__.values()} # type: ignore[attr-defined]
119
+ return cls(**{key: value for key, value in payload.items() if key in known})
120
+
121
+
122
+ @dataclass
123
+ class CustomDesignSpec:
124
+ factors: list[CustomFactor] = field(default_factory=list)
125
+ responses: list[ResponseSpec] = field(default_factory=list)
126
+ terms: list[str] = field(default_factory=list)
127
+ criterion: str = "D"
128
+ runs: int = 12
129
+ center_points: int = 0
130
+ replicate_runs: int = 0
131
+ block_size: int = 0
132
+ randomize: bool = True
133
+ seed: int = 42
134
+ starts: int = 20
135
+ constraints: list[LinearConstraint] = field(default_factory=list)
136
+ name: str = ""
137
+
138
+ def __post_init__(self) -> None:
139
+ self.factors = [item if isinstance(item, CustomFactor) else CustomFactor.from_dict(item) for item in self.factors]
140
+ self.responses = [item if isinstance(item, ResponseSpec) else ResponseSpec.from_dict(item) for item in self.responses]
141
+ self.constraints = [item if isinstance(item, LinearConstraint) else LinearConstraint.from_dict(item) for item in self.constraints]
142
+ self.terms = [str(term).strip() for term in self.terms if str(term).strip()]
143
+ self.criterion = str(self.criterion or "D").strip().upper()
144
+ self.runs = int(self.runs)
145
+ self.center_points = int(self.center_points)
146
+ self.replicate_runs = int(self.replicate_runs)
147
+ self.block_size = int(self.block_size)
148
+ self.seed = int(self.seed)
149
+ self.starts = int(self.starts)
150
+
151
+ def to_dict(self) -> dict[str, Any]:
152
+ return {
153
+ "factors": [factor.to_dict() for factor in self.factors],
154
+ "responses": [response.to_dict() for response in self.responses],
155
+ "terms": list(self.terms),
156
+ "criterion": self.criterion,
157
+ "runs": self.runs,
158
+ "center_points": self.center_points,
159
+ "replicate_runs": self.replicate_runs,
160
+ "block_size": self.block_size,
161
+ "randomize": bool(self.randomize),
162
+ "seed": self.seed,
163
+ "starts": self.starts,
164
+ "constraints": [constraint.to_dict() for constraint in self.constraints],
165
+ "name": self.name,
166
+ }
167
+
168
+ @classmethod
169
+ def from_dict(cls, payload: dict[str, Any]) -> "CustomDesignSpec":
170
+ return cls(
171
+ factors=[CustomFactor.from_dict(item) for item in payload.get("factors", [])],
172
+ responses=[ResponseSpec.from_dict(item) for item in payload.get("responses", [])],
173
+ terms=list(payload.get("terms", [])),
174
+ criterion=payload.get("criterion", "D"),
175
+ runs=payload.get("runs", 12),
176
+ center_points=payload.get("center_points", 0),
177
+ replicate_runs=payload.get("replicate_runs", 0),
178
+ block_size=payload.get("block_size", 0),
179
+ randomize=bool(payload.get("randomize", True)),
180
+ seed=payload.get("seed", 42),
181
+ starts=payload.get("starts", 20),
182
+ constraints=[LinearConstraint.from_dict(item) for item in payload.get("constraints", [])],
183
+ name=payload.get("name", ""),
184
+ )
185
+
186
+
187
+ def default_terms(factors: Sequence[CustomFactor], include_interactions: bool = True, include_quadratic: bool = True) -> list[str]:
188
+ names = [factor.name for factor in factors if factor.role != "blocking"]
189
+ terms = list(names)
190
+ if include_interactions:
191
+ terms.extend(f"{first}*{second}" for first, second in itertools.combinations(names, 2))
192
+ if include_quadratic:
193
+ terms.extend(f"{factor.name}^2" for factor in factors if factor.role == "continuous")
194
+ return terms
195
+
196
+
197
+ def _parse_term(term: str) -> list[tuple[str, int]]:
198
+ text = str(term).strip()
199
+ if not text:
200
+ raise ValueError("Empty model term.")
201
+ parts = [part.strip() for part in text.split("*")]
202
+ parsed: list[tuple[str, int]] = []
203
+ for part in parts:
204
+ if not part:
205
+ raise ValueError(f"Invalid model term: {term}")
206
+ if part.endswith("^2"):
207
+ name = part[:-2].strip()
208
+ power = 2
209
+ else:
210
+ name = part
211
+ power = 1
212
+ if not name:
213
+ raise ValueError(f"Invalid model term: {term}")
214
+ parsed.append((name, power))
215
+ if any(power == 2 for _, power in parsed) and len(parsed) > 1:
216
+ raise ValueError(f"Quadratic terms cannot be combined with interactions: {term}")
217
+ if len({name for name, _ in parsed}) != len(parsed):
218
+ raise ValueError(f"Repeated factor in model term: {term}")
219
+ return parsed
220
+
221
+
222
+ def normalize_terms(factors: Sequence[CustomFactor], terms: Sequence[str] | None) -> list[str]:
223
+ factor_map = {factor.name: factor for factor in factors}
224
+ source = [str(term).strip() for term in (terms or []) if str(term).strip()]
225
+ if not source:
226
+ source = default_terms(factors)
227
+ normalized: list[str] = []
228
+ for term in source:
229
+ parsed = _parse_term(term)
230
+ for name, power in parsed:
231
+ factor = factor_map.get(name)
232
+ if factor is None:
233
+ raise ValueError(f"Unknown factor in model term {term!r}: {name}")
234
+ if factor.role == "blocking":
235
+ raise ValueError(f"Blocking factor {name!r} is added automatically.")
236
+ if power == 2 and factor.role != "continuous":
237
+ raise ValueError(f"Quadratic terms require a continuous factor: {term}")
238
+ canonical = "*".join(f"{name}^2" if power == 2 else name for name, power in parsed)
239
+ if canonical not in normalized:
240
+ normalized.append(canonical)
241
+ if not normalized:
242
+ raise ValueError("Select at least one model term.")
243
+ return normalized
244
+
245
+
246
+ def _validate_spec(spec: CustomDesignSpec) -> None:
247
+ if not spec.factors:
248
+ raise ValueError("Define at least one factor.")
249
+ names = [factor.name for factor in spec.factors]
250
+ if any(not name for name in names):
251
+ raise ValueError("Every factor needs a name.")
252
+ if len(set(names)) != len(names):
253
+ raise ValueError("Factor names must be unique.")
254
+ if any("*" in name or "^" in name or ":" in name for name in names):
255
+ raise ValueError("Factor names cannot contain *, ^, or :.")
256
+ continuous = [factor for factor in spec.factors if factor.role == "continuous"]
257
+ categorical = [factor for factor in spec.factors if factor.role == "categorical"]
258
+ blocking = [factor for factor in spec.factors if factor.role == "blocking"]
259
+ if len(blocking) > 1:
260
+ raise ValueError("Only one blocking factor is supported.")
261
+ if not continuous and not categorical:
262
+ raise ValueError("Define at least one continuous or categorical factor.")
263
+ for factor in continuous:
264
+ if not math.isfinite(float(factor.low)) or not math.isfinite(float(factor.high)):
265
+ raise ValueError(f"Factor {factor.name}: enter finite low and high levels.")
266
+ if float(factor.high) <= float(factor.low):
267
+ raise ValueError(f"Factor {factor.name}: high level must be greater than low level.")
268
+ for factor in categorical + blocking:
269
+ if len(factor.levels) < 2:
270
+ raise ValueError(f"Factor {factor.name}: define at least two levels.")
271
+ if len(set(factor.levels)) != len(factor.levels):
272
+ raise ValueError(f"Factor {factor.name}: levels must be unique.")
273
+ if not spec.responses:
274
+ raise ValueError("Define at least one response.")
275
+ response_names = [response.name for response in spec.responses]
276
+ if any(not name for name in response_names):
277
+ raise ValueError("Every response needs a name.")
278
+ if len(set(response_names)) != len(response_names):
279
+ raise ValueError("Response names must be unique.")
280
+ overlap = set(response_names) & set(names)
281
+ if overlap:
282
+ raise ValueError(f"Response names overlap factor names: {', '.join(sorted(overlap))}")
283
+ for response in spec.responses:
284
+ if response.goal not in {"None", "Maximize", "Minimize", "Match Target"}:
285
+ raise ValueError(f"Response {response.name}: unsupported goal {response.goal!r}.")
286
+ if response.importance <= 0:
287
+ raise ValueError(f"Response {response.name}: importance must be positive.")
288
+ if spec.criterion not in CRITERIA:
289
+ raise ValueError("Optimality criterion must be D, A, or I.")
290
+ if spec.runs < 1:
291
+ raise ValueError("Number of runs must be at least one.")
292
+ if spec.center_points < 0 or spec.replicate_runs < 0:
293
+ raise ValueError("Center and replicate runs cannot be negative.")
294
+ if spec.center_points and not continuous:
295
+ raise ValueError("Center points require at least one continuous factor.")
296
+ if spec.block_size < 0:
297
+ raise ValueError("Block size cannot be negative.")
298
+ if spec.starts < 1:
299
+ raise ValueError("Number of starts must be at least one.")
300
+ continuous_names = {factor.name for factor in continuous}
301
+ for constraint in spec.constraints:
302
+ unknown = set(constraint.coefficients) - continuous_names
303
+ if unknown:
304
+ raise ValueError(f"Linear constraints can only use continuous factors: {', '.join(sorted(unknown))}")
305
+ if not any(abs(value) > 0 for value in constraint.coefficients.values()):
306
+ raise ValueError("Each linear constraint needs at least one non-zero coefficient.")
307
+
308
+
309
+ def _factor_map(factors: Sequence[CustomFactor]) -> dict[str, CustomFactor]:
310
+ return {factor.name: factor for factor in factors}
311
+
312
+
313
+ def _basis_columns(factor: CustomFactor, rows: Sequence[dict[str, Any]]) -> list[tuple[str, np.ndarray]]:
314
+ if factor.role == "continuous":
315
+ values = np.array([factor.coded(row[factor.name]) for row in rows], dtype=float)
316
+ return [(factor.name, values)]
317
+ if factor.role == "categorical":
318
+ values = np.array([str(row[factor.name]) for row in rows], dtype=object)
319
+ reference = factor.levels[-1]
320
+ columns: list[tuple[str, np.ndarray]] = []
321
+ for level in factor.levels[:-1]:
322
+ coded = np.where(values == level, 1.0, np.where(values == reference, -1.0, 0.0))
323
+ columns.append((f"{factor.name}[{level}]", coded.astype(float)))
324
+ return columns
325
+ raise ValueError(f"Blocking factor {factor.name!r} is not a model term.")
326
+
327
+
328
+ def _term_column_count(factor: CustomFactor, power: int) -> int:
329
+ if power == 2:
330
+ return 1
331
+ if factor.role == "continuous":
332
+ return 1
333
+ if factor.role == "categorical":
334
+ return max(0, len(factor.levels) - 1)
335
+ return 0
336
+
337
+
338
+ def model_term_count(factors: Sequence[CustomFactor], terms: Sequence[str]) -> int:
339
+ factor_map = _factor_map(factors)
340
+ count = 1
341
+ for term in terms:
342
+ columns = 1
343
+ for name, power in _parse_term(term):
344
+ columns *= _term_column_count(factor_map[name], power)
345
+ count += columns
346
+ return count
347
+
348
+
349
+ def _block_spec(spec: CustomDesignSpec, total_runs: int) -> tuple[str | None, list[str]]:
350
+ blocking = [factor for factor in spec.factors if factor.role == "blocking"]
351
+ if blocking:
352
+ factor = blocking[0]
353
+ return factor.name, list(factor.levels)
354
+ if spec.block_size > 0:
355
+ count = max(2, int(math.ceil(total_runs / spec.block_size)))
356
+ return "Block", [f"Block {index}" for index in range(1, count + 1)]
357
+ return None, []
358
+
359
+
360
+ def _constraint_ok(row: dict[str, Any], constraints: Sequence[LinearConstraint]) -> bool:
361
+ for constraint in constraints:
362
+ value = sum(float(coefficient) * float(row.get(name, 0.0)) for name, coefficient in constraint.coefficients.items())
363
+ tolerance = 1e-9 * max(1.0, abs(constraint.bound))
364
+ if constraint.relation == "<=" and value > constraint.bound + tolerance:
365
+ return False
366
+ if constraint.relation == ">=" and value < constraint.bound - tolerance:
367
+ return False
368
+ if constraint.relation == "=" and abs(value - constraint.bound) > tolerance:
369
+ return False
370
+ return True
371
+
372
+
373
+ def _candidate_rows(
374
+ spec: CustomDesignSpec,
375
+ rng: np.random.Generator,
376
+ levels: Sequence[float] = CONTINUOUS_LEVELS,
377
+ ) -> list[dict[str, Any]]:
378
+ continuous = [factor for factor in spec.factors if factor.role == "continuous"]
379
+ categorical = [factor for factor in spec.factors if factor.role == "categorical"]
380
+ continuous_levels = [list(levels) for _ in continuous]
381
+ categorical_levels = [list(factor.levels) for factor in categorical]
382
+ lengths = [len(levels) for levels in continuous_levels + categorical_levels]
383
+ total = math.prod(lengths) if lengths else 1
384
+ combos: list[tuple[Any, ...]] = []
385
+ if total <= MAX_CANDIDATES:
386
+ combos = list(itertools.product(*(continuous_levels + categorical_levels)))
387
+ else:
388
+ seen: set[tuple[Any, ...]] = set()
389
+ samples = [
390
+ tuple(0.0 for _ in continuous) + tuple(levels[0] for levels in categorical_levels),
391
+ tuple(-1.0 for _ in continuous) + tuple(levels[-1] for levels in categorical_levels),
392
+ tuple(1.0 for _ in continuous) + tuple(levels[0] for levels in categorical_levels),
393
+ ]
394
+ for combo in samples:
395
+ seen.add(combo)
396
+ while len(seen) < MAX_CANDIDATES:
397
+ combo = tuple(
398
+ rng.choice(levels)
399
+ for levels in continuous_levels + categorical_levels
400
+ )
401
+ seen.add(combo)
402
+ combos = list(seen)
403
+ rows: list[dict[str, Any]] = []
404
+ seen_rows: set[tuple[Any, ...]] = set()
405
+ for combo in combos:
406
+ row: dict[str, Any] = {}
407
+ offset = 0
408
+ for factor in continuous:
409
+ row[factor.name] = factor.actual(float(combo[offset]))
410
+ offset += 1
411
+ for factor in categorical:
412
+ row[factor.name] = str(combo[offset])
413
+ offset += 1
414
+ key = tuple(row[factor.name] for factor in continuous + categorical)
415
+ if key in seen_rows or not _constraint_ok(row, spec.constraints):
416
+ continue
417
+ seen_rows.add(key)
418
+ rows.append(row)
419
+ if not rows:
420
+ raise ValueError("No candidate runs satisfy the factor constraints.")
421
+ return rows
422
+
423
+
424
+ def _model_matrix(
425
+ rows: Sequence[dict[str, Any]],
426
+ factors: Sequence[CustomFactor],
427
+ terms: Sequence[str],
428
+ *,
429
+ block_values: Sequence[Any] | None = None,
430
+ block_name: str | None = None,
431
+ block_levels: Sequence[str] | None = None,
432
+ ) -> tuple[np.ndarray, list[str]]:
433
+ if not rows:
434
+ raise ValueError("No design rows to evaluate.")
435
+ factor_map = _factor_map(factors)
436
+ columns: list[np.ndarray] = [np.ones(len(rows), dtype=float)]
437
+ labels: list[str] = ["Intercept"]
438
+ for term in terms:
439
+ term_columns: list[tuple[str, np.ndarray]] = [("", np.ones(len(rows), dtype=float))]
440
+ for name, power in _parse_term(term):
441
+ factor = factor_map[name]
442
+ if power == 2:
443
+ values = np.array([factor.coded(row[name]) ** 2 for row in rows], dtype=float)
444
+ term_columns = [
445
+ (f"{label}*{name}^2" if label else f"{name}^2", current * values)
446
+ for label, current in term_columns
447
+ ]
448
+ else:
449
+ basis = _basis_columns(factor, rows)
450
+ expanded = []
451
+ for left_label, left_values in term_columns:
452
+ for right_label, right_values in basis:
453
+ label = f"{left_label}*{right_label}" if left_label else right_label
454
+ expanded.append((label, left_values * right_values))
455
+ term_columns = expanded
456
+ for label, values in term_columns:
457
+ labels.append(label)
458
+ columns.append(values)
459
+ if block_values is not None and block_name:
460
+ levels = list(block_levels or [])
461
+ if not levels:
462
+ levels = list(dict.fromkeys(str(value) for value in block_values))
463
+ values = np.array([str(value) for value in block_values], dtype=object)
464
+ for level in levels[1:]:
465
+ labels.append(f"{block_name}[{level}]")
466
+ columns.append((values == level).astype(float))
467
+ return np.column_stack(columns), labels
468
+
469
+
470
+ def _moment_matrix(
471
+ candidates: Sequence[dict[str, Any]],
472
+ factors: Sequence[CustomFactor],
473
+ terms: Sequence[str],
474
+ *,
475
+ block_name: str | None = None,
476
+ block_levels: Sequence[str] | None = None,
477
+ ) -> np.ndarray:
478
+ if block_name and block_levels:
479
+ expanded: list[dict[str, Any]] = []
480
+ block_values: list[str] = []
481
+ for row in candidates:
482
+ for level in block_levels:
483
+ payload = dict(row)
484
+ payload[block_name] = level
485
+ expanded.append(payload)
486
+ block_values.append(level)
487
+ matrix, _ = _model_matrix(
488
+ expanded,
489
+ factors,
490
+ terms,
491
+ block_values=block_values,
492
+ block_name=block_name,
493
+ block_levels=block_levels,
494
+ )
495
+ else:
496
+ matrix, _ = _model_matrix(candidates, factors, terms)
497
+ return matrix.T @ matrix / max(1, len(matrix))
498
+
499
+
500
+ def _score(matrix: np.ndarray, criterion: str, moment: np.ndarray | None = None) -> float:
501
+ if matrix.size == 0 or matrix.shape[0] < 2:
502
+ return -np.inf
503
+ gram = matrix.T @ matrix
504
+ try:
505
+ sign, logdet = np.linalg.slogdet(gram)
506
+ except Exception:
507
+ return -np.inf
508
+ if sign <= 0 or not np.isfinite(logdet):
509
+ return -np.inf
510
+ try:
511
+ factor = np.linalg.cholesky(gram)
512
+ except np.linalg.LinAlgError:
513
+ return -np.inf
514
+ diagonal = np.diag(factor)
515
+ if diagonal.min() <= 1e-9 * max(1.0, diagonal.max()):
516
+ return -np.inf
517
+ if criterion == "D":
518
+ return float(logdet)
519
+ try:
520
+ if int(np.linalg.matrix_rank(gram)) < gram.shape[0]:
521
+ return -np.inf
522
+ inverse = np.linalg.inv(gram)
523
+ except Exception:
524
+ return -np.inf
525
+ if criterion == "A":
526
+ return -float(np.trace(inverse))
527
+ if moment is None:
528
+ return -np.inf
529
+ return -float(np.trace(moment @ inverse))
530
+
531
+
532
+ def _design_matrix(
533
+ design: Sequence[dict[str, Any]],
534
+ factors: Sequence[CustomFactor],
535
+ terms: Sequence[str],
536
+ block_name: str | None,
537
+ block_levels: Sequence[str],
538
+ ) -> tuple[np.ndarray, list[str]]:
539
+ block_values = [row.get(block_name) for row in design] if block_name else None
540
+ return _model_matrix(
541
+ design,
542
+ factors,
543
+ terms,
544
+ block_values=block_values,
545
+ block_name=block_name,
546
+ block_levels=block_levels,
547
+ )
548
+
549
+
550
+ def _score_design(
551
+ design: Sequence[dict[str, Any]],
552
+ factors: Sequence[CustomFactor],
553
+ terms: Sequence[str],
554
+ criterion: str,
555
+ moment: np.ndarray,
556
+ block_name: str | None,
557
+ block_levels: Sequence[str],
558
+ ) -> float:
559
+ matrix, _ = _design_matrix(design, factors, terms, block_name, block_levels)
560
+ return _score(matrix, criterion, moment)
561
+
562
+
563
+ def _balanced_block_labels(count: int, levels: Sequence[str], rng: np.random.Generator) -> list[str]:
564
+ labels = [levels[index % len(levels)] for index in range(count)]
565
+ rng.shuffle(labels)
566
+ return labels
567
+
568
+
569
+ def _assign_blocks(
570
+ design: Sequence[dict[str, Any]],
571
+ block_name: str | None,
572
+ block_levels: Sequence[str],
573
+ rng: np.random.Generator,
574
+ ) -> list[dict[str, Any]]:
575
+ result = [dict(row) for row in design]
576
+ if not block_name:
577
+ return result
578
+ labels = _balanced_block_labels(len(result), block_levels, rng)
579
+ for row, label in zip(result, labels):
580
+ row[block_name] = label
581
+ return result
582
+
583
+
584
+ def _evaluate_rows(
585
+ rows: Sequence[dict[str, Any]],
586
+ factors: Sequence[CustomFactor],
587
+ terms: Sequence[str],
588
+ criterion: str,
589
+ candidates: Sequence[dict[str, Any]] | None = None,
590
+ *,
591
+ block_values: Sequence[Any] | None = None,
592
+ block_name: str | None = None,
593
+ block_levels: Sequence[str] | None = None,
594
+ ) -> dict[str, Any]:
595
+ full_matrix, labels = _model_matrix(
596
+ rows,
597
+ factors,
598
+ terms,
599
+ block_values=block_values,
600
+ block_name=block_name,
601
+ block_levels=block_levels,
602
+ )
603
+ core_matrix, _ = _model_matrix(rows, factors, terms)
604
+ candidate_rows = list(candidates or rows)
605
+ moment = _moment_matrix(
606
+ candidate_rows,
607
+ factors,
608
+ terms,
609
+ block_name=block_name,
610
+ block_levels=block_levels,
611
+ )
612
+ gram = full_matrix.T @ full_matrix
613
+ rank = int(np.linalg.matrix_rank(full_matrix))
614
+ p = full_matrix.shape[1]
615
+ n = full_matrix.shape[0]
616
+ try:
617
+ sign, logdet = np.linalg.slogdet(gram)
618
+ except Exception:
619
+ sign, logdet = 0.0, float("-inf")
620
+ d_efficiency = float(100.0 * np.exp(logdet / p) / n) if sign > 0 and np.isfinite(logdet) else float("nan")
621
+ try:
622
+ condition = float(np.linalg.cond(gram))
623
+ if rank < p or not np.isfinite(condition):
624
+ raise np.linalg.LinAlgError("rank deficient")
625
+ inverse = np.linalg.inv(gram)
626
+ a_criterion = float(np.trace(inverse))
627
+ i_criterion = float(np.trace(moment @ inverse))
628
+ except Exception:
629
+ a_criterion = float("inf")
630
+ i_criterion = float("inf")
631
+ condition = float("inf")
632
+ model_columns = full_matrix[:, 1:] if full_matrix.shape[1] > 1 else full_matrix
633
+ if model_columns.shape[1] > 1 and n > 1:
634
+ correlation = np.corrcoef(model_columns, rowvar=False)
635
+ correlation = np.nan_to_num(np.abs(correlation), nan=0.0)
636
+ np.fill_diagonal(correlation, 0.0)
637
+ max_correlation = float(correlation.max()) if correlation.size else float("nan")
638
+ else:
639
+ max_correlation = 0.0
640
+ return {
641
+ "runs": n,
642
+ "model_columns": p,
643
+ "treatment_columns": core_matrix.shape[1],
644
+ "design_columns": full_matrix.shape[1],
645
+ "rank": rank,
646
+ "criterion": criterion,
647
+ "d_efficiency": d_efficiency,
648
+ "a_criterion": a_criterion,
649
+ "i_criterion": i_criterion,
650
+ "condition_number": condition,
651
+ "max_correlation": max_correlation,
652
+ "column_labels": labels,
653
+ }
654
+
655
+
656
+ def _select_rows(
657
+ candidates: Sequence[dict[str, Any]],
658
+ count: int,
659
+ rng: np.random.Generator,
660
+ ) -> list[dict[str, Any]]:
661
+ indices = list(range(len(candidates)))
662
+ rng.shuffle(indices)
663
+ if count <= len(candidates):
664
+ return [dict(candidates[index]) for index in indices[:count]]
665
+ selected = [dict(candidates[index]) for index in indices]
666
+ while len(selected) < count:
667
+ selected.append(dict(candidates[int(rng.integers(0, len(candidates)))]))
668
+ return selected
669
+
670
+
671
+ def _coordinate_exchange(
672
+ initial: list[dict[str, Any]],
673
+ candidates: Sequence[dict[str, Any]],
674
+ factors: Sequence[CustomFactor],
675
+ terms: Sequence[str],
676
+ criterion: str,
677
+ moment: np.ndarray,
678
+ starts: int,
679
+ rng: np.random.Generator,
680
+ block_name: str | None = None,
681
+ block_levels: Sequence[str] = (),
682
+ ) -> list[dict[str, Any]]:
683
+ best_design: list[dict[str, Any]] | None = None
684
+ best_score = -np.inf
685
+ for start_index in range(max(1, starts)):
686
+ if start_index == 0:
687
+ design = [dict(row) for row in initial]
688
+ else:
689
+ design = _select_rows(candidates, len(initial), rng)
690
+ design = _assign_blocks(design, block_name, block_levels, rng)
691
+ score = _score_design(design, factors, terms, criterion, moment, block_name, block_levels)
692
+ improved = True
693
+ passes = 0
694
+ while improved and passes < 30:
695
+ passes += 1
696
+ improved = False
697
+ for row_index in range(len(design)):
698
+ current = design[row_index]
699
+ for candidate in candidates:
700
+ if all(current.get(name) == candidate.get(name) for name in candidate):
701
+ continue
702
+ replacement = dict(candidate)
703
+ if block_name:
704
+ replacement[block_name] = current.get(block_name)
705
+ trial = list(design)
706
+ trial[row_index] = replacement
707
+ trial_score = _score_design(trial, factors, terms, criterion, moment, block_name, block_levels)
708
+ if trial_score > score + 1e-12:
709
+ design = trial
710
+ score = trial_score
711
+ current = replacement
712
+ improved = True
713
+ if score > best_score:
714
+ best_score = score
715
+ best_design = [dict(row) for row in design]
716
+ if best_design is None:
717
+ raise ValueError("Could not construct a custom design.")
718
+ return best_design
719
+
720
+
721
+ def _refine_design(
722
+ design: list[dict[str, Any]],
723
+ candidates: Sequence[dict[str, Any]],
724
+ factors: Sequence[CustomFactor],
725
+ terms: Sequence[str],
726
+ criterion: str,
727
+ moment: np.ndarray,
728
+ fixed_indices: set[int],
729
+ block_name: str | None = None,
730
+ block_levels: Sequence[str] = (),
731
+ ) -> list[dict[str, Any]]:
732
+ result = [dict(row) for row in design]
733
+ score = _score_design(result, factors, terms, criterion, moment, block_name, block_levels)
734
+ improved = True
735
+ passes = 0
736
+ while improved and passes < 30:
737
+ passes += 1
738
+ improved = False
739
+ for row_index in range(len(result)):
740
+ if row_index in fixed_indices:
741
+ continue
742
+ current = result[row_index]
743
+ for candidate in candidates:
744
+ if all(current.get(name) == candidate.get(name) for name in candidate):
745
+ continue
746
+ replacement = dict(candidate)
747
+ if block_name:
748
+ replacement[block_name] = current.get(block_name)
749
+ trial = list(result)
750
+ trial[row_index] = replacement
751
+ trial_score = _score_design(trial, factors, terms, criterion, moment, block_name, block_levels)
752
+ if trial_score > score + 1e-12:
753
+ result = trial
754
+ score = trial_score
755
+ current = replacement
756
+ improved = True
757
+ return result
758
+
759
+
760
+ def _center_candidates(rows: Sequence[dict[str, Any]], factors: Sequence[CustomFactor]) -> list[dict[str, Any]]:
761
+ continuous = [factor for factor in factors if factor.role == "continuous"]
762
+ centers = []
763
+ for row in rows:
764
+ if all(abs(factor.coded(row[factor.name])) <= 1e-9 for factor in continuous):
765
+ centers.append(dict(row))
766
+ return centers
767
+
768
+
769
+ def _add_centers(
770
+ design: list[dict[str, Any]],
771
+ candidates: Sequence[dict[str, Any]],
772
+ factors: Sequence[CustomFactor],
773
+ terms: Sequence[str],
774
+ count: int,
775
+ criterion: str,
776
+ moment: np.ndarray,
777
+ rng: np.random.Generator,
778
+ block_name: str | None = None,
779
+ block_levels: Sequence[str] = (),
780
+ ) -> list[dict[str, Any]]:
781
+ if count <= 0:
782
+ return design
783
+ centers = _center_candidates(candidates, factors)
784
+ if not centers:
785
+ raise ValueError("No center runs satisfy the factor constraints.")
786
+ result = list(design)
787
+ for _ in range(count):
788
+ counts = {level: sum(row.get(block_name) == level for row in result) for level in block_levels}
789
+ allowed = [level for level in block_levels if counts[level] == min(counts.values())] if block_name else [None]
790
+ best_row = centers[0]
791
+ best_score = -np.inf
792
+ for center in centers:
793
+ for level in allowed:
794
+ payload = dict(center)
795
+ if block_name:
796
+ payload[block_name] = level
797
+ trial = result + [payload]
798
+ score = _score_design(trial, factors, terms, criterion, moment, block_name, block_levels)
799
+ if score > best_score:
800
+ best_score = score
801
+ best_row = payload
802
+ result.append(dict(best_row))
803
+ return result
804
+
805
+
806
+ def _add_replicates(
807
+ design: list[dict[str, Any]],
808
+ factors: Sequence[CustomFactor],
809
+ terms: Sequence[str],
810
+ count: int,
811
+ criterion: str,
812
+ moment: np.ndarray,
813
+ block_name: str | None = None,
814
+ block_levels: Sequence[str] = (),
815
+ ) -> list[dict[str, Any]]:
816
+ result = list(design)
817
+ for _ in range(max(0, count)):
818
+ best_index = 0
819
+ best_score = -np.inf
820
+ for index, row in enumerate(result):
821
+ trial = result + [dict(row)]
822
+ score = _score_design(trial, factors, terms, criterion, moment, block_name, block_levels)
823
+ if score > best_score:
824
+ best_score = score
825
+ best_index = index
826
+ result.append(dict(result[best_index]))
827
+ return result
828
+
829
+
830
+ def build_custom_design(spec: CustomDesignSpec) -> DataTable:
831
+ _validate_spec(spec)
832
+ factors = list(spec.factors)
833
+ terms = normalize_terms(factors, spec.terms)
834
+ model_columns = model_term_count(factors, terms)
835
+ total_requested = spec.runs + spec.center_points + spec.replicate_runs
836
+ planned_block_name, planned_block_levels = _block_spec(spec, total_requested)
837
+ block_columns = max(0, len(planned_block_levels) - 1) if planned_block_name else 0
838
+ if planned_block_name and len(planned_block_levels) > total_requested:
839
+ raise ValueError("The blocking factor has more levels than the requested total runs.")
840
+ if planned_block_name and spec.runs < len(planned_block_levels):
841
+ raise ValueError("The optimal design needs at least one run in every block.")
842
+ if spec.runs < model_columns:
843
+ raise ValueError(f"At least {model_columns} optimal runs are needed for the selected model terms.")
844
+ if total_requested < model_columns + block_columns:
845
+ raise ValueError(
846
+ f"At least {model_columns + block_columns} total runs are needed for the model and blocks; "
847
+ f"{total_requested} were requested."
848
+ )
849
+ rng = np.random.default_rng(spec.seed)
850
+ candidates = _candidate_rows(spec, rng)
851
+ moment_candidates = _candidate_rows(spec, rng, MOMENT_LEVELS)
852
+ block_name, block_levels = _block_spec(spec, total_requested)
853
+ moment = _moment_matrix(
854
+ moment_candidates,
855
+ factors,
856
+ terms,
857
+ block_name=block_name,
858
+ block_levels=block_levels,
859
+ )
860
+ initial = _select_rows(candidates, spec.runs, rng)
861
+ design = _coordinate_exchange(
862
+ initial,
863
+ candidates,
864
+ factors,
865
+ terms,
866
+ spec.criterion,
867
+ moment,
868
+ spec.starts,
869
+ rng,
870
+ block_name,
871
+ block_levels,
872
+ )
873
+ point_types = ["Optimal"] * len(design)
874
+ base_count = len(design)
875
+ design = _add_centers(
876
+ design,
877
+ candidates,
878
+ factors,
879
+ terms,
880
+ spec.center_points,
881
+ spec.criterion,
882
+ moment,
883
+ rng,
884
+ block_name,
885
+ block_levels,
886
+ )
887
+ point_types.extend(["Center"] * spec.center_points)
888
+ if spec.center_points:
889
+ design = _refine_design(
890
+ design,
891
+ candidates,
892
+ factors,
893
+ terms,
894
+ spec.criterion,
895
+ moment,
896
+ set(range(base_count, len(design))),
897
+ block_name,
898
+ block_levels,
899
+ )
900
+ design = _add_replicates(
901
+ design,
902
+ factors,
903
+ terms,
904
+ spec.replicate_runs,
905
+ spec.criterion,
906
+ moment,
907
+ block_name,
908
+ block_levels,
909
+ )
910
+ point_types.extend(["Replicate"] * spec.replicate_runs)
911
+ total_runs = len(design)
912
+ block_values = [row.get(block_name) for row in design] if block_name else None
913
+ order = list(range(total_runs))
914
+ if spec.randomize:
915
+ rng.shuffle(order)
916
+ design = [design[index] for index in order]
917
+ point_types = [point_types[index] for index in order]
918
+ if block_values is not None:
919
+ block_values = [block_values[index] for index in order]
920
+ factor_columns = [factor.name for factor in factors if factor.role != "blocking"]
921
+ replicate_columns = list(factor_columns)
922
+ if block_name and block_name not in factor_columns:
923
+ factor_columns.append(block_name)
924
+ response_names = [response.name for response in spec.responses]
925
+ occurrence: dict[tuple[Any, ...], int] = {}
926
+ rows: list[dict[str, Any]] = []
927
+ for index, row in enumerate(design, start=1):
928
+ key = tuple(row.get(name) for name in replicate_columns)
929
+ occurrence[key] = occurrence.get(key, 0) + 1
930
+ payload: dict[str, Any] = {
931
+ "Std Order": order[index - 1] + 1,
932
+ "Run Order": index,
933
+ "Replicate": occurrence[key],
934
+ "Point Type": point_types[index - 1],
935
+ }
936
+ if block_name:
937
+ payload[block_name] = row.get(block_name)
938
+ for factor in factors:
939
+ if factor.role != "blocking":
940
+ payload[factor.name] = row.get(factor.name)
941
+ for name in response_names:
942
+ payload[name] = np.nan
943
+ rows.append(payload)
944
+ columns = ["Std Order", "Run Order", "Replicate", "Point Type"]
945
+ if block_name:
946
+ columns.append(block_name)
947
+ columns.extend(factor.name for factor in factors if factor.role != "blocking")
948
+ columns.extend(response_names)
949
+ frame = pd.DataFrame(rows).loc[:, columns]
950
+ evaluation = _evaluate_rows(
951
+ design,
952
+ factors,
953
+ terms,
954
+ spec.criterion,
955
+ moment_candidates,
956
+ block_values=block_values,
957
+ block_name=block_name,
958
+ block_levels=block_levels,
959
+ )
960
+ design_payload = {
961
+ "design_type": "Custom",
962
+ "factors": [factor.to_dict() for factor in factors],
963
+ "responses": [response.to_dict() for response in spec.responses],
964
+ "terms": terms,
965
+ "criterion": spec.criterion,
966
+ "runs": spec.runs,
967
+ "center_points": spec.center_points,
968
+ "replicate_runs": spec.replicate_runs,
969
+ "block_size": spec.block_size,
970
+ "block_name": block_name,
971
+ "block_levels": block_levels,
972
+ "randomize": spec.randomize,
973
+ "seed": spec.seed,
974
+ "starts": spec.starts,
975
+ "constraints": [constraint.to_dict() for constraint in spec.constraints],
976
+ "evaluation": evaluation,
977
+ "spec": spec.to_dict(),
978
+ }
979
+ table = DataTable(
980
+ frame,
981
+ name=spec.name or "Custom Design",
982
+ source="Custom DOE",
983
+ metadata={"design": design_payload},
984
+ )
985
+ for factor in factors:
986
+ if factor.name in table.specs:
987
+ table.specs[factor.name].units = factor.units
988
+ table.specs[factor.name].modeling_type = "continuous" if factor.role == "continuous" else "nominal"
989
+ for response in spec.responses:
990
+ if response.name in table.specs:
991
+ table.specs[response.name].modeling_type = "continuous"
992
+ table.specs[response.name].units = response.units
993
+ return table
994
+
995
+
996
+ def _spec_from_table(table: DataTable) -> CustomDesignSpec:
997
+ info = table.metadata.get("design") or {}
998
+ if info.get("design_type") != "Custom":
999
+ raise ValueError("This table has no custom design metadata.")
1000
+ payload = info.get("spec")
1001
+ if isinstance(payload, dict):
1002
+ return CustomDesignSpec.from_dict(payload)
1003
+ return CustomDesignSpec(
1004
+ factors=[CustomFactor.from_dict(item) for item in info.get("factors", [])],
1005
+ responses=[ResponseSpec.from_dict(item) for item in info.get("responses", [])],
1006
+ terms=list(info.get("terms", [])),
1007
+ criterion=info.get("criterion", "D"),
1008
+ runs=info.get("runs", len(table)),
1009
+ center_points=info.get("center_points", 0),
1010
+ replicate_runs=info.get("replicate_runs", 0),
1011
+ block_size=info.get("block_size", 0),
1012
+ randomize=info.get("randomize", True),
1013
+ seed=info.get("seed", 42),
1014
+ starts=info.get("starts", 20),
1015
+ constraints=[LinearConstraint.from_dict(item) for item in info.get("constraints", [])],
1016
+ name=table.name,
1017
+ )
1018
+
1019
+
1020
+ def _table_rows(table: DataTable, spec: CustomDesignSpec) -> list[dict[str, Any]]:
1021
+ frame = table.data
1022
+ rows: list[dict[str, Any]] = []
1023
+ for record in frame.to_dict("records"):
1024
+ row: dict[str, Any] = {}
1025
+ valid = True
1026
+ for factor in spec.factors:
1027
+ if factor.role == "blocking":
1028
+ continue
1029
+ value = record.get(factor.name)
1030
+ if pd.isna(value):
1031
+ valid = False
1032
+ break
1033
+ row[factor.name] = float(value) if factor.role == "continuous" else str(value)
1034
+ if valid:
1035
+ rows.append(row)
1036
+ if not rows:
1037
+ raise ValueError("No complete design rows.")
1038
+ return rows
1039
+
1040
+
1041
+ def _table_block_values(table: DataTable, spec: CustomDesignSpec) -> tuple[str | None, list[str], list[str]]:
1042
+ info = table.metadata.get("design") or {}
1043
+ block_name = info.get("block_name")
1044
+ if not block_name or block_name not in table.columns:
1045
+ return None, [], []
1046
+ levels = list(info.get("block_levels") or [])
1047
+ values = [str(value) for value in table.data[block_name].fillna("").tolist()]
1048
+ if not levels:
1049
+ levels = list(dict.fromkeys(values))
1050
+ return str(block_name), levels, values
1051
+
1052
+
1053
+ def evaluate_custom_design(table: DataTable) -> dict[str, Any]:
1054
+ spec = _spec_from_table(table)
1055
+ terms = normalize_terms(spec.factors, spec.terms)
1056
+ rows = _table_rows(table, spec)
1057
+ block_name, block_levels, block_values = _table_block_values(table, spec)
1058
+ rng = np.random.default_rng(spec.seed)
1059
+ candidates = _candidate_rows(spec, rng, MOMENT_LEVELS)
1060
+ return _evaluate_rows(
1061
+ rows,
1062
+ spec.factors,
1063
+ terms,
1064
+ spec.criterion,
1065
+ candidates,
1066
+ block_values=block_values if block_name else None,
1067
+ block_name=block_name,
1068
+ block_levels=block_levels,
1069
+ )
1070
+
1071
+
1072
+ def _evaluation_frame(evaluation: dict[str, Any]) -> pd.DataFrame:
1073
+ return pd.DataFrame(
1074
+ [
1075
+ ("Design", "Custom"),
1076
+ ("Criterion", evaluation["criterion"]),
1077
+ ("Runs", evaluation["runs"]),
1078
+ ("Treatment model columns", evaluation.get("treatment_columns", evaluation["model_columns"])),
1079
+ ("Design matrix columns", evaluation.get("design_columns", evaluation["model_columns"])),
1080
+ ("Rank", evaluation["rank"]),
1081
+ ("D-efficiency (%)", evaluation["d_efficiency"]),
1082
+ ("A-criterion (trace)", evaluation["a_criterion"]),
1083
+ ("I-criterion (avg prediction variance)", evaluation["i_criterion"]),
1084
+ ("Max |correlation|", evaluation["max_correlation"]),
1085
+ ("Condition number", evaluation["condition_number"]),
1086
+ ],
1087
+ columns=["Metric", "Value"],
1088
+ )
1089
+
1090
+
1091
+ def design_diagnostics(table: DataTable) -> AnalysisResult:
1092
+ evaluation = evaluate_custom_design(table)
1093
+ spec = _spec_from_table(table)
1094
+ terms = normalize_terms(spec.factors, spec.terms)
1095
+ rows = _table_rows(table, spec)
1096
+ block_name, block_levels, block_values = _table_block_values(table, spec)
1097
+ matrix, labels = _model_matrix(
1098
+ rows,
1099
+ spec.factors,
1100
+ terms,
1101
+ block_values=block_values if block_name else None,
1102
+ block_name=block_name,
1103
+ block_levels=block_levels,
1104
+ )
1105
+ result = AnalysisResult(
1106
+ title="Custom Design Evaluation",
1107
+ analysis_type="doe_diagnostics",
1108
+ params={"design_type": "Custom", "criterion": spec.criterion},
1109
+ source_table=table.name,
1110
+ )
1111
+ result.add_table("Design Summary", _evaluation_frame(evaluation))
1112
+ coefficient_matrix = pd.DataFrame(matrix, columns=labels)
1113
+ correlation = coefficient_matrix.corr().abs().fillna(0.0)
1114
+ np.fill_diagonal(correlation.values, 0.0)
1115
+ result.add_table("Term Correlation", correlation.reset_index().rename(columns={"index": "Term"}))
1116
+ result.add_plot(
1117
+ "correlation_heatmap",
1118
+ {"columns": labels, "matrix": correlation.to_dict()},
1119
+ title="Term Correlation",
1120
+ data=coefficient_matrix,
1121
+ )
1122
+ result.summary = (
1123
+ f"Custom {spec.criterion}-optimal design with {evaluation['runs']} runs, "
1124
+ f"D-efficiency {evaluation['d_efficiency']:.2f}%, max |correlation| {evaluation['max_correlation']:.3f}."
1125
+ )
1126
+ return result
1127
+
1128
+
1129
+ def _lack_of_fit(
1130
+ data: pd.DataFrame,
1131
+ factors: Sequence[CustomFactor],
1132
+ response: str,
1133
+ model,
1134
+ block_name: str | None,
1135
+ ) -> pd.DataFrame | None:
1136
+ columns = [factor.name for factor in factors if factor.role != "blocking" and factor.name in data.columns]
1137
+ if block_name and block_name in data.columns:
1138
+ columns.append(block_name)
1139
+ if not columns:
1140
+ return None
1141
+ groups = data.groupby(columns, dropna=False)[response]
1142
+ sizes = groups.size()
1143
+ pure_df = int((sizes - 1).clip(lower=0).sum())
1144
+ if pure_df <= 0:
1145
+ return None
1146
+ pure_sse = float(sum(((chunk - chunk.mean()) ** 2).sum() for _, chunk in groups))
1147
+ lack_df = int(model.df_resid - pure_df)
1148
+ if lack_df <= 0:
1149
+ return None
1150
+ lack_sse = max(0.0, float(model.ssr) - pure_sse)
1151
+ ms_lack = lack_sse / lack_df
1152
+ ms_pure = pure_sse / pure_df
1153
+ f_value = ms_lack / ms_pure if ms_pure else np.nan
1154
+ p_value = float(_scipy_stats.f.sf(f_value, lack_df, pure_df)) if np.isfinite(f_value) else np.nan
1155
+ return pd.DataFrame(
1156
+ [
1157
+ {"Source": "Lack of Fit", "SS": lack_sse, "DF": lack_df, "MS": ms_lack, "F": f_value, "p-value": p_value},
1158
+ {"Source": "Pure Error", "SS": pure_sse, "DF": pure_df, "MS": ms_pure, "F": np.nan, "p-value": np.nan},
1159
+ ]
1160
+ )
1161
+
1162
+
1163
+ def _custom_anova(data: pd.DataFrame, response: str, matrix: np.ndarray, labels: Sequence[str]) -> pd.DataFrame | None:
1164
+ if matrix.shape[1] <= 1:
1165
+ return None
1166
+ safe = [f"x{index}" for index in range(1, matrix.shape[1])]
1167
+ frame = pd.DataFrame(matrix[:, 1:], columns=safe, index=data.index)
1168
+ frame["__response__"] = pd.to_numeric(data[response], errors="coerce")
1169
+ formula = "__response__ ~ " + " + ".join(safe)
1170
+ try:
1171
+ model = smf.ols(formula, data=frame).fit()
1172
+ table = anova_lm(model, typ=2).reset_index().rename(columns={"index": "Source"})
1173
+ except Exception:
1174
+ return None
1175
+ mapping = dict(zip(safe, labels[1:]))
1176
+ table["Source"] = table["Source"].map(lambda value: display_formula(mapping.get(str(value), str(value))))
1177
+ return table
1178
+
1179
+
1180
+ def _profiler_goal(response_spec: ResponseSpec | None) -> ProfilerGoal | None:
1181
+ if response_spec is None:
1182
+ return None
1183
+ goals = {
1184
+ "Maximize": "maximize",
1185
+ "Minimize": "minimize",
1186
+ "Match Target": "target",
1187
+ "None": "maximize",
1188
+ }
1189
+ return ProfilerGoal(
1190
+ goals.get(response_spec.goal, "maximize"),
1191
+ response_spec.lower,
1192
+ response_spec.upper,
1193
+ response_spec.target,
1194
+ )
1195
+
1196
+
1197
+ def _profiler_session(
1198
+ model,
1199
+ factors: Sequence[CustomFactor],
1200
+ terms: Sequence[str],
1201
+ *,
1202
+ block_name: str | None,
1203
+ block_levels: Sequence[str],
1204
+ response: str,
1205
+ points: int = 9,
1206
+ response_spec: ResponseSpec | None = None,
1207
+ ) -> ProfilerSession:
1208
+ profiler_factors: list[ProfilerFactor] = []
1209
+ for factor in factors:
1210
+ if factor.role == "continuous":
1211
+ profiler_factors.append(
1212
+ ProfilerFactor(
1213
+ factor.name,
1214
+ "continuous",
1215
+ low=factor.low,
1216
+ high=factor.high,
1217
+ current=factor.center,
1218
+ initial=factor.center,
1219
+ units=factor.units,
1220
+ )
1221
+ )
1222
+ elif factor.role == "categorical" and factor.levels:
1223
+ profiler_factors.append(
1224
+ ProfilerFactor(
1225
+ factor.name,
1226
+ "categorical",
1227
+ levels=list(factor.levels),
1228
+ current=factor.levels[0],
1229
+ initial=factor.levels[0],
1230
+ units=factor.units,
1231
+ )
1232
+ )
1233
+
1234
+ def predict(settings: dict[str, Any]) -> float:
1235
+ row: dict[str, Any] = {}
1236
+ for item in factors:
1237
+ if item.role == "continuous":
1238
+ row[item.name] = float(settings.get(item.name, item.center))
1239
+ elif item.role == "categorical":
1240
+ row[item.name] = str(settings.get(item.name, item.levels[0] if item.levels else ""))
1241
+ block_values = [block_levels[0]] if block_name and block_levels else None
1242
+ matrix, _ = _model_matrix(
1243
+ [row],
1244
+ factors,
1245
+ terms,
1246
+ block_values=block_values,
1247
+ block_name=block_name,
1248
+ block_levels=block_levels,
1249
+ )
1250
+ return float(model.predict(matrix)[0])
1251
+
1252
+ return ProfilerSession(
1253
+ response=response,
1254
+ factors=profiler_factors,
1255
+ predict=predict,
1256
+ response_label=response,
1257
+ points=points,
1258
+ response_goal=_profiler_goal(response_spec),
1259
+ )
1260
+
1261
+
1262
+ def _profiler_frame(
1263
+ model,
1264
+ factors: Sequence[CustomFactor],
1265
+ terms: Sequence[str],
1266
+ *,
1267
+ block_name: str | None,
1268
+ block_levels: Sequence[str],
1269
+ points: int = 9,
1270
+ ) -> pd.DataFrame:
1271
+ def base_row() -> dict[str, Any]:
1272
+ row: dict[str, Any] = {}
1273
+ for item in factors:
1274
+ if item.role == "continuous":
1275
+ row[item.name] = item.center
1276
+ elif item.role == "categorical":
1277
+ row[item.name] = item.levels[0] if item.levels else ""
1278
+ return row
1279
+
1280
+ def predict(row: dict[str, Any]) -> float:
1281
+ block_values = [block_levels[0]] if block_name and block_levels else None
1282
+ matrix, _ = _model_matrix(
1283
+ [row],
1284
+ factors,
1285
+ terms,
1286
+ block_values=block_values,
1287
+ block_name=block_name,
1288
+ block_levels=block_levels,
1289
+ )
1290
+ return float(model.predict(matrix)[0])
1291
+
1292
+ rows: list[dict[str, Any]] = []
1293
+ for factor in factors:
1294
+ if factor.role == "continuous":
1295
+ for value in np.linspace(-1.0, 1.0, max(3, points)):
1296
+ row = base_row()
1297
+ actual = factor.actual(float(value))
1298
+ row[factor.name] = actual
1299
+ rows.append(
1300
+ {
1301
+ "Factor": factor.name,
1302
+ "Level": actual,
1303
+ "Coded": float(value),
1304
+ "Level Label": f"{actual:.6g}",
1305
+ "Categorical": False,
1306
+ "Predicted": predict(row),
1307
+ }
1308
+ )
1309
+ elif factor.role == "categorical":
1310
+ for index, level in enumerate(factor.levels):
1311
+ row = base_row()
1312
+ row[factor.name] = level
1313
+ rows.append(
1314
+ {
1315
+ "Factor": factor.name,
1316
+ "Level": float(index),
1317
+ "Coded": np.nan,
1318
+ "Level Label": level,
1319
+ "Categorical": True,
1320
+ "Predicted": predict(row),
1321
+ }
1322
+ )
1323
+ return pd.DataFrame(rows)
1324
+
1325
+
1326
+ def _block_mean_shift(model, block_name: str | None, block_levels: Sequence[str], block_values: Sequence[str]) -> float:
1327
+ if not block_name or len(block_levels) < 2 or not block_values:
1328
+ return 0.0
1329
+ values = pd.Series(list(block_values), dtype=object)
1330
+ sizes = values.value_counts()
1331
+ total = int(sizes.sum())
1332
+ if total <= 0:
1333
+ return 0.0
1334
+ params = pd.Series(model.params)
1335
+ contribution = pd.Series(0.0, index=sizes.index, dtype=float)
1336
+ for level in block_levels[1:]:
1337
+ key = f"{block_name}[{level}]"
1338
+ if key in params.index:
1339
+ contribution.loc[level] = float(params[key])
1340
+ return float((contribution * sizes).sum() / total)
1341
+
1342
+
1343
+ def _adjust_block_intercept(model, block_name: str | None, block_levels: Sequence[str], block_values: Sequence[str]) -> float:
1344
+ shift = _block_mean_shift(model, block_name, block_levels, block_values)
1345
+ if shift == 0.0:
1346
+ return 0.0
1347
+ model._custom_raw_summary = {
1348
+ "params": model.params.copy(),
1349
+ "bse": model.bse.copy(),
1350
+ "tvalues": model.tvalues.copy(),
1351
+ "pvalues": model.pvalues.copy(),
1352
+ "fittedvalues": np.asarray(model.fittedvalues).copy(),
1353
+ "resid": np.asarray(model.resid).copy(),
1354
+ }
1355
+ model._custom_block_mean_shift = shift
1356
+ result_params = model._results.params
1357
+ names = list(model.model.exog_names)
1358
+ if "Intercept" in names:
1359
+ index = names.index("Intercept")
1360
+ if hasattr(result_params, "loc"):
1361
+ result_params.loc["Intercept"] += shift
1362
+ else:
1363
+ result_params[index] += shift
1364
+ return shift
1365
+
1366
+
1367
+ def _fit_custom_model(
1368
+ table: DataTable,
1369
+ response: str,
1370
+ terms: Sequence[str] | None = None,
1371
+ ):
1372
+ spec = _spec_from_table(table)
1373
+ model_terms = normalize_terms(spec.factors, terms or spec.terms)
1374
+ frame = table.analysis_df()
1375
+ if response not in frame.columns:
1376
+ raise KeyError(response)
1377
+ required = [factor.name for factor in spec.factors if factor.role != "blocking"] + [response]
1378
+ data = frame.loc[:, required].copy()
1379
+ for factor in spec.factors:
1380
+ if factor.role == "continuous" and factor.name in data.columns:
1381
+ data[factor.name] = pd.to_numeric(data[factor.name], errors="coerce")
1382
+ elif factor.role == "categorical" and factor.name in data.columns:
1383
+ data[factor.name] = data[factor.name].astype(str)
1384
+ data[response] = pd.to_numeric(data[response], errors="coerce")
1385
+ data = data.dropna()
1386
+ if len(data) < 2:
1387
+ raise ValueError("Enter at least two response values before fitting the design model.")
1388
+ rows = data.to_dict("records")
1389
+ block_name, block_levels, block_values = _table_block_values(table, spec)
1390
+ if block_name:
1391
+ block_lookup = dict(zip(table.data.index, block_values))
1392
+ block_values = [block_lookup[index] for index in data.index]
1393
+ matrix, labels = _model_matrix(
1394
+ rows,
1395
+ spec.factors,
1396
+ model_terms,
1397
+ block_values=block_values if block_name else None,
1398
+ block_name=block_name,
1399
+ block_levels=block_levels,
1400
+ )
1401
+ if matrix.shape[0] <= matrix.shape[1]:
1402
+ raise ValueError("Not enough response rows to fit the custom design model.")
1403
+ exog = pd.DataFrame(matrix, columns=labels, index=data.index)
1404
+ model = sm.OLS(data[response], exog).fit()
1405
+ if block_name:
1406
+ _adjust_block_intercept(model, block_name, block_levels, block_values)
1407
+ return spec, model_terms, data, matrix, labels, model, block_name, block_levels, block_values
1408
+
1409
+
1410
+ def analyze_custom_design(
1411
+ table: DataTable,
1412
+ response: str,
1413
+ terms: Sequence[str] | None = None,
1414
+ ) -> AnalysisResult:
1415
+ spec, model_terms, data, matrix, labels, model, block_name, block_levels, block_values = _fit_custom_model(
1416
+ table,
1417
+ response,
1418
+ terms,
1419
+ )
1420
+ y = data[response]
1421
+ raw = getattr(model, "_custom_raw_summary", None)
1422
+ bse = raw["bse"] if raw else model.bse
1423
+ tvalues = raw["tvalues"] if raw else model.tvalues
1424
+ pvalues = raw["pvalues"] if raw else model.pvalues
1425
+ coefficients = pd.DataFrame(
1426
+ {
1427
+ "Term": [display_formula(name) for name in model.params.index],
1428
+ "Estimate": model.params.to_numpy(),
1429
+ "Std Error": bse.to_numpy(),
1430
+ "t": tvalues.to_numpy(),
1431
+ "p-value": pvalues.to_numpy(),
1432
+ "Significance": [p_stars(value) for value in pvalues.to_numpy()],
1433
+ }
1434
+ )
1435
+ effects = coefficients.loc[coefficients["Term"] != "Intercept"].copy()
1436
+ effects["Abs t"] = effects["t"].abs()
1437
+ effects = effects.sort_values("Abs t", ascending=False).reset_index(drop=True)
1438
+ evaluation = evaluate_custom_design(table)
1439
+ result = AnalysisResult(
1440
+ title=f"Custom DOE Analysis: {response}",
1441
+ analysis_type="custom_doe_analysis",
1442
+ params={"response": response, "terms": model_terms},
1443
+ source_table=table.name,
1444
+ )
1445
+ result.add_table("Model Coefficients", coefficients)
1446
+ result.add_table("Effects (sorted by |t|)", effects)
1447
+ result.add_table(
1448
+ "Model Metrics",
1449
+ pd.DataFrame(
1450
+ [
1451
+ ("Design", "Custom"),
1452
+ ("Criterion", spec.criterion),
1453
+ ("Response", response),
1454
+ ("Runs used", len(data)),
1455
+ ("Model terms", len(model_terms)),
1456
+ ("R-squared", model.rsquared),
1457
+ ("Adjusted R-squared", model.rsquared_adj),
1458
+ ("F statistic", model.fvalue),
1459
+ ("Model p-value", model.f_pvalue),
1460
+ ("RMSE", float(np.sqrt(model.mse_resid))),
1461
+ ("AIC", model.aic),
1462
+ ("BIC", model.bic),
1463
+ ],
1464
+ columns=["Metric", "Value"],
1465
+ ),
1466
+ )
1467
+ result.add_table("Design Evaluation", _evaluation_frame(evaluation))
1468
+ anova = _custom_anova(data, response, matrix, labels)
1469
+ if anova is not None:
1470
+ result.add_table("ANOVA", anova)
1471
+ lack_of_fit = _lack_of_fit(data, spec.factors, response, model, block_name)
1472
+ if lack_of_fit is not None:
1473
+ result.add_table("Lack of Fit", lack_of_fit)
1474
+ raw = getattr(model, "_custom_raw_summary", None)
1475
+ fittedvalues = raw["fittedvalues"] if raw else model.fittedvalues.to_numpy()
1476
+ residuals = raw["resid"] if raw else model.resid.to_numpy()
1477
+ prediction = pd.DataFrame({"Actual": y, "Predicted": fittedvalues, "Residual": residuals}, index=data.index)
1478
+ result.add_plot("doe_pareto", {}, title="Pareto Plot of Standardized Effects", data=effects)
1479
+ result.add_plot(
1480
+ "actual_predicted",
1481
+ {"actual": "Actual", "predicted": "Predicted"},
1482
+ title="Actual vs Predicted",
1483
+ data=prediction,
1484
+ )
1485
+ result.add_plot(
1486
+ "residual_fitted",
1487
+ {"fitted": "Predicted", "residual": "Residual"},
1488
+ title="Residuals vs Fitted",
1489
+ data=prediction,
1490
+ )
1491
+ profiler = _profiler_frame(
1492
+ model,
1493
+ spec.factors,
1494
+ model_terms,
1495
+ block_name=block_name,
1496
+ block_levels=block_levels,
1497
+ )
1498
+ if not profiler.empty:
1499
+ result.add_table("Prediction Profiler", profiler)
1500
+ result.add_plot(
1501
+ "profiler",
1502
+ {
1503
+ "factor": "Factor",
1504
+ "level": "Level",
1505
+ "label": "Level Label",
1506
+ "categorical": "Categorical",
1507
+ "predicted": "Predicted",
1508
+ "x_label": "Actual Level",
1509
+ },
1510
+ title="Prediction Profiler",
1511
+ data=profiler,
1512
+ )
1513
+ result.add_model("custom_design_model", model)
1514
+ result.add_model("custom_design_spec", spec)
1515
+ response_spec = next((item for item in spec.responses if item.name == response), None)
1516
+ try:
1517
+ result.profiler_session = _profiler_session(
1518
+ model,
1519
+ spec.factors,
1520
+ model_terms,
1521
+ block_name=block_name,
1522
+ block_levels=block_levels,
1523
+ response=response,
1524
+ response_spec=response_spec,
1525
+ )
1526
+ except Exception:
1527
+ result.profiler_session = None
1528
+ result.summary = (
1529
+ f"{model.rsquared:.4f} R-squared, adjusted R² = {model.rsquared_adj:.4f}, "
1530
+ f"model p = {model.f_pvalue:.4g}, N = {len(data)}. "
1531
+ f"Design D-efficiency {evaluation['d_efficiency']:.2f}%."
1532
+ )
1533
+ return result
1534
+
1535
+
1536
+ def prediction_profiler(
1537
+ table: DataTable,
1538
+ response: str,
1539
+ order: int = 2,
1540
+ points: int = 9,
1541
+ ) -> AnalysisResult:
1542
+ del order
1543
+ spec, model_terms, data, matrix, labels, model, block_name, block_levels, block_values = _fit_custom_model(
1544
+ table,
1545
+ response,
1546
+ )
1547
+ profiler = _profiler_frame(
1548
+ model,
1549
+ spec.factors,
1550
+ model_terms,
1551
+ block_name=block_name,
1552
+ block_levels=block_levels,
1553
+ points=points,
1554
+ )
1555
+ result = AnalysisResult(
1556
+ title=f"Prediction Profiler: {response}",
1557
+ analysis_type="custom_prediction_profiler",
1558
+ params={"response": response, "points": points},
1559
+ source_table=table.name,
1560
+ )
1561
+ result.add_table("Prediction Profiler", profiler)
1562
+ result.add_plot(
1563
+ "profiler",
1564
+ {
1565
+ "factor": "Factor",
1566
+ "level": "Level",
1567
+ "label": "Level Label",
1568
+ "categorical": "Categorical",
1569
+ "predicted": "Predicted",
1570
+ "x_label": "Actual Level",
1571
+ },
1572
+ title="Prediction Profiler",
1573
+ data=profiler,
1574
+ )
1575
+ result.add_model("custom_design_model", model)
1576
+ response_spec = next((item for item in spec.responses if item.name == response), None)
1577
+ try:
1578
+ result.profiler_session = _profiler_session(
1579
+ model,
1580
+ spec.factors,
1581
+ model_terms,
1582
+ block_name=block_name,
1583
+ block_levels=block_levels,
1584
+ response=response,
1585
+ points=points,
1586
+ response_spec=response_spec,
1587
+ )
1588
+ except Exception:
1589
+ result.profiler_session = None
1590
+ result.summary = (
1591
+ f"Prediction profiler for {response} across {len(spec.factors)} factor(s), "
1592
+ "holding other factors at their center or first categorical level."
1593
+ )
1594
+ return result
1595
+
1596
+
1597
+ def simulate_response(
1598
+ table: DataTable,
1599
+ response: str,
1600
+ order: int = 2,
1601
+ simulations: int = 1000,
1602
+ noise_sd: float | None = None,
1603
+ distribution: str = "normal",
1604
+ lsl: float | None = None,
1605
+ usl: float | None = None,
1606
+ seed: int = 42,
1607
+ ) -> AnalysisResult:
1608
+ del order
1609
+ if simulations < 10:
1610
+ raise ValueError("At least ten simulated runs are required.")
1611
+ spec, model_terms, data, matrix, labels, model, block_name, block_levels, block_values = _fit_custom_model(
1612
+ table,
1613
+ response,
1614
+ )
1615
+ rng = np.random.default_rng(seed)
1616
+ settings: list[dict[str, Any]] = []
1617
+ attempts = 0
1618
+ max_attempts = max(1000, simulations * 200)
1619
+ while len(settings) < simulations and attempts < max_attempts:
1620
+ attempts += 1
1621
+ row: dict[str, Any] = {}
1622
+ for factor in spec.factors:
1623
+ if factor.role == "continuous":
1624
+ row[factor.name] = float(rng.uniform(factor.low, factor.high))
1625
+ elif factor.role == "categorical":
1626
+ row[factor.name] = str(rng.choice(factor.levels))
1627
+ if _constraint_ok(row, spec.constraints):
1628
+ settings.append(row)
1629
+ if len(settings) < simulations:
1630
+ raise ValueError(
1631
+ "Could not generate enough simulated runs that satisfy the factor constraints. "
1632
+ "Relax the constraints or reduce the number of simulations."
1633
+ )
1634
+ simulated_blocks = [str(rng.choice(block_levels)) for _ in range(simulations)] if block_name else None
1635
+ simulated_matrix, _ = _model_matrix(
1636
+ settings,
1637
+ spec.factors,
1638
+ model_terms,
1639
+ block_values=simulated_blocks,
1640
+ block_name=block_name,
1641
+ block_levels=block_levels,
1642
+ )
1643
+ systematic = np.asarray(model.predict(simulated_matrix), dtype=float)
1644
+ sd = float(noise_sd if noise_sd is not None else np.sqrt(max(model.mse_resid, 0.0)))
1645
+ distribution = distribution.lower()
1646
+ if distribution in {"normal", "gaussian"}:
1647
+ noise = rng.normal(0.0, sd, simulations) if sd > 0 else np.zeros(simulations)
1648
+ elif distribution in {"lognormal", "lognormal_noise"}:
1649
+ if sd > 0:
1650
+ sigma_log = math.sqrt(math.log1p(sd ** 2))
1651
+ noise = rng.lognormal(mean=-0.5 * sigma_log ** 2, sigma=sigma_log, size=simulations) - 1.0
1652
+ else:
1653
+ noise = np.zeros(simulations)
1654
+ elif distribution in {"uniform", "uniform_noise"}:
1655
+ half = sd * np.sqrt(3)
1656
+ noise = rng.uniform(-half, half, simulations)
1657
+ else:
1658
+ noise = rng.normal(0.0, sd, simulations) if sd > 0 else np.zeros(simulations)
1659
+ simulated = systematic + noise
1660
+ frame = pd.DataFrame(settings)
1661
+ if block_name:
1662
+ frame[block_name] = simulated_blocks
1663
+ frame["Systematic"] = systematic
1664
+ frame["Noise"] = noise
1665
+ frame["Simulated"] = simulated
1666
+ if lsl is not None and usl is not None:
1667
+ frame["Within Spec"] = (frame["Simulated"] >= lsl) & (frame["Simulated"] <= usl)
1668
+ yield_rate = float(frame["Within Spec"].mean())
1669
+ else:
1670
+ yield_rate = np.nan
1671
+ result = AnalysisResult(
1672
+ title=f"Response Simulation: {response}",
1673
+ analysis_type="custom_response_simulation",
1674
+ params={
1675
+ "response": response,
1676
+ "simulations": simulations,
1677
+ "noise_sd": noise_sd,
1678
+ "distribution": distribution,
1679
+ "lsl": lsl,
1680
+ "usl": usl,
1681
+ "seed": seed,
1682
+ },
1683
+ source_table=table.name,
1684
+ )
1685
+ result.add_table(
1686
+ "Simulation Summary",
1687
+ pd.DataFrame(
1688
+ [
1689
+ {
1690
+ "Simulations": simulations,
1691
+ "Noise Std Dev": sd,
1692
+ "Noise Distribution": distribution,
1693
+ "Mean": float(np.mean(simulated)),
1694
+ "Std Dev": float(np.std(simulated, ddof=1)),
1695
+ "P05": float(np.quantile(simulated, 0.05)),
1696
+ "P50": float(np.quantile(simulated, 0.50)),
1697
+ "P95": float(np.quantile(simulated, 0.95)),
1698
+ "Within Spec": yield_rate,
1699
+ "Expected PPM": (1 - yield_rate) * 1e6 if np.isfinite(yield_rate) else np.nan,
1700
+ }
1701
+ ]
1702
+ ),
1703
+ )
1704
+ result.add_table("Simulated Runs (first 200)", frame.head(200))
1705
+ result.add_plot("histogram", {"column": "Simulated", "lsl": lsl, "usl": usl}, title=f"Simulated {response}", data=frame)
1706
+ if lsl is not None or usl is not None:
1707
+ result.add_plot("capability", {"column": "Simulated", "lsl": lsl, "usl": usl}, title=f"Simulated Capability: {response}", data=frame)
1708
+ result.add_model("custom_design_model", model)
1709
+ result.summary = (
1710
+ f"{simulations} simulations from the fitted custom model; mean {np.mean(simulated):.6g}, "
1711
+ f"std dev {np.std(simulated, ddof=1):.6g}"
1712
+ + (f", within-spec {yield_rate:.2%}." if np.isfinite(yield_rate) else ".")
1713
+ )
1714
+ return result