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,307 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Sequence
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from scipy.cluster.hierarchy import fcluster, linkage
8
+ from sklearn.cluster import KMeans
9
+ from sklearn.decomposition import FactorAnalysis, PCA
10
+ from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
11
+ from sklearn.metrics import silhouette_score
12
+ from sklearn.preprocessing import StandardScaler
13
+
14
+ from statstudio.stats.common import numeric_columns
15
+ from statstudio.stats.results import AnalysisResult
16
+
17
+
18
+ def _numeric_matrix(df: pd.DataFrame, columns: Sequence[str]) -> tuple[pd.DataFrame, np.ndarray]:
19
+ missing = [c for c in columns if c not in df.columns]
20
+ if missing:
21
+ raise KeyError(f"Missing columns: {', '.join(missing)}")
22
+ frame = df.loc[:, columns].apply(pd.to_numeric, errors="coerce").dropna()
23
+ if len(frame) < 3:
24
+ raise ValueError("At least three complete rows are required.")
25
+ return frame, frame.to_numpy(dtype=float)
26
+
27
+
28
+ def pca(df: pd.DataFrame, columns: Sequence[str] | None = None, n_components: int = 2, standardize: bool = True) -> AnalysisResult:
29
+ if columns is None:
30
+ columns = numeric_columns(df)
31
+ frame, matrix = _numeric_matrix(df, columns)
32
+ if standardize:
33
+ matrix = StandardScaler().fit_transform(matrix)
34
+ n_components = min(n_components, len(columns), len(frame))
35
+ model = PCA(n_components=n_components)
36
+ scores = model.fit_transform(matrix)
37
+ eigen_scale = (len(frame) - 1) / len(frame) if standardize and len(frame) > 1 else 1.0
38
+ eigenvalues = model.explained_variance_ * eigen_scale
39
+ loadings = pd.DataFrame(
40
+ model.components_.T,
41
+ index=columns,
42
+ columns=[f"PC{i + 1}" for i in range(n_components)],
43
+ )
44
+ explained = pd.DataFrame(
45
+ {
46
+ "Component": [f"PC{i + 1}" for i in range(n_components)],
47
+ "Eigenvalue": eigenvalues,
48
+ "Variance Explained": model.explained_variance_ratio_,
49
+ "Cumulative": np.cumsum(model.explained_variance_ratio_),
50
+ }
51
+ )
52
+ score_frame = pd.DataFrame(scores, columns=[f"PC{i + 1}" for i in range(n_components)])
53
+ result = AnalysisResult(
54
+ title="Principal Component Analysis",
55
+ analysis_type="pca",
56
+ params={"columns": list(columns), "n_components": n_components, "standardize": standardize},
57
+ )
58
+ result.add_table("Explained Variance", explained)
59
+ result.add_table("Loadings", loadings.reset_index().rename(columns={"index": "Variable"}))
60
+ result.add_table("Component Scores (first rows)", score_frame.head(50))
61
+ result.add_plot("scree", {"eigenvalues": eigenvalues.tolist()}, title="Scree Plot")
62
+ result.add_plot(
63
+ "pca_biplot",
64
+ {"scores": score_frame.head(500).to_dict("list"), "loadings": loadings.reset_index().rename(columns={"index": "Variable"}).to_dict("records")},
65
+ title="PCA Biplot",
66
+ data=score_frame.head(500),
67
+ )
68
+ result.add_plot(
69
+ "correlation_heatmap",
70
+ {"columns": columns, "matrix": loadings.to_dict()},
71
+ title="Loadings Heatmap",
72
+ data=loadings.reset_index().rename(columns={"index": "Variable"}),
73
+ )
74
+ result.summary = (
75
+ f"{n_components} components explain {explained['Cumulative'].iloc[-1] * 100:.1f}% "
76
+ f"of the variance across {len(columns)} variables and {len(frame)} rows."
77
+ )
78
+ return result
79
+
80
+
81
+ def kmeans_clustering(
82
+ df: pd.DataFrame,
83
+ columns: Sequence[str] | None = None,
84
+ n_clusters: int = 3,
85
+ standardize: bool = True,
86
+ ) -> AnalysisResult:
87
+ if columns is None:
88
+ columns = numeric_columns(df)
89
+ frame, matrix = _numeric_matrix(df, columns)
90
+ if standardize:
91
+ matrix = StandardScaler().fit_transform(matrix)
92
+ n_clusters = max(1, min(n_clusters, len(frame)))
93
+ model = KMeans(n_clusters=n_clusters, n_init=10, random_state=42)
94
+ labels = model.fit_predict(matrix)
95
+ score = silhouette_score(matrix, labels) if n_clusters > 1 and len(frame) > n_clusters else np.nan
96
+ profile = frame.copy()
97
+ profile["Cluster"] = labels
98
+ means = profile.groupby("Cluster")[list(columns)].mean().reset_index()
99
+ counts = profile["Cluster"].value_counts().sort_index().rename_axis("Cluster").reset_index(name="N")
100
+ result = AnalysisResult(
101
+ title="K-Means Clustering",
102
+ analysis_type="kmeans",
103
+ params={"columns": list(columns), "n_clusters": n_clusters, "standardize": standardize},
104
+ )
105
+ result.add_table("Cluster Sizes", counts)
106
+ result.add_table("Cluster Means", means)
107
+ result.add_table("Cluster Assignments", profile.head(200))
108
+ result.add_plot(
109
+ "cluster_scatter",
110
+ {"x": columns[0], "y": columns[1] if len(columns) > 1 else columns[0], "group": "Cluster"},
111
+ title="K-Means Clusters",
112
+ data=profile,
113
+ )
114
+ result.summary = f"{n_clusters} clusters from {len(frame)} rows; silhouette score = {score:.3f}."
115
+ return result
116
+
117
+
118
+ def hierarchical_clustering(
119
+ df: pd.DataFrame,
120
+ columns: Sequence[str] | None = None,
121
+ n_clusters: int = 3,
122
+ linkage_method: str = "ward",
123
+ ) -> AnalysisResult:
124
+ if columns is None:
125
+ columns = numeric_columns(df)
126
+ frame, matrix = _numeric_matrix(df, columns)
127
+ matrix = StandardScaler().fit_transform(matrix)
128
+ linkage_matrix = linkage(matrix, method=linkage_method)
129
+ labels = fcluster(linkage_matrix, t=n_clusters, criterion="maxclust")
130
+ profile = frame.copy()
131
+ profile["Cluster"] = labels - 1
132
+ means = profile.groupby("Cluster")[list(columns)].mean().reset_index()
133
+ result = AnalysisResult(
134
+ title="Hierarchical Clustering",
135
+ analysis_type="hierarchical_clustering",
136
+ params={"columns": list(columns), "n_clusters": n_clusters, "linkage_method": linkage_method},
137
+ )
138
+ result.add_table("Cluster Means", means)
139
+ result.add_table("Cluster Assignments", profile.head(200))
140
+ result.add_plot(
141
+ "dendrogram",
142
+ {"linkage": linkage_matrix.tolist()},
143
+ title="Dendrogram",
144
+ )
145
+ result.summary = f"{n_clusters} clusters using {linkage_method} linkage across {len(frame)} rows."
146
+ return result
147
+
148
+
149
+ def discriminant_analysis(
150
+ df: pd.DataFrame,
151
+ response: str,
152
+ predictors: Sequence[str],
153
+ method: str = "lda",
154
+ cross_validate: bool = True,
155
+ folds: int = 5,
156
+ priors: Sequence[float] | None = None,
157
+ ) -> AnalysisResult:
158
+ if response not in df.columns:
159
+ raise KeyError(response)
160
+ predictors = [p for p in predictors if p != response]
161
+ if not predictors:
162
+ raise ValueError("Choose at least one predictor.")
163
+ frame = df.loc[:, [response] + predictors].dropna()
164
+ numeric = frame.loc[:, predictors].apply(pd.to_numeric, errors="coerce")
165
+ frame = frame.assign(**{p: numeric[p] for p in predictors}).dropna()
166
+ if frame[response].nunique() < 2:
167
+ raise ValueError("Response must contain at least two classes.")
168
+ from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
169
+ from sklearn.model_selection import StratifiedKFold, cross_val_predict
170
+
171
+ method = method.lower()
172
+ if method in {"qda", "quadratic"}:
173
+ model = QuadraticDiscriminantAnalysis(priors=priors)
174
+ method_label = "QDA"
175
+ else:
176
+ model = LinearDiscriminantAnalysis(priors=priors)
177
+ method_label = "LDA"
178
+ model.fit(frame[predictors], frame[response])
179
+ predicted = model.predict(frame[predictors])
180
+ accuracy = float(np.mean(predicted == frame[response]))
181
+ confusion = pd.crosstab(frame[response], predicted, rownames=["Actual"], colnames=["Predicted"]).reset_index()
182
+ cv_accuracy = np.nan
183
+ cv_confusion = None
184
+ if cross_validate and len(frame) >= max(6, folds):
185
+ folds = max(2, min(int(folds), int(frame[response].value_counts().min())))
186
+ try:
187
+ cv_predicted = cross_val_predict(model, frame[predictors], frame[response], cv=StratifiedKFold(n_splits=folds, shuffle=True, random_state=42))
188
+ cv_accuracy = float(np.mean(cv_predicted == frame[response]))
189
+ cv_confusion = pd.crosstab(frame[response], cv_predicted, rownames=["Actual"], colnames=["Predicted"]).reset_index()
190
+ except Exception:
191
+ cv_accuracy = np.nan
192
+ result = AnalysisResult(
193
+ title=f"Discriminant Analysis ({method_label}): {response}",
194
+ analysis_type="discriminant",
195
+ params={"response": response, "predictors": list(predictors), "method": method, "cross_validate": cross_validate, "folds": folds},
196
+ )
197
+ if hasattr(model, "coef_"):
198
+ coefficients = pd.DataFrame({"Variable": predictors})
199
+ for index, row in enumerate(np.atleast_2d(model.coef_)):
200
+ coefficients[f"Coefficient {index + 1}"] = row
201
+ result.add_table("Discriminant Coefficients", coefficients)
202
+ result.add_table("Confusion Matrix", confusion)
203
+ result.add_table("Accuracy", pd.DataFrame([{"Residual Accuracy": accuracy, "Cross-Validated Accuracy": cv_accuracy, "N": len(frame), "Method": method_label}]))
204
+ if cv_confusion is not None:
205
+ result.add_table("Cross-Validated Confusion Matrix", cv_confusion)
206
+ if hasattr(model, "priors_"):
207
+ result.add_table("Class Priors", pd.DataFrame({"Class": model.classes_, "Prior": model.priors_}))
208
+ result.add_model("discriminant", model)
209
+ result.summary = f"{len(model.classes_)} classes, {method_label} accuracy = {accuracy:.3f}, CV accuracy = {cv_accuracy:.3f}, N = {len(frame)}."
210
+ return result
211
+
212
+
213
+ def canonical_correlation(df: pd.DataFrame, x_columns: Sequence[str], y_columns: Sequence[str]) -> AnalysisResult:
214
+ from sklearn.cross_decomposition import CCA
215
+
216
+ x_columns = [c for c in x_columns if c in df.columns]
217
+ y_columns = [c for c in y_columns if c in df.columns]
218
+ if not x_columns or not y_columns:
219
+ raise ValueError("Choose at least one variable in each set.")
220
+ frame = df.loc[:, x_columns + y_columns].apply(pd.to_numeric, errors="coerce").dropna()
221
+ if len(frame) < 3:
222
+ raise ValueError("At least three complete rows are required.")
223
+ components = min(len(x_columns), len(y_columns))
224
+ model = CCA(n_components=components)
225
+ model.fit(frame[x_columns], frame[y_columns])
226
+ x_scores, y_scores = model.transform(frame[x_columns], frame[y_columns])
227
+ correlations = [float(np.corrcoef(x_scores[:, i], y_scores[:, i])[0, 1]) for i in range(components)]
228
+ table = pd.DataFrame({"Canonical Variate": [f"CV{i + 1}" for i in range(components)], "Correlation": correlations})
229
+ weights_x = pd.DataFrame(model.x_weights_, index=x_columns, columns=[f"X{i + 1}" for i in range(components)]).reset_index().rename(columns={"index": "Variable"})
230
+ weights_y = pd.DataFrame(model.y_weights_, index=y_columns, columns=[f"Y{i + 1}" for i in range(components)]).reset_index().rename(columns={"index": "Variable"})
231
+ result = AnalysisResult(title="Canonical Correlation Analysis", analysis_type="canonical_correlation", params={"x_columns": x_columns, "y_columns": y_columns, "components": components})
232
+ result.add_table("Canonical Correlations", table)
233
+ result.add_table("X Weights", weights_x)
234
+ result.add_table("Y Weights", weights_y)
235
+ result.add_model("canonical", model)
236
+ result.summary = f"First canonical correlation = {correlations[0]:.4f}; N = {len(frame)}."
237
+ return result
238
+
239
+
240
+ def factor_analysis(
241
+ df: pd.DataFrame,
242
+ columns: Sequence[str] | None = None,
243
+ n_factors: int = 2,
244
+ rotation: str = "varimax",
245
+ ) -> AnalysisResult:
246
+ if columns is None:
247
+ columns = numeric_columns(df)
248
+ frame, matrix = _numeric_matrix(df, columns)
249
+ matrix = StandardScaler().fit_transform(matrix)
250
+ model = FactorAnalysis(n_components=n_factors, rotation=rotation, random_state=42)
251
+ model.fit(matrix)
252
+ loadings = pd.DataFrame(
253
+ model.components_.T,
254
+ index=columns,
255
+ columns=[f"Factor {i + 1}" for i in range(n_factors)],
256
+ )
257
+ scores = pd.DataFrame(model.transform(matrix), columns=[f"Factor {i + 1}" for i in range(n_factors)])
258
+ result = AnalysisResult(
259
+ title="Factor Analysis",
260
+ analysis_type="factor_analysis",
261
+ params={"columns": list(columns), "n_factors": n_factors, "rotation": rotation},
262
+ )
263
+ result.add_table("Loadings", loadings.reset_index().rename(columns={"index": "Variable"}))
264
+ result.add_table("Factor Scores (first rows)", scores.head(100))
265
+ result.summary = f"Extracted {n_factors} factors from {len(columns)} variables ({len(frame)} rows)."
266
+ return result
267
+
268
+
269
+ def manova(df: pd.DataFrame, responses: Sequence[str], factor: str) -> AnalysisResult:
270
+ try:
271
+ from statsmodels.multivariate.manova import MANOVA
272
+ except Exception as exc:
273
+ raise ValueError(f"MANOVA is unavailable: {exc}") from exc
274
+ if not responses:
275
+ raise ValueError("Choose at least one response.")
276
+ frame = df.loc[:, list(responses) + [factor]].dropna()
277
+ response_terms = " + ".join(f'Q("{r}")' for r in responses)
278
+ formula = f"{response_terms} ~ C(Q(\"{factor}\"))"
279
+ try:
280
+ model = MANOVA.from_formula(formula, data=frame)
281
+ fit = model.mv_test()
282
+ except Exception as exc:
283
+ raise ValueError(f"MANOVA failed: {exc}") from exc
284
+ result = AnalysisResult(
285
+ title="Multivariate Analysis of Variance",
286
+ analysis_type="manova",
287
+ params={"responses": list(responses), "factor": factor},
288
+ )
289
+ try:
290
+ summary = fit.summary()
291
+ frames = []
292
+ for table in summary.tables:
293
+ if not isinstance(table, pd.DataFrame) or table.shape[1] < 5:
294
+ continue
295
+ frame = table.copy()
296
+ term = str(frame.columns[0])
297
+ frame.insert(0, "Term", term)
298
+ frame = frame.reset_index().rename(columns={"index": "Test"})
299
+ frames.append(frame)
300
+ if frames:
301
+ result.add_table("MANOVA Tests", pd.concat(frames, ignore_index=True))
302
+ else:
303
+ result.add_table("MANOVA Summary", pd.DataFrame([{"Summary": str(fit)}]))
304
+ except Exception:
305
+ result.add_table("MANOVA Summary", pd.DataFrame([{"Summary": str(fit)}]))
306
+ result.summary = f"MANOVA for {', '.join(responses)} by {factor}; N = {len(frame)}."
307
+ return result
@@ -0,0 +1,264 @@
1
+ from __future__ import annotations
2
+
3
+ import itertools
4
+ import math
5
+ from typing import Sequence
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+
10
+ from statstudio.core.table import DataTable
11
+ from statstudio.stats.common import display_formula
12
+ from statstudio.stats.results import AnalysisResult
13
+ from statstudio.stats.doe import Factor
14
+
15
+
16
+ def _model_matrix(coded: np.ndarray) -> np.ndarray:
17
+ columns = [np.ones(len(coded))]
18
+ columns.extend(coded[:, index] for index in range(coded.shape[1]))
19
+ if coded.shape[1] >= 2:
20
+ for first, second in itertools.combinations(range(coded.shape[1]), 2):
21
+ columns.append(coded[:, first] * coded[:, second])
22
+ return np.column_stack(columns)
23
+
24
+
25
+ def _d_efficiency(coded: np.ndarray) -> float:
26
+ matrix = _model_matrix(coded)
27
+ try:
28
+ sign, logdet = np.linalg.slogdet(matrix.T @ matrix)
29
+ except Exception:
30
+ return -np.inf
31
+ if sign <= 0:
32
+ return -np.inf
33
+ return float(100.0 * np.exp(logdet / matrix.shape[1]) / len(coded))
34
+
35
+
36
+ def _criterion_score(coded: np.ndarray, criterion: str, moment: np.ndarray) -> float:
37
+ if len(np.unique(coded, axis=0)) < len(coded):
38
+ return -np.inf
39
+ matrix = _model_matrix(coded)
40
+ gram = matrix.T @ matrix
41
+ try:
42
+ sign, logdet = np.linalg.slogdet(gram)
43
+ except Exception:
44
+ return -np.inf
45
+ if sign <= 0 or not np.isfinite(logdet):
46
+ return -np.inf
47
+ try:
48
+ if int(np.linalg.matrix_rank(gram)) < gram.shape[0]:
49
+ return -np.inf
50
+ inverse = np.linalg.inv(gram)
51
+ except Exception:
52
+ return -np.inf
53
+ if criterion == "D":
54
+ return float(logdet)
55
+ if criterion == "A":
56
+ return -float(np.trace(inverse))
57
+ return -float(np.trace(moment @ inverse))
58
+
59
+
60
+ def _criterion_metadata(coded: np.ndarray, criterion: str, moment: np.ndarray) -> dict:
61
+ matrix = _model_matrix(coded)
62
+ gram = matrix.T @ matrix
63
+ inverse = np.linalg.inv(gram)
64
+ return {
65
+ "criterion": criterion,
66
+ "d_efficiency": _d_efficiency(coded),
67
+ "a_criterion": float(np.trace(inverse)),
68
+ "i_criterion": float(np.trace(moment @ inverse)),
69
+ "rank": int(np.linalg.matrix_rank(matrix)),
70
+ "condition_number": float(np.linalg.cond(gram)),
71
+ }
72
+
73
+
74
+ def optimal_design(
75
+ factors: Sequence[Factor],
76
+ runs: int | None = None,
77
+ criterion: str = "D",
78
+ starts: int = 20,
79
+ seed: int = 42,
80
+ exact: bool | None = None,
81
+ ) -> DataTable:
82
+ if not factors:
83
+ raise ValueError("At least one factor is required.")
84
+ k = len(factors)
85
+ candidate_levels = [-1.0, 0.0, 1.0]
86
+ candidates = np.array(list(itertools.product(candidate_levels, repeat=k)), dtype=float)
87
+ runs = int(runs or min(len(candidates), 2 ** k + 2 * k + max(2, k)))
88
+ runs = max(k + 2, min(runs, len(candidates)))
89
+ criterion = criterion.upper()
90
+ if criterion not in {"D", "A", "I"}:
91
+ raise ValueError("Criterion must be D, A, or I.")
92
+ candidate_matrix = _model_matrix(candidates)
93
+ moment = candidate_matrix.T @ candidate_matrix / max(1, len(candidate_matrix))
94
+ rng = np.random.default_rng(seed)
95
+ best_design = None
96
+ best_score = -np.inf
97
+ combination_count = math.comb(len(candidates), runs)
98
+ use_exact = combination_count <= 200_000 if exact is None else exact
99
+ search_method = "exact" if use_exact else "coordinate-exchange"
100
+ if use_exact:
101
+ for indices in itertools.combinations(range(len(candidates)), runs):
102
+ design = candidates[list(indices)].copy()
103
+ score = _criterion_score(design, criterion, moment)
104
+ if score > best_score:
105
+ best_score = score
106
+ best_design = design
107
+ else:
108
+ for _ in range(max(1, starts)):
109
+ indices = rng.choice(len(candidates), size=runs, replace=False)
110
+ design = candidates[indices].copy()
111
+ score = _criterion_score(design, criterion, moment)
112
+ improved = True
113
+ while improved:
114
+ improved = False
115
+ for row in range(runs):
116
+ current = design[row].copy()
117
+ for candidate in candidates:
118
+ if np.array_equal(candidate, current):
119
+ continue
120
+ trial = design.copy()
121
+ trial[row] = candidate
122
+ trial_score = _criterion_score(trial, criterion, moment)
123
+ if trial_score > score + 1e-12:
124
+ design = trial
125
+ score = trial_score
126
+ current = candidate.copy()
127
+ improved = True
128
+ if score > best_score:
129
+ best_score = score
130
+ best_design = design
131
+ if best_design is None:
132
+ raise ValueError("Could not construct an optimal design.")
133
+ if len(np.unique(best_design, axis=0)) < runs:
134
+ raise ValueError("The optimal design contains duplicate rows.")
135
+ metrics = _criterion_metadata(best_design, criterion, moment)
136
+ if metrics["rank"] < _model_matrix(best_design).shape[1]:
137
+ raise ValueError("The optimal design is rank deficient; increase the number of runs.")
138
+ frame = pd.DataFrame({
139
+ "Std Order": np.arange(1, runs + 1),
140
+ "Run Order": rng.permutation(np.arange(1, runs + 1)),
141
+ "Replicate": 1,
142
+ "Point Type": "Optimal",
143
+ })
144
+ for index, factor in enumerate(factors):
145
+ frame[factor.name] = [factor.actual(float(value)) for value in best_design[:, index]]
146
+ table = DataTable(
147
+ frame,
148
+ name=f"{criterion.upper()}-Optimal Design",
149
+ source="Optimal DOE",
150
+ metadata={
151
+ "design": {
152
+ "design_type": f"{criterion}-Optimal",
153
+ "factors": [factor.to_dict() for factor in factors],
154
+ "generators": [],
155
+ "resolution": "",
156
+ "replicate": 1,
157
+ "center_points": 0,
158
+ "randomize": True,
159
+ "seed": seed,
160
+ "notes": f"{criterion}-optimal coordinate-exchange design.",
161
+ **metrics,
162
+ "score": best_score,
163
+ "search": search_method,
164
+ }
165
+ },
166
+ )
167
+ for factor in factors:
168
+ if factor.name in table.specs:
169
+ table.specs[factor.name].units = factor.units
170
+ table.specs[factor.name].modeling_type = "continuous"
171
+ return table
172
+
173
+
174
+ def mixture_design(
175
+ components: Sequence[str],
176
+ levels: int = 3,
177
+ total: float = 1.0,
178
+ seed: int = 42,
179
+ ) -> DataTable:
180
+ components = [str(name) for name in components]
181
+ if len(components) < 2:
182
+ raise ValueError("At least two mixture components are required.")
183
+ if levels < 2 or levels > 6:
184
+ raise ValueError("Mixture levels must be between 2 and 6.")
185
+ step_count = levels - 1
186
+ rows = []
187
+ for composition in itertools.product(range(step_count + 1), repeat=len(components)):
188
+ if sum(composition) != step_count:
189
+ continue
190
+ rows.append({name: total * value / step_count for name, value in zip(components, composition)})
191
+ rng = np.random.default_rng(seed)
192
+ order = rng.permutation(len(rows))
193
+ frame = pd.DataFrame(rows).iloc[order].reset_index(drop=True)
194
+ frame.insert(0, "Point Type", "Mixture")
195
+ frame.insert(0, "Replicate", 1)
196
+ frame.insert(0, "Run Order", np.arange(1, len(frame) + 1))
197
+ frame.insert(0, "Std Order", np.arange(1, len(frame) + 1))
198
+ table = DataTable(
199
+ frame,
200
+ name="Mixture Design",
201
+ source="Mixture DOE",
202
+ metadata={
203
+ "design": {
204
+ "design_type": "Mixture",
205
+ "mixture": True,
206
+ "components": components,
207
+ "factors": [{"name": name, "low": 0.0, "high": total, "units": ""} for name in components],
208
+ "generators": [],
209
+ "resolution": "",
210
+ "replicate": 1,
211
+ "center_points": 0,
212
+ "randomize": True,
213
+ "seed": seed,
214
+ "notes": f"Simplex lattice mixture design with {levels} levels.",
215
+ }
216
+ },
217
+ )
218
+ for name in components:
219
+ if name in table.specs:
220
+ table.specs[name].modeling_type = "continuous"
221
+ return table
222
+
223
+
224
+ def analyze_mixture(table: DataTable, response: str, order: int = 1) -> AnalysisResult:
225
+ import statsmodels.formula.api as smf
226
+
227
+ info = table.metadata.get("design") or {}
228
+ components = info.get("components") or [item.get("name") for item in info.get("factors", [])]
229
+ components = [str(name) for name in components if name]
230
+ if len(components) < 2:
231
+ raise ValueError("This table has no mixture component metadata.")
232
+ frame = table.analysis_df()
233
+ if response not in frame.columns:
234
+ raise KeyError(response)
235
+ data = frame.loc[:, components + [response]].apply(pd.to_numeric, errors="coerce").dropna()
236
+ terms = [f'Q("{name}")' for name in components]
237
+ if order >= 2:
238
+ terms.extend(f'Q("{first}"):Q("{second}")' for first, second in itertools.combinations(components, 2))
239
+ formula = f'Q("{response}") ~ -1 + ' + " + ".join(terms)
240
+ model = smf.ols(formula, data=data).fit()
241
+ result = AnalysisResult(
242
+ title=f"Mixture Analysis: {response}",
243
+ analysis_type="mixture_analysis",
244
+ params={"response": response, "components": components, "order": order},
245
+ source_table=table.name,
246
+ )
247
+ result.add_table("Mixture Coefficients", pd.DataFrame({
248
+ "Term": [display_formula(name) for name in model.params.index],
249
+ "Estimate": model.params.to_numpy(),
250
+ "Std Error": model.bse.to_numpy(),
251
+ "t": model.tvalues.to_numpy(),
252
+ "p-value": model.pvalues.to_numpy(),
253
+ }))
254
+ result.add_table("Model Metrics", pd.DataFrame([{
255
+ "Runs": len(data),
256
+ "Components": len(components),
257
+ "R-squared": model.rsquared,
258
+ "Adjusted R-squared": model.rsquared_adj,
259
+ "AIC": model.aic,
260
+ "BIC": model.bic,
261
+ }]))
262
+ result.add_model("mixture_model", model)
263
+ result.summary = f"Scheffe mixture model for {response} with R² = {model.rsquared:.4f} over {len(data)} runs."
264
+ return result