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,1070 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import itertools
5
+ from dataclasses import asdict, dataclass
6
+ from typing import Any, Sequence
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import statsmodels.formula.api as smf
11
+ from scipy import stats as _scipy_stats
12
+ from scipy.optimize import minimize
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, ProfilerSession
18
+ from statstudio.stats.results import AnalysisResult
19
+
20
+
21
+ @dataclass
22
+ class Factor:
23
+ name: str
24
+ low: float = -1.0
25
+ high: float = 1.0
26
+ units: str = ""
27
+
28
+ @property
29
+ def center(self) -> float:
30
+ return (self.low + self.high) / 2
31
+
32
+ @property
33
+ def half_range(self) -> float:
34
+ return (self.high - self.low) / 2
35
+
36
+ def actual(self, coded: float) -> float:
37
+ return self.center + coded * self.half_range
38
+
39
+ def coded(self, actual: float) -> float:
40
+ if self.half_range == 0:
41
+ return 0.0
42
+ return (actual - self.center) / self.half_range
43
+
44
+ def to_dict(self) -> dict[str, Any]:
45
+ payload = asdict(self)
46
+ payload["center"] = self.center
47
+ payload["half_range"] = self.half_range
48
+ return payload
49
+
50
+
51
+ def _q(name: str) -> str:
52
+ return f'Q("{name}")'
53
+
54
+
55
+ def _randomize(rows: list[dict[str, Any]], seed: int | None) -> list[dict[str, Any]]:
56
+ rng = np.random.default_rng(seed)
57
+ order = rng.permutation(len(rows))
58
+ return [rows[int(i)] for i in order]
59
+
60
+
61
+ def _build_design_table(
62
+ coded_rows: list[dict[str, Any]],
63
+ factors: Sequence[Factor],
64
+ design_type: str,
65
+ *,
66
+ point_types: list[str] | None = None,
67
+ generators: list[str] | None = None,
68
+ resolution: str = "",
69
+ replicate: int = 1,
70
+ center_points: int = 0,
71
+ randomize: bool = True,
72
+ seed: int | None = 42,
73
+ notes: str = "",
74
+ ) -> DataTable:
75
+ expanded: list[dict[str, Any]] = []
76
+ for replicate_index in range(1, replicate + 1):
77
+ for row_index, row in enumerate(coded_rows):
78
+ item = {
79
+ "Std Order": len(expanded) + 1,
80
+ "Replicate": replicate_index,
81
+ "Point Type": (point_types[row_index] if point_types else "Factorial"),
82
+ }
83
+ for factor in factors:
84
+ item[factor.name] = factor.actual(float(row[factor.name]))
85
+ expanded.append(item)
86
+ if randomize:
87
+ expanded = _randomize(expanded, seed)
88
+ for run_index, row in enumerate(expanded, start=1):
89
+ row["Run Order"] = run_index
90
+ columns = ["Std Order", "Run Order", "Replicate", "Point Type"] + [f.name for f in factors]
91
+ frame = pd.DataFrame(expanded).loc[:, columns]
92
+ table = DataTable(
93
+ frame,
94
+ name=f"{design_type} Design",
95
+ source=f"DOE {design_type}",
96
+ metadata={
97
+ "design": {
98
+ "design_type": design_type,
99
+ "factors": [f.to_dict() for f in factors],
100
+ "generators": generators or [],
101
+ "resolution": resolution,
102
+ "replicate": replicate,
103
+ "center_points": center_points,
104
+ "randomize": randomize,
105
+ "seed": seed,
106
+ "notes": notes,
107
+ }
108
+ },
109
+ )
110
+ for factor in factors:
111
+ if factor.name in table.specs:
112
+ table.specs[factor.name].units = factor.units
113
+ table.specs[factor.name].modeling_type = "continuous"
114
+ return table
115
+
116
+
117
+ def full_factorial(
118
+ factors: Sequence[Factor],
119
+ replicates: int = 1,
120
+ center_points: int = 0,
121
+ randomize: bool = True,
122
+ seed: int | None = 42,
123
+ ) -> DataTable:
124
+ if not factors:
125
+ raise ValueError("At least one factor is required.")
126
+ if len(factors) > 10:
127
+ raise ValueError("Full factorial designs are limited to 10 factors.")
128
+ rows = []
129
+ point_types = []
130
+ for values in itertools.product([-1.0, 1.0], repeat=len(factors)):
131
+ rows.append({factor.name: value for factor, value in zip(factors, values)})
132
+ point_types.append("Factorial")
133
+ for _ in range(center_points):
134
+ rows.append({factor.name: 0.0 for factor in factors})
135
+ point_types.append("Center")
136
+ return _build_design_table(
137
+ rows,
138
+ factors,
139
+ "Full Factorial",
140
+ point_types=point_types,
141
+ replicate=replicates,
142
+ center_points=center_points,
143
+ randomize=randomize,
144
+ seed=seed,
145
+ notes=f"2^{len(factors)} full factorial.",
146
+ )
147
+
148
+
149
+ def _default_generators(k: int, p: int, resolution: str) -> list[list[int]]:
150
+ base = k - p
151
+ if p == 0:
152
+ return []
153
+ if p == 1:
154
+ return [list(range(base))]
155
+ wanted = {"III": 2, "IV": 3, "V": 4, "VI": 5, "VII": 6}.get(resolution.upper(), 3)
156
+ wanted = min(wanted, base)
157
+ combinations = [list(combo) for combo in itertools.combinations(range(base), wanted)]
158
+ if len(combinations) < p:
159
+ all_combinations = []
160
+ for size in range(max(2, wanted), base + 1):
161
+ all_combinations.extend(list(c) for c in itertools.combinations(range(base), size))
162
+ combinations = all_combinations
163
+ if len(combinations) < p:
164
+ raise ValueError("Not enough factor combinations to construct this fractional design.")
165
+ return combinations[:p]
166
+
167
+
168
+ def _generator_expression(factors: Sequence[Factor], extra_index: int, generator: list[int]) -> str:
169
+ base = "*".join(factors[i].name or f"F{i + 1}" for i in generator)
170
+ return f"{factors[extra_index].name or 'F' + str(extra_index + 1)}={base}"
171
+
172
+
173
+ _FRACTIONAL_CATALOG: dict[tuple[int, str], list[list[int]]] = {
174
+ (3, "III"): [[0, 1]],
175
+ (4, "IV"): [[0, 1, 2]],
176
+ (5, "III"): [[0, 1], [0, 2]],
177
+ (6, "IV"): [[0, 1, 2], [0, 1, 3]],
178
+ (7, "IV"): [[0, 1, 2], [0, 1, 3], [0, 2, 3]],
179
+ (8, "V"): [[0, 1, 2, 3], [0, 1, 4, 5]],
180
+ }
181
+
182
+
183
+ def _design_resolution(base: int, generators: Sequence[Sequence[int]], fallback: str) -> str:
184
+ words = [frozenset([base + offset, *generator]) for offset, generator in enumerate(generators)]
185
+ relations: set[frozenset[int]] = set()
186
+ for count in range(1, len(words) + 1):
187
+ for combination in itertools.combinations(words, count):
188
+ tally: dict[int, int] = {}
189
+ for word in combination:
190
+ for index in word:
191
+ tally[index] = tally.get(index, 0) + 1
192
+ relation = frozenset(index for index, occurrences in tally.items() if occurrences % 2)
193
+ if relation:
194
+ relations.add(relation)
195
+ word_lengths = [len(relation) for relation in relations]
196
+ minimum_length = min(word_lengths) if word_lengths else 0
197
+ return {
198
+ 2: "II",
199
+ 3: "III",
200
+ 4: "IV",
201
+ 5: "V",
202
+ 6: "VI",
203
+ 7: "VII",
204
+ 8: "VIII",
205
+ }.get(minimum_length, fallback)
206
+
207
+
208
+ def _resolution_rank(value: str) -> int:
209
+ return {"II": 2, "III": 3, "IV": 4, "V": 5, "VI": 6, "VII": 7, "VIII": 8}.get(value.upper(), 0)
210
+
211
+
212
+ def fractional_factorial(
213
+ factors: Sequence[Factor],
214
+ resolution: str = "Auto",
215
+ replicates: int = 1,
216
+ center_points: int = 0,
217
+ randomize: bool = True,
218
+ seed: int | None = 42,
219
+ generators: list[list[int]] | None = None,
220
+ ) -> DataTable:
221
+ k = len(factors)
222
+ if k < 3:
223
+ raise ValueError("Fractional factorial designs need at least three factors.")
224
+ if k > 10:
225
+ raise ValueError("Fractional factorial designs are limited to 10 factors.")
226
+ requested = resolution.upper()
227
+ if requested == "AUTO":
228
+ requested = "III" if k < 4 else "IV"
229
+ if requested not in {"III", "IV", "V", "VI", "VII", "VIII"}:
230
+ raise ValueError("Resolution must be Auto, III, IV, V, VI, VII, or VIII.")
231
+ explicit_generators = generators is not None
232
+ p = len(generators) if generators is not None else 0
233
+ if generators is None:
234
+ catalog = _FRACTIONAL_CATALOG.get((k, requested))
235
+ if catalog is not None:
236
+ generators = catalog
237
+ p = len(generators)
238
+ else:
239
+ best = None
240
+ for candidate_p in range(k - 2, 0, -1):
241
+ try:
242
+ candidate = _default_generators(k, candidate_p, requested)
243
+ except ValueError:
244
+ continue
245
+ candidate_base = k - candidate_p
246
+ actual = _design_resolution(candidate_base, candidate, requested)
247
+ if _resolution_rank(actual) >= _resolution_rank(requested):
248
+ best = (candidate_p, candidate)
249
+ break
250
+ if best is None:
251
+ raise ValueError(f"No fractional factorial for {k} factors at resolution {requested}.")
252
+ p, generators = best
253
+ else:
254
+ p = len(generators)
255
+ base = k - p
256
+ if base < 2:
257
+ raise ValueError("Too many generators for the number of factors.")
258
+ if len(generators) != p:
259
+ raise ValueError("Generator count does not match the number of added factors.")
260
+ coded_rows = []
261
+ point_types = []
262
+ for base_values in itertools.product([-1.0, 1.0], repeat=base):
263
+ row = {factors[i].name: value for i, value in enumerate(base_values)}
264
+ for offset, generator in enumerate(generators):
265
+ value = 1.0
266
+ for index in generator:
267
+ value *= base_values[index]
268
+ row[factors[base + offset].name] = value
269
+ coded_rows.append(row)
270
+ point_types.append("Fractional")
271
+ for _ in range(center_points):
272
+ coded_rows.append({factor.name: 0.0 for factor in factors})
273
+ point_types.append("Center")
274
+ expressions = [
275
+ _generator_expression(factors, base + offset, generator)
276
+ for offset, generator in enumerate(generators)
277
+ ]
278
+ actual_resolution = _design_resolution(base, generators, requested)
279
+ if not explicit_generators and _resolution_rank(actual_resolution) < _resolution_rank(requested):
280
+ raise ValueError(
281
+ f"Requested resolution {requested} is not achievable with these generators; "
282
+ f"realized resolution is {actual_resolution}."
283
+ )
284
+ return _build_design_table(
285
+ coded_rows,
286
+ factors,
287
+ "Fractional Factorial",
288
+ point_types=point_types,
289
+ generators=expressions,
290
+ resolution=actual_resolution,
291
+ replicate=replicates,
292
+ center_points=center_points,
293
+ randomize=randomize,
294
+ seed=seed,
295
+ notes=f"2^({k}-{p}) fractional factorial, generators: {', '.join(expressions)}.",
296
+ )
297
+
298
+
299
+ def _hadamard(runs: int) -> np.ndarray:
300
+ if runs < 2 or runs % 4 != 0:
301
+ raise ValueError("Hadamard screening designs need a run count divisible by four.")
302
+ if runs & (runs - 1) == 0:
303
+ matrix = np.array([[1.0]])
304
+ while matrix.shape[0] < runs:
305
+ matrix = np.block([[matrix, matrix], [matrix, -matrix]])
306
+ return matrix
307
+ q = runs - 1
308
+ if q < 3 or any(q % divisor == 0 for divisor in range(2, int(q**0.5) + 1)):
309
+ raise ValueError(f"No screening construction is available for {runs} runs.")
310
+ if q % 4 != 3:
311
+ raise ValueError(f"No screening construction is available for {runs} runs.")
312
+ residues = {(value * value) % q for value in range(1, q)}
313
+ q_matrix = np.zeros((q, q), dtype=float)
314
+ for i in range(q):
315
+ for j in range(q):
316
+ if i != j:
317
+ q_matrix[i, j] = 1.0 if (j - i) % q in residues else -1.0
318
+ ones = np.ones((1, q), dtype=float)
319
+ ones_column = np.ones((q, 1), dtype=float)
320
+ return np.block([[np.array([[1.0]]), ones], [ones_column, q_matrix - np.eye(q)]])
321
+
322
+
323
+ def screening_design(
324
+ factors: Sequence[Factor],
325
+ runs: int = 16,
326
+ center_points: int = 0,
327
+ randomize: bool = True,
328
+ seed: int | None = 42,
329
+ ) -> DataTable:
330
+ if runs not in {8, 12, 16, 20, 24, 32, 44, 48, 64}:
331
+ raise ValueError("Screening designs support 8, 12, 16, 20, 24, 32, 44, 48, or 64 runs.")
332
+ if len(factors) > runs - 1:
333
+ raise ValueError(f"{runs} runs support at most {runs - 1} factors.")
334
+ matrix = _hadamard(runs)
335
+ design = matrix[:, 1 : len(factors) + 1]
336
+ coded_rows = []
337
+ for row in design:
338
+ coded_rows.append({factor.name: float(value) for factor, value in zip(factors, row)})
339
+ for _ in range(center_points):
340
+ coded_rows.append({factor.name: 0.0 for factor in factors})
341
+ point_types = ["Screening"] * len(design) + ["Center"] * center_points
342
+ return _build_design_table(
343
+ coded_rows,
344
+ factors,
345
+ "Plackett-Burman Screening",
346
+ point_types=point_types,
347
+ center_points=center_points,
348
+ randomize=randomize,
349
+ seed=seed,
350
+ notes="Hadamard-based screening design.",
351
+ )
352
+
353
+
354
+ def central_composite(
355
+ factors: Sequence[Factor],
356
+ alpha: float | None = None,
357
+ center_points: int = 4,
358
+ replicates: int = 1,
359
+ randomize: bool = True,
360
+ seed: int | None = 42,
361
+ ) -> DataTable:
362
+ k = len(factors)
363
+ if k < 2:
364
+ raise ValueError("Central composite designs need at least two factors.")
365
+ if k > 7:
366
+ raise ValueError("Central composite designs are limited to seven factors.")
367
+ if alpha is None:
368
+ alpha = (2**k) ** 0.25
369
+ if alpha <= 0:
370
+ raise ValueError("Alpha must be positive.")
371
+ coded_rows = []
372
+ point_types = []
373
+ for values in itertools.product([-1.0, 1.0], repeat=k):
374
+ coded_rows.append({factor.name: value for factor, value in zip(factors, values)})
375
+ point_types.append("Factorial")
376
+ for index in range(k):
377
+ for sign in (-1.0, 1.0):
378
+ row = {factor.name: 0.0 for factor in factors}
379
+ row[factors[index].name] = sign * alpha
380
+ coded_rows.append(row)
381
+ point_types.append("Axial")
382
+ for _ in range(center_points):
383
+ coded_rows.append({factor.name: 0.0 for factor in factors})
384
+ point_types.append("Center")
385
+ return _build_design_table(
386
+ coded_rows,
387
+ factors,
388
+ "Central Composite",
389
+ point_types=point_types,
390
+ replicate=replicates,
391
+ center_points=center_points,
392
+ randomize=randomize,
393
+ seed=seed,
394
+ notes=f"Rotatable central composite design with alpha = {alpha:.4g}.",
395
+ )
396
+
397
+
398
+ def box_behnken(
399
+ factors: Sequence[Factor],
400
+ center_points: int = 3,
401
+ replicates: int = 1,
402
+ randomize: bool = True,
403
+ seed: int | None = 42,
404
+ ) -> DataTable:
405
+ k = len(factors)
406
+ if k < 3:
407
+ raise ValueError("Box-Behnken designs need at least three factors.")
408
+ if k > 7:
409
+ raise ValueError("Box-Behnken designs are limited to seven factors.")
410
+ coded_rows = []
411
+ for first, second in itertools.combinations(range(k), 2):
412
+ for first_value in (-1.0, 1.0):
413
+ for second_value in (-1.0, 1.0):
414
+ row = {factor.name: 0.0 for factor in factors}
415
+ row[factors[first].name] = first_value
416
+ row[factors[second].name] = second_value
417
+ coded_rows.append(row)
418
+ for _ in range(center_points):
419
+ coded_rows.append({factor.name: 0.0 for factor in factors})
420
+ point_types = ["Edge"] * (len(coded_rows) - center_points) + ["Center"] * center_points
421
+ return _build_design_table(
422
+ coded_rows,
423
+ factors,
424
+ "Box-Behnken",
425
+ point_types=point_types,
426
+ replicate=replicates,
427
+ center_points=center_points,
428
+ randomize=randomize,
429
+ seed=seed,
430
+ notes="Box-Behnken response surface design.",
431
+ )
432
+
433
+
434
+ def design_info(table: DataTable) -> dict[str, Any] | None:
435
+ payload = table.metadata.get("design")
436
+ return payload if isinstance(payload, dict) else None
437
+
438
+
439
+ def design_factors(table: DataTable) -> list[Factor]:
440
+ info = design_info(table)
441
+ if not info:
442
+ return []
443
+ if info.get("design_type") == "Custom":
444
+ raise ValueError("Use the custom DOE analysis and diagnostics for this design.")
445
+ return [Factor(**{k: v for k, v in item.items() if k in {"name", "low", "high", "units"}}) for item in info.get("factors", [])]
446
+
447
+
448
+ def _coded_frame(table: DataTable, factors: Sequence[Factor], response: str) -> pd.DataFrame:
449
+ frame = table.analysis_df()
450
+ result = pd.DataFrame(index=frame.index)
451
+ for factor in factors:
452
+ if factor.name not in frame.columns:
453
+ raise KeyError(f"Factor column missing: {factor.name}")
454
+ values = pd.to_numeric(frame[factor.name], errors="coerce")
455
+ result[factor.name] = (values - factor.center) / factor.half_range if factor.half_range else 0.0
456
+ if response not in frame.columns:
457
+ raise KeyError(f"Response column missing: {response}")
458
+ result[response] = pd.to_numeric(frame[response], errors="coerce")
459
+ return result.dropna()
460
+
461
+
462
+ def _model_terms(factors: Sequence[Factor], order: int) -> list[str]:
463
+ names = [f.name for f in factors]
464
+ terms = [_q(name) for name in names]
465
+ if order >= 2:
466
+ terms.extend(f"{_q(first)}:{_q(second)}" for first, second in itertools.combinations(names, 2))
467
+ terms.extend(f'I({_q(name)}**2)' for name in names)
468
+ if order >= 3:
469
+ terms.extend(
470
+ f"{_q(first)}:{_q(second)}:{_q(third)}"
471
+ for first, second, third in itertools.combinations(names, 3)
472
+ )
473
+ return terms
474
+
475
+
476
+ def fit_design_model(table: DataTable, response: str, order: int = 2):
477
+ factors = design_factors(table)
478
+ if not factors:
479
+ raise ValueError("This table has no DOE design metadata.")
480
+ frame = _coded_frame(table, factors, response)
481
+ formula = f"{_q(response)} ~ " + " + ".join(_model_terms(factors, order))
482
+ model = smf.ols(formula, data=frame).fit()
483
+ return model, factors, frame
484
+
485
+
486
+ def analyze_design(
487
+ table: DataTable,
488
+ response: str,
489
+ order: int = 2,
490
+ optimize: str | None = None,
491
+ ) -> AnalysisResult:
492
+ factors = design_factors(table)
493
+ if not factors:
494
+ raise ValueError("This table has no DOE design metadata. Create a design with StatStudio first.")
495
+ if order not in {1, 2, 3}:
496
+ raise ValueError("Model order must be 1 (main), 2 (full quadratic), or 3 (full quadratic plus three-way interactions).")
497
+ frame = _coded_frame(table, factors, response)
498
+ terms = _model_terms(factors, order)
499
+ if len(frame) <= len(terms) + 1:
500
+ raise ValueError("Not enough runs to fit the requested model with residual degrees of freedom.")
501
+ formula = f"{_q(response)} ~ " + " + ".join(terms)
502
+ model = smf.ols(formula, data=frame).fit()
503
+ coefficients = pd.DataFrame(
504
+ {
505
+ "Term": [display_formula(name) for name in model.params.index],
506
+ "Estimate": model.params.values,
507
+ "Std Error": model.bse.values,
508
+ "t": model.tvalues.values,
509
+ "p-value": model.pvalues.values,
510
+ "Effect": [2 * value if name != "Intercept" else np.nan for name, value in model.params.items()],
511
+ "Significance": [p_stars(p) for p in model.pvalues.values],
512
+ }
513
+ )
514
+ effects = coefficients.loc[coefficients["Term"] != "Intercept"].copy()
515
+ effects["Abs t"] = effects["t"].abs()
516
+ effects = effects.sort_values("Abs t", ascending=False)
517
+ result = AnalysisResult(
518
+ title=f"DOE Analysis: {response}",
519
+ analysis_type="doe_analysis",
520
+ params={"response": response, "order": order, "optimize": optimize},
521
+ source_table=table.name,
522
+ )
523
+ result.add_table("Model Coefficients", coefficients)
524
+ result.add_table("Effects (sorted by |t|)", effects.reset_index(drop=True))
525
+ result.add_table(
526
+ "Model Metrics",
527
+ pd.DataFrame(
528
+ [
529
+ ("Design", design_info(table).get("design_type", "DOE") if design_info(table) else "DOE"),
530
+ ("Runs", len(frame)),
531
+ ("Model terms", len(terms)),
532
+ ("R-squared", model.rsquared),
533
+ ("Adjusted R-squared", model.rsquared_adj),
534
+ ("F statistic", model.fvalue),
535
+ ("Model p-value", model.f_pvalue),
536
+ ("RMSE", float(np.sqrt(model.mse_resid))),
537
+ ("AIC", model.aic),
538
+ ("BIC", model.bic),
539
+ ],
540
+ columns=["Metric", "Value"],
541
+ ),
542
+ )
543
+ try:
544
+ anova = anova_lm(model, typ=2).reset_index().rename(columns={"index": "Source"})
545
+ anova["Source"] = anova["Source"].map(display_formula)
546
+ result.add_table("ANOVA", anova)
547
+ except Exception:
548
+ pass
549
+ alias = _alias_table(model)
550
+ if not alias.empty:
551
+ result.add_table("Alias Structure", alias)
552
+ lack_of_fit = _lack_of_fit_table(frame, factors, response, model)
553
+ if lack_of_fit is not None:
554
+ result.add_table("Lack of Fit", lack_of_fit)
555
+ result.add_plot("doe_pareto", {}, title="Pareto Plot of Standardized Effects", data=effects)
556
+ main_effects = _main_effects_frame(model, factors, response)
557
+ result.add_table("Main Effects", main_effects)
558
+ result.add_plot("main_effects", {"factor": "Factor", "level": "Level", "response": "Predicted"}, title="Main Effects", data=main_effects)
559
+ interactions = _interaction_frame(model, factors)
560
+ if not interactions.empty:
561
+ result.add_table("Interaction Predictions", interactions)
562
+ result.add_plot("interaction", {"factor1": "Factor 1", "level1": "Level 1", "factor2": "Factor 2", "level2": "Level 2", "response": "Predicted"}, title="Interaction Plots", data=interactions)
563
+ if len(factors) >= 2:
564
+ contour = _contour_frame(model, factors)
565
+ result.add_plot("doe_contour", {"x": "Factor 1", "y": "Factor 2", "z": "Predicted", "x_label": factors[0].name, "y_label": factors[1].name}, title="Response Contour", data=contour)
566
+ profiler = _profiler_frame(model, factors, response)
567
+ result.add_table("Prediction Profiler", profiler)
568
+ result.add_plot("profiler", {"factor": "Factor", "level": "Level", "predicted": "Predicted", "x_label": "Actual Level"}, title="Prediction Profiler", data=profiler)
569
+ result.add_model("doe_model", model)
570
+ result.add_model("doe_factors", factors)
571
+ try:
572
+ result.profiler_session = _profiler_session(model, factors, response)
573
+ except Exception:
574
+ result.profiler_session = None
575
+ if optimize in {"max", "maximize", "min", "minimize"}:
576
+ optimum = _optimize(model, factors, response, maximize=optimize.startswith("max"))
577
+ result.add_table("Optimized Settings", optimum)
578
+ result.summary = (
579
+ f"{model.rsquared:.4f} R-squared, model p = {model.f_pvalue:.4g}. "
580
+ f"Optimum predicted {response}: {optimum['Predicted Response'].iloc[0]:.6g}."
581
+ )
582
+ else:
583
+ result.summary = f"{model.rsquared:.4f} R-squared, adjusted R² = {model.rsquared_adj:.4f}, model p = {model.f_pvalue:.4g}, N = {len(frame)}."
584
+ info = design_info(table) or {}
585
+ notes = []
586
+ if info.get("resolution"):
587
+ notes.append(f"Design resolution: {info['resolution']}. Generators: {', '.join(info.get('generators', [])) or 'none'}.")
588
+ if notes:
589
+ result.notes = " ".join(notes)
590
+ try:
591
+ diagnostics = design_diagnostics(table)
592
+ result.tables.extend(diagnostics.tables)
593
+ except Exception:
594
+ pass
595
+ return result
596
+
597
+
598
+ def _alias_table(model) -> pd.DataFrame:
599
+ exog = pd.DataFrame(model.model.exog, columns=model.model.exog_names)
600
+ correlation = exog.corr().abs()
601
+ rows = []
602
+ columns = list(correlation.columns)
603
+ for first_index, first in enumerate(columns):
604
+ for second in columns[first_index + 1:]:
605
+ value = correlation.loc[first, second]
606
+ if pd.notna(value) and value >= 0.999:
607
+ rows.append({"Term 1": display_formula(first), "Term 2": display_formula(second), "Absolute correlation": float(value)})
608
+ return pd.DataFrame(rows)
609
+
610
+
611
+ def _lack_of_fit_table(frame: pd.DataFrame, factors: Sequence[Factor], response: str, model) -> pd.DataFrame | None:
612
+ factor_columns = [factor.name for factor in factors]
613
+ groups = frame.groupby(factor_columns, dropna=False)[response]
614
+ sizes = groups.size()
615
+ pure_df = int((sizes - 1).clip(lower=0).sum())
616
+ if pure_df <= 0:
617
+ return None
618
+ pure_sse = float(sum(((chunk - chunk.mean()) ** 2).sum() for _, chunk in groups))
619
+ lack_df = int(model.df_resid - pure_df)
620
+ if lack_df <= 0:
621
+ return None
622
+ lack_sse = max(0.0, float(model.ssr) - pure_sse)
623
+ ms_lack = lack_sse / lack_df
624
+ ms_pure = pure_sse / pure_df
625
+ f_value = ms_lack / ms_pure if ms_pure else np.nan
626
+ p_value = float(_scipy_stats.f.sf(f_value, lack_df, pure_df)) if np.isfinite(f_value) else np.nan
627
+ return pd.DataFrame([
628
+ {"Source": "Lack of Fit", "SS": lack_sse, "DF": lack_df, "MS": ms_lack, "F": f_value, "p-value": p_value},
629
+ {"Source": "Pure Error", "SS": pure_sse, "DF": pure_df, "MS": ms_pure, "F": np.nan, "p-value": np.nan},
630
+ ])
631
+
632
+
633
+ def _profiler_session(model, factors: Sequence[Factor], response: str, points: int = 9) -> ProfilerSession:
634
+ profiler_factors = [
635
+ ProfilerFactor(
636
+ factor.name,
637
+ "continuous",
638
+ low=factor.low,
639
+ high=factor.high,
640
+ current=factor.center,
641
+ initial=factor.center,
642
+ units=factor.units,
643
+ )
644
+ for factor in factors
645
+ ]
646
+
647
+ def predict(settings: dict[str, Any]) -> float:
648
+ coded = {
649
+ factor.name: factor.coded(float(settings.get(factor.name, factor.center)))
650
+ for factor in factors
651
+ }
652
+ predicted = model.predict(pd.DataFrame([coded]))
653
+ return float(np.asarray(predicted).reshape(-1)[0])
654
+
655
+ return ProfilerSession(
656
+ response=response,
657
+ factors=profiler_factors,
658
+ predict=predict,
659
+ response_label=response,
660
+ points=points,
661
+ )
662
+
663
+
664
+ def _profiler_frame(model, factors: Sequence[Factor], response: str, points: int = 9) -> pd.DataFrame:
665
+ rows = []
666
+ for factor in factors:
667
+ for value in np.linspace(-1.0, 1.0, max(3, points)):
668
+ settings = {item.name: 0.0 for item in factors}
669
+ settings[factor.name] = float(value)
670
+ predicted = float(model.predict(_settings_frame(factors, settings)).iloc[0])
671
+ rows.append({"Factor": factor.name, "Level": factor.actual(float(value)), "Coded": float(value), "Predicted": predicted})
672
+ return pd.DataFrame(rows)
673
+
674
+
675
+ def prediction_profiler(
676
+ table: DataTable,
677
+ response: str,
678
+ order: int = 2,
679
+ points: int = 9,
680
+ ) -> AnalysisResult:
681
+ factors = design_factors(table)
682
+ if not factors:
683
+ raise ValueError("This table has no DOE design metadata.")
684
+ frame = _coded_frame(table, factors, response)
685
+ formula = f"{_q(response)} ~ " + " + ".join(_model_terms(factors, order))
686
+ model = smf.ols(formula, data=frame).fit()
687
+ profiler = _profiler_frame(model, factors, response, points)
688
+ result = AnalysisResult(
689
+ title=f"Prediction Profiler: {response}",
690
+ analysis_type="prediction_profiler",
691
+ params={"response": response, "order": order, "points": points},
692
+ source_table=table.name,
693
+ )
694
+ result.add_table("Profiler Grid", profiler)
695
+ result.add_plot("profiler", {"factor": "Factor", "level": "Level", "predicted": "Predicted"}, title="Prediction Profiler", data=profiler)
696
+ result.add_model("doe_model", model)
697
+ result.add_model("doe_factors", factors)
698
+ try:
699
+ result.profiler_session = _profiler_session(model, factors, response, points)
700
+ except Exception:
701
+ result.profiler_session = None
702
+ result.summary = f"Prediction profiler for {response} across {len(factors)} factor(s), holding other factors at their center."
703
+ return result
704
+
705
+
706
+ def _settings_frame(factors: Sequence[Factor], values: dict[str, float]) -> pd.DataFrame:
707
+ return pd.DataFrame([{factor.name: values.get(factor.name, 0.0) for factor in factors}])
708
+
709
+
710
+ def _main_effects_frame(model, factors: Sequence[Factor], response: str) -> pd.DataFrame:
711
+ rows = []
712
+ for factor in factors:
713
+ for level in (-1.0, 1.0):
714
+ predicted = float(model.predict(_settings_frame(factors, {factor.name: level})).iloc[0])
715
+ rows.append(
716
+ {
717
+ "Factor": factor.name,
718
+ "Level": "Low" if level < 0 else "High",
719
+ "Coded Level": level,
720
+ "Predicted": predicted,
721
+ }
722
+ )
723
+ return pd.DataFrame(rows)
724
+
725
+
726
+ def _interaction_frame(model, factors: Sequence[Factor]) -> pd.DataFrame:
727
+ rows = []
728
+ for first, second in itertools.combinations(factors, 2):
729
+ for first_level in (-1.0, 1.0):
730
+ for second_level in (-1.0, 1.0):
731
+ values = {first.name: first_level, second.name: second_level}
732
+ predicted = float(model.predict(_settings_frame(factors, values)).iloc[0])
733
+ rows.append(
734
+ {
735
+ "Factor 1": first.name,
736
+ "Level 1": "Low" if first_level < 0 else "High",
737
+ "Factor 2": second.name,
738
+ "Level 2": "Low" if second_level < 0 else "High",
739
+ "Predicted": predicted,
740
+ }
741
+ )
742
+ return pd.DataFrame(rows)
743
+
744
+
745
+ def _contour_frame(model, factors: Sequence[Factor], points: int = 25) -> pd.DataFrame:
746
+ first, second = factors[0], factors[1]
747
+ x_values = np.linspace(-1, 1, points)
748
+ y_values = np.linspace(-1, 1, points)
749
+ rows = []
750
+ grid = []
751
+ for x in x_values:
752
+ row = []
753
+ for y in y_values:
754
+ settings = {factor.name: 0.0 for factor in factors}
755
+ settings[first.name] = float(x)
756
+ settings[second.name] = float(y)
757
+ row.append(float(model.predict(_settings_frame(factors, settings)).iloc[0]))
758
+ grid.append(row)
759
+ for i, x in enumerate(x_values):
760
+ for j, y in enumerate(y_values):
761
+ rows.append({"Factor 1": float(x), "Factor 2": float(y), "Predicted": grid[i][j]})
762
+ frame = pd.DataFrame(rows)
763
+ frame.attrs["grid"] = grid
764
+ return frame
765
+
766
+
767
+ def _optimize(model, factors: Sequence[Factor], response: str, maximize: bool = True) -> pd.DataFrame:
768
+ def objective(values: np.ndarray) -> float:
769
+ settings = {factor.name: float(value) for factor, value in zip(factors, values)}
770
+ predicted = float(model.predict(_settings_frame(factors, settings)).iloc[0])
771
+ return -predicted if maximize else predicted
772
+
773
+ starts = [np.zeros(len(factors))]
774
+ rng = np.random.default_rng(123)
775
+ starts.extend(rng.uniform(-1, 1, size=len(factors)) for _ in range(12))
776
+ best = None
777
+ for start in starts:
778
+ try:
779
+ outcome = minimize(objective, start, bounds=[(-1, 1)] * len(factors), method="L-BFGS-B")
780
+ except Exception:
781
+ continue
782
+ if best is None or outcome.fun < best.fun:
783
+ best = outcome
784
+ if best is None:
785
+ raise ValueError("Optimization failed.")
786
+ coded = {factor.name: float(value) for factor, value in zip(factors, best.x)}
787
+ actual = {factor.name: factor.actual(coded[factor.name]) for factor in factors}
788
+ predicted = -best.fun if maximize else best.fun
789
+ row = {
790
+ "Objective": "Maximize" if maximize else "Minimize",
791
+ "Predicted Response": predicted,
792
+ }
793
+ for factor in factors:
794
+ row[f"{factor.name} (coded)"] = coded[factor.name]
795
+ row[f"{factor.name} (actual)"] = actual[factor.name]
796
+ return pd.DataFrame([row])
797
+
798
+
799
+ def predict_response(table: DataTable, response: str, order: int, settings: dict[str, float]) -> tuple[float, pd.DataFrame]:
800
+ factors = design_factors(table)
801
+ if not factors:
802
+ raise ValueError("No DOE design metadata.")
803
+ frame = _coded_frame(table, factors, response)
804
+ formula = f"{_q(response)} ~ " + " + ".join(_model_terms(factors, order))
805
+ model = smf.ols(formula, data=frame).fit()
806
+ coded = {factor.name: factor.coded(settings.get(factor.name, factor.center)) for factor in factors}
807
+ predicted = float(model.predict(_settings_frame(factors, coded)).iloc[0])
808
+ return predicted, pd.DataFrame([settings])
809
+
810
+
811
+ def assign_blocks(table: DataTable, n_blocks: int) -> DataTable:
812
+ if n_blocks < 1:
813
+ raise ValueError("Number of blocks must be at least one.")
814
+ frame = table.data.copy()
815
+ factors = design_factors(table)
816
+ block: np.ndarray | None = None
817
+ if factors:
818
+ coded = pd.DataFrame(
819
+ {
820
+ factor.name: (pd.to_numeric(frame[factor.name], errors="coerce") - factor.center) / factor.half_range
821
+ if factor.half_range
822
+ else pd.Series(0.0, index=frame.index)
823
+ for factor in factors
824
+ },
825
+ index=frame.index,
826
+ )
827
+ candidates: list[tuple[int, np.ndarray]] = []
828
+ names = [factor.name for factor in factors]
829
+ for size in range(2, len(names) + 1):
830
+ for combination in itertools.combinations(names, size):
831
+ product = coded[list(combination)].prod(axis=1).to_numpy(dtype=float)
832
+ if np.unique(np.sign(product)).size > 1:
833
+ candidates.append((size, np.sign(product)))
834
+ candidates.sort(key=lambda item: item[0], reverse=True)
835
+ bits = max(1, int(np.ceil(np.log2(n_blocks)))) if n_blocks > 1 else 0
836
+ chosen: list[np.ndarray] = []
837
+ for _, product in candidates:
838
+ if len(chosen) >= bits:
839
+ break
840
+ if all(not np.array_equal(product, other) for other in chosen):
841
+ chosen.append(product)
842
+ if chosen:
843
+ codes = np.zeros(len(frame), dtype=int)
844
+ for bit, product in enumerate(chosen):
845
+ codes |= (product >= 0).astype(int) << bit
846
+ block = codes % n_blocks + 1
847
+ if block is None:
848
+ block = (np.arange(len(frame)) % n_blocks) + 1
849
+ frame["Block"] = block
850
+ result = DataTable(frame, name=f"{table.name} (Blocked)", source=table.source, specs=table.specs, metadata=copy.deepcopy(table.metadata))
851
+ info = result.metadata.get("design")
852
+ if isinstance(info, dict):
853
+ info["blocks"] = n_blocks
854
+ result.modified = True
855
+ return result
856
+
857
+
858
+ def fold_over(table: DataTable) -> DataTable:
859
+ factors = design_factors(table)
860
+ if not factors:
861
+ raise ValueError("This table has no DOE design metadata.")
862
+ frame = table.analysis_df().reset_index(drop=True)
863
+ factorial = frame
864
+ if "Point Type" in frame.columns:
865
+ factorial = frame[frame["Point Type"].astype(str).str.lower().isin({"factorial", "fractional", "screening", "edge"})]
866
+ if factorial.empty:
867
+ factorial = frame
868
+ mirrored = factorial.copy()
869
+ for factor in factors:
870
+ if factor.name not in mirrored.columns:
871
+ raise KeyError(f"Factor column missing: {factor.name}")
872
+ mirrored[factor.name] = 2 * factor.center - pd.to_numeric(mirrored[factor.name], errors="coerce")
873
+ for column in frame.columns:
874
+ if column not in mirrored.columns:
875
+ mirrored[column] = np.nan
876
+ elif column not in [f.name for f in factors] and column not in {"Std Order", "Run Order", "Replicate", "Point Type", "Block"}:
877
+ mirrored[column] = np.nan
878
+ combined = pd.concat([frame, mirrored], ignore_index=True)
879
+ if "Std Order" in combined.columns:
880
+ combined["Std Order"] = np.arange(1, len(combined) + 1)
881
+ if "Run Order" in combined.columns:
882
+ combined["Run Order"] = np.arange(1, len(combined) + 1)
883
+ result = DataTable(combined, name=f"{table.name} (Fold-Over)", source=f"Fold-over of {table.name}", metadata=copy.deepcopy(table.metadata))
884
+ info = result.metadata.get("design")
885
+ if isinstance(info, dict):
886
+ info["fold_over"] = True
887
+ result.modified = True
888
+ return result
889
+
890
+
891
+ def _design_matrix(table: DataTable) -> tuple[pd.DataFrame, list[str]]:
892
+ factors = design_factors(table)
893
+ if not factors:
894
+ raise ValueError("This table has no DOE design metadata.")
895
+ frame = table.analysis_df()
896
+ coded = pd.DataFrame(index=frame.index)
897
+ for factor in factors:
898
+ values = pd.to_numeric(frame[factor.name], errors="coerce")
899
+ coded[factor.name] = (values - factor.center) / factor.half_range if factor.half_range else 0.0
900
+ coded = coded.dropna()
901
+ return coded, [f.name for f in factors]
902
+
903
+
904
+ def design_diagnostics(table: DataTable) -> AnalysisResult:
905
+ info = design_info(table) or {}
906
+ if info.get("design_type") == "Custom":
907
+ from statstudio.stats import custom_doe
908
+
909
+ return custom_doe.design_diagnostics(table)
910
+ coded, names = _design_matrix(table)
911
+ matrix = coded.to_numpy(dtype=float)
912
+ n = matrix.shape[0]
913
+ # Main-effects model matrix with intercept
914
+ X = np.column_stack([np.ones(n), matrix])
915
+ p = X.shape[1]
916
+ try:
917
+ moment = X.T @ X
918
+ sign, logdet = np.linalg.slogdet(moment)
919
+ d_efficiency = float(100.0 * np.exp(logdet / p) / n) if sign > 0 else np.nan
920
+ except Exception:
921
+ d_efficiency = np.nan
922
+ lc = coded.copy()
923
+ lc["Mean"] = 1.0
924
+ corr = lc.corr().abs().fillna(0.0)
925
+ np.fill_diagonal(corr.values, 0.0)
926
+ max_corr = float(np.nanmax(corr.to_numpy())) if corr.size else np.nan
927
+ worst = None
928
+ if corr.size:
929
+ stacked = corr.stack()
930
+ if not stacked.empty:
931
+ worst = stacked.idxmax()
932
+ result = AnalysisResult(
933
+ title="Design Diagnostics",
934
+ analysis_type="doe_diagnostics",
935
+ params={"design_type": info.get("design_type"), "factors": names},
936
+ source_table=table.name,
937
+ )
938
+ result.add_table(
939
+ "Design Summary",
940
+ pd.DataFrame(
941
+ [
942
+ ("Design", info.get("design_type", "DOE")),
943
+ ("Factors", len(names)),
944
+ ("Runs", n),
945
+ ("Blocks", info.get("blocks", 1)),
946
+ ("Resolution", info.get("resolution") or "n/a"),
947
+ ("Generators", ", ".join(info.get("generators", [])) or "none"),
948
+ ("D-efficiency", d_efficiency),
949
+ ("Max |correlation|", max_corr),
950
+ ("Worst correlation", str(worst) if worst else ""),
951
+ ],
952
+ columns=["Metric", "Value"],
953
+ ),
954
+ )
955
+ result.add_plot("correlation_heatmap", {"columns": list(lc.columns), "matrix": lc.corr().to_dict()}, title="Factor Correlation", data=lc.reset_index(drop=True))
956
+ result.summary = f"{info.get('design_type', 'DOE')} with {n} runs, D-efficiency {d_efficiency:.2f}%, max |correlation| {max_corr:.3f}."
957
+ return result
958
+
959
+
960
+ def factorial_levels(
961
+ factors: Sequence[Factor],
962
+ levels: int = 3,
963
+ replicates: int = 1,
964
+ randomize: bool = True,
965
+ seed: int | None = 42,
966
+ ) -> DataTable:
967
+ if not factors:
968
+ raise ValueError("At least one factor is required.")
969
+ if levels < 2 or levels > 5:
970
+ raise ValueError("Only two to five levels are supported.")
971
+ if len(factors) > 6:
972
+ raise ValueError("Multi-level factorial designs are limited to six factors.")
973
+ coded_levels = np.linspace(-1.0, 1.0, levels).tolist()
974
+ rows = []
975
+ point_types = []
976
+ for values in itertools.product(coded_levels, repeat=len(factors)):
977
+ rows.append({factor.name: value for factor, value in zip(factors, values)})
978
+ point_types.append("Center" if all(abs(value) < 1e-9 for value in values) else f"{levels}-Level")
979
+ if len(rows) > 1000:
980
+ raise ValueError("The requested design exceeds 1000 runs.")
981
+ return _build_design_table(
982
+ rows,
983
+ factors,
984
+ f"{levels}-Level Factorial",
985
+ point_types=point_types,
986
+ replicate=replicates,
987
+ randomize=randomize,
988
+ seed=seed,
989
+ notes=f"{levels}^{len(factors)} full factorial.",
990
+ )
991
+
992
+
993
+ def replicate_design(table: DataTable, replicates: int = 1, randomize: bool = True, seed: int | None = 42) -> DataTable:
994
+ factors = design_factors(table)
995
+ if not factors:
996
+ raise ValueError("This table has no DOE design metadata.")
997
+ if replicates < 1:
998
+ raise ValueError("Replicates must be at least one.")
999
+ frame = table.analysis_df().reset_index(drop=True)
1000
+ pieces = []
1001
+ for replicate_index in range(1, replicates + 1):
1002
+ piece = frame.copy()
1003
+ piece["Replicate"] = replicate_index
1004
+ pieces.append(piece)
1005
+ combined = pd.concat(pieces, ignore_index=True)
1006
+ if randomize:
1007
+ combined = combined.sample(frac=1.0, random_state=seed).reset_index(drop=True)
1008
+ combined["Run Order"] = np.arange(1, len(combined) + 1)
1009
+ combined["Std Order"] = np.arange(1, len(combined) + 1)
1010
+ result = DataTable(combined, name=f"{table.name} (Replicated)", source=table.source, specs=table.specs, metadata=copy.deepcopy(table.metadata))
1011
+ info = result.metadata.get("design")
1012
+ if isinstance(info, dict):
1013
+ info["replicate"] = replicates
1014
+ result.modified = True
1015
+ return result
1016
+
1017
+
1018
+ def fold_factor(table: DataTable, factor_name: str) -> DataTable:
1019
+ factors = design_factors(table)
1020
+ factor = next((item for item in factors if item.name == factor_name), None)
1021
+ if factor is None:
1022
+ raise KeyError(factor_name)
1023
+ frame = table.analysis_df().reset_index(drop=True)
1024
+ factorial = frame
1025
+ if "Point Type" in frame.columns:
1026
+ factorial = frame[frame["Point Type"].astype(str).str.lower().isin({"factorial", "fractional", "screening", "edge"})]
1027
+ if factorial.empty:
1028
+ factorial = frame
1029
+ mirrored = factorial.copy()
1030
+ mirrored[factor_name] = 2 * factor.center - pd.to_numeric(mirrored[factor_name], errors="coerce")
1031
+ for column in frame.columns:
1032
+ if column not in mirrored.columns:
1033
+ mirrored[column] = np.nan
1034
+ elif column not in [item.name for item in factors] and column not in {"Std Order", "Run Order", "Replicate", "Point Type", "Block"}:
1035
+ mirrored[column] = np.nan
1036
+ combined = pd.concat([frame, mirrored], ignore_index=True)
1037
+ combined["Std Order"] = np.arange(1, len(combined) + 1)
1038
+ combined["Run Order"] = np.arange(1, len(combined) + 1)
1039
+ result = DataTable(combined, name=f"{table.name} (Fold {factor_name})", source=f"Fold over {factor_name} of {table.name}", specs=table.specs, metadata=copy.deepcopy(table.metadata))
1040
+ info = result.metadata.get("design")
1041
+ if isinstance(info, dict):
1042
+ info["fold_factor"] = factor_name
1043
+ result.modified = True
1044
+ return result
1045
+
1046
+
1047
+ def add_axial_points(table: DataTable, alpha: float = 2.0) -> DataTable:
1048
+ factors = design_factors(table)
1049
+ if not factors:
1050
+ raise ValueError("This table has no DOE design metadata.")
1051
+ frame = table.analysis_df().reset_index(drop=True)
1052
+ rows = []
1053
+ for factor in factors:
1054
+ for sign in (-1.0, 1.0):
1055
+ row = {column: np.nan for column in frame.columns}
1056
+ for item in factors:
1057
+ row[item.name] = item.center
1058
+ row[factor.name] = factor.actual(sign * alpha)
1059
+ row["Point Type"] = "Axial"
1060
+ row["Replicate"] = 1
1061
+ rows.append(row)
1062
+ combined = pd.concat([frame, pd.DataFrame(rows)], ignore_index=True)
1063
+ combined["Std Order"] = np.arange(1, len(combined) + 1)
1064
+ combined["Run Order"] = np.arange(1, len(combined) + 1)
1065
+ result = DataTable(combined, name=f"{table.name} (Augmented)", source=f"Axial augmentation of {table.name}", specs=table.specs, metadata=copy.deepcopy(table.metadata))
1066
+ info = result.metadata.get("design")
1067
+ if isinstance(info, dict):
1068
+ info["alpha"] = alpha
1069
+ result.modified = True
1070
+ return result