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.
- statstudio/__init__.py +9 -0
- statstudio/__main__.py +3 -0
- statstudio/app.py +83 -0
- statstudio/cli.py +116 -0
- statstudio/core/__init__.py +3 -0
- statstudio/core/archive.py +27 -0
- statstudio/core/commands.py +67 -0
- statstudio/core/formula_catalog.py +74 -0
- statstudio/core/formulas.py +605 -0
- statstudio/core/joins.py +123 -0
- statstudio/core/project.py +358 -0
- statstudio/core/runtime.py +321 -0
- statstudio/core/scripting.py +594 -0
- statstudio/core/table.py +796 -0
- statstudio/core/transform.py +450 -0
- statstudio/feature_help.py +595 -0
- statstudio/io/__init__.py +3 -0
- statstudio/io/docx.py +201 -0
- statstudio/io/export.py +99 -0
- statstudio/io/file_import.py +199 -0
- statstudio/io/odbc.py +334 -0
- statstudio/io/sample_data.py +164 -0
- statstudio/io/table_io.py +118 -0
- statstudio/plots/__init__.py +19 -0
- statstudio/plots/advanced.py +651 -0
- statstudio/plots/basic.py +957 -0
- statstudio/plots/bayesian_plots.py +94 -0
- statstudio/plots/common.py +334 -0
- statstudio/plots/diagnostics.py +214 -0
- statstudio/plots/doe_plots.py +235 -0
- statstudio/plots/plotly_builders.py +719 -0
- statstudio/plots/predictive_plots.py +72 -0
- statstudio/plots/registry.py +251 -0
- statstudio/plugins.py +111 -0
- statstudio/resources/help_topics.json +13195 -0
- statstudio/resources/logo.ico +0 -0
- statstudio/resources/logo.png +0 -0
- statstudio/resources/statstudio.svg +8 -0
- statstudio/stats/__init__.py +42 -0
- statstudio/stats/bayesian.py +1094 -0
- statstudio/stats/bayesian_optimization.py +590 -0
- statstudio/stats/common.py +140 -0
- statstudio/stats/correlation.py +135 -0
- statstudio/stats/custom_doe.py +1714 -0
- statstudio/stats/descriptive.py +200 -0
- statstudio/stats/desirability.py +132 -0
- statstudio/stats/distributions.py +331 -0
- statstudio/stats/doe.py +1070 -0
- statstudio/stats/hypothesis.py +1305 -0
- statstudio/stats/multivariate.py +307 -0
- statstudio/stats/optimal_doe.py +264 -0
- statstudio/stats/power.py +194 -0
- statstudio/stats/predictive.py +605 -0
- statstudio/stats/profiler.py +379 -0
- statstudio/stats/quality.py +1218 -0
- statstudio/stats/regression.py +1600 -0
- statstudio/stats/results.py +235 -0
- statstudio/stats/simulator.py +95 -0
- statstudio/stats/survival.py +637 -0
- statstudio/stats/timeseries.py +643 -0
- statstudio/stats/tolerance.py +154 -0
- statstudio/ui/__init__.py +0 -0
- statstudio/ui/analysis_hub.py +271 -0
- statstudio/ui/command_catalog.py +460 -0
- statstudio/ui/command_palette.py +55 -0
- statstudio/ui/console.py +239 -0
- statstudio/ui/dialogs/__init__.py +0 -0
- statstudio/ui/dialogs/advanced_dialogs.py +392 -0
- statstudio/ui/dialogs/base.py +537 -0
- statstudio/ui/dialogs/bayesian_dialogs.py +488 -0
- statstudio/ui/dialogs/bayesian_optimization_dialog.py +299 -0
- statstudio/ui/dialogs/custom_doe_dialog.py +467 -0
- statstudio/ui/dialogs/doe_dialogs.py +220 -0
- statstudio/ui/dialogs/extended_dialogs.py +665 -0
- statstudio/ui/dialogs/graph_builder.py +139 -0
- statstudio/ui/dialogs/help_dialog.py +207 -0
- statstudio/ui/dialogs/help_topics.py +280 -0
- statstudio/ui/dialogs/lazy.py +184 -0
- statstudio/ui/dialogs/odbc_dialog.py +311 -0
- statstudio/ui/dialogs/plot_dialog.py +1385 -0
- statstudio/ui/dialogs/report_composer.py +218 -0
- statstudio/ui/dialogs/script_dialogs.py +267 -0
- statstudio/ui/dialogs/stats_dialogs.py +1688 -0
- statstudio/ui/dialogs/table_dialogs.py +997 -0
- statstudio/ui/dialogs/window.py +58 -0
- statstudio/ui/docks/__init__.py +0 -0
- statstudio/ui/formula_editor.py +121 -0
- statstudio/ui/icons.py +257 -0
- statstudio/ui/jobs.py +179 -0
- statstudio/ui/main_window.py +3934 -0
- statstudio/ui/plot_interaction.py +178 -0
- statstudio/ui/profiler_widget.py +437 -0
- statstudio/ui/recent.py +82 -0
- statstudio/ui/reports/__init__.py +0 -0
- statstudio/ui/reports/report_view.py +1632 -0
- statstudio/ui/script_jobs.py +35 -0
- statstudio/ui/scripts_panel.py +271 -0
- statstudio/ui/table_document.py +233 -0
- statstudio/ui/table_model.py +285 -0
- statstudio/ui/table_view.py +285 -0
- statstudio/ui/theme.py +645 -0
- statstudio/ui/welcome.py +453 -0
- statstudio/ui/window_controls.py +53 -0
- statstudio/ui/workers.py +53 -0
- statstudio-0.1.0.dist-info/METADATA +261 -0
- statstudio-0.1.0.dist-info/RECORD +110 -0
- statstudio-0.1.0.dist-info/WHEEL +5 -0
- statstudio-0.1.0.dist-info/entry_points.txt +5 -0
- statstudio-0.1.0.dist-info/licenses/LICENSE +674 -0
- statstudio-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1600 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from itertools import combinations
|
|
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
|
|
13
|
+
from scipy.optimize import minimize
|
|
14
|
+
from statsmodels.stats.anova import anova_lm
|
|
15
|
+
from statsmodels.stats.diagnostic import het_breuschpagan
|
|
16
|
+
from statsmodels.stats.outliers_influence import variance_inflation_factor
|
|
17
|
+
|
|
18
|
+
from statstudio.stats.common import display_formula, p_stars
|
|
19
|
+
from statstudio.stats.desirability import desirability_score, overall_desirability
|
|
20
|
+
from statstudio.stats.profiler import ProfilerFactor, ProfilerSession
|
|
21
|
+
from statstudio.stats.results import AnalysisResult
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class FittedRegression:
|
|
26
|
+
model: Any
|
|
27
|
+
frame: pd.DataFrame
|
|
28
|
+
response: str
|
|
29
|
+
predictors: list[str]
|
|
30
|
+
kind: str = "linear"
|
|
31
|
+
label: str = "Predicted"
|
|
32
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _term(name: str, df: pd.DataFrame) -> str:
|
|
36
|
+
if name not in df.columns:
|
|
37
|
+
raise KeyError(name)
|
|
38
|
+
if pd.api.types.is_numeric_dtype(df[name]) and not pd.api.types.is_bool_dtype(df[name]):
|
|
39
|
+
return f'Q("{name}")'
|
|
40
|
+
return f'C(Q("{name}"))'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _formula(response: str, predictors: Sequence[str], frame: pd.DataFrame, interactions: bool) -> str:
|
|
44
|
+
terms = [_term(p, frame) for p in predictors]
|
|
45
|
+
if interactions and len(terms) > 1:
|
|
46
|
+
for first, second in combinations(terms, 2):
|
|
47
|
+
terms.append(f"{first}:{second}")
|
|
48
|
+
right = " + ".join(terms) if terms else "1"
|
|
49
|
+
return f'{_term(response, frame)} ~ {right}'
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _clean(df: pd.DataFrame, response: str, predictors: Sequence[str]) -> pd.DataFrame:
|
|
53
|
+
columns = [response] + [p for p in predictors if p != response]
|
|
54
|
+
missing = [c for c in columns if c not in df.columns]
|
|
55
|
+
if missing:
|
|
56
|
+
raise KeyError(f"Missing columns: {', '.join(missing)}")
|
|
57
|
+
frame = df.loc[:, columns].copy()
|
|
58
|
+
frame[response] = pd.to_numeric(frame[response], errors="coerce")
|
|
59
|
+
return frame.dropna()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _coefficient_table(result, exponential: bool = False) -> pd.DataFrame:
|
|
63
|
+
conf = np.asarray(result.conf_int())
|
|
64
|
+
parameters = np.asarray(result.params)
|
|
65
|
+
names = list(getattr(result.params, "index", getattr(result.model, "exog_names", range(len(parameters)))))
|
|
66
|
+
frame = pd.DataFrame(
|
|
67
|
+
{
|
|
68
|
+
"Term": [display_formula(name) for name in names],
|
|
69
|
+
"Estimate": parameters,
|
|
70
|
+
"Std Error": np.asarray(result.bse),
|
|
71
|
+
"Statistic": np.asarray(result.tvalues),
|
|
72
|
+
"p-value": np.asarray(result.pvalues),
|
|
73
|
+
"CI Low": conf[:, 0],
|
|
74
|
+
"CI High": conf[:, 1],
|
|
75
|
+
}
|
|
76
|
+
)
|
|
77
|
+
frame["Significance"] = frame["p-value"].map(p_stars)
|
|
78
|
+
if exponential:
|
|
79
|
+
frame["Odds Ratio"] = np.exp(frame["Estimate"])
|
|
80
|
+
frame["OR CI Low"] = np.exp(frame["CI Low"])
|
|
81
|
+
frame["OR CI High"] = np.exp(frame["CI High"])
|
|
82
|
+
frame = frame.rename(columns={"Statistic": "z"})
|
|
83
|
+
else:
|
|
84
|
+
frame = frame.rename(columns={"Statistic": "t"})
|
|
85
|
+
return frame
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _metrics(result, response: str, frame: pd.DataFrame, model_name: str) -> pd.DataFrame:
|
|
89
|
+
n = int(getattr(result, "nobs", len(frame)))
|
|
90
|
+
aic = float(getattr(result, "aic", np.nan))
|
|
91
|
+
bic = float(getattr(result, "bic", np.nan))
|
|
92
|
+
aicc = np.nan
|
|
93
|
+
if model_name.startswith(("OLS", "Polynomial")):
|
|
94
|
+
parameters = len(np.asarray(result.params)) + 1
|
|
95
|
+
aic += 2.0
|
|
96
|
+
if n > 0:
|
|
97
|
+
bic += math.log(n)
|
|
98
|
+
denominator = n - parameters - 1
|
|
99
|
+
if denominator > 0:
|
|
100
|
+
aicc = aic + (2.0 * parameters * (parameters + 1) / denominator)
|
|
101
|
+
rows = [
|
|
102
|
+
("Model", model_name),
|
|
103
|
+
("N", n),
|
|
104
|
+
("R-squared", getattr(result, "rsquared", np.nan)),
|
|
105
|
+
("Adjusted R-squared", getattr(result, "rsquared_adj", np.nan)),
|
|
106
|
+
("F statistic", getattr(result, "fvalue", np.nan)),
|
|
107
|
+
("Model p-value", getattr(result, "f_pvalue", np.nan)),
|
|
108
|
+
("AIC", aic),
|
|
109
|
+
("AICc", aicc),
|
|
110
|
+
("BIC", bic),
|
|
111
|
+
("Log likelihood", getattr(result, "llf", np.nan)),
|
|
112
|
+
]
|
|
113
|
+
if hasattr(result, "mse_resid"):
|
|
114
|
+
rows.append(("Residual std error", float(np.sqrt(result.mse_resid))))
|
|
115
|
+
return pd.DataFrame(rows, columns=["Metric", "Value"])
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _diagnostics(result, frame: pd.DataFrame, response: str) -> pd.DataFrame:
|
|
119
|
+
residuals = np.asarray(result.resid)
|
|
120
|
+
rows = [
|
|
121
|
+
("Mean residual", float(np.mean(residuals))),
|
|
122
|
+
("Residual std dev", float(np.std(residuals, ddof=1))),
|
|
123
|
+
("Min residual", float(np.min(residuals))),
|
|
124
|
+
("Max residual", float(np.max(residuals))),
|
|
125
|
+
]
|
|
126
|
+
if len(residuals) >= 3:
|
|
127
|
+
rows.append(("Shapiro-Wilk p", float(stats.shapiro(residuals).pvalue)))
|
|
128
|
+
try:
|
|
129
|
+
bp = het_breuschpagan(residuals, result.model.exog)
|
|
130
|
+
rows.append(("Breusch-Pagan p", float(bp[1])))
|
|
131
|
+
except Exception:
|
|
132
|
+
pass
|
|
133
|
+
if len(residuals) >= 8:
|
|
134
|
+
rows.append(("Durbin-Watson", float(sm.stats.stattools.durbin_watson(residuals))))
|
|
135
|
+
return pd.DataFrame(rows, columns=["Diagnostic", "Value"])
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _vif_table(result, predictors: Sequence[str]) -> pd.DataFrame:
|
|
139
|
+
try:
|
|
140
|
+
exog = result.model.exog
|
|
141
|
+
names = result.model.exog_names
|
|
142
|
+
rows = []
|
|
143
|
+
for index, name in enumerate(names):
|
|
144
|
+
if name == "Intercept":
|
|
145
|
+
continue
|
|
146
|
+
try:
|
|
147
|
+
value = variance_inflation_factor(exog, index)
|
|
148
|
+
except Exception:
|
|
149
|
+
value = np.nan
|
|
150
|
+
rows.append({"Term": display_formula(name), "VIF": value})
|
|
151
|
+
return pd.DataFrame(rows)
|
|
152
|
+
except Exception:
|
|
153
|
+
return pd.DataFrame()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _add_regression_plots(result: AnalysisResult, result_fit, frame: pd.DataFrame, response: str) -> None:
|
|
157
|
+
fitted = np.asarray(result_fit.fittedvalues)
|
|
158
|
+
actual = np.asarray(frame[response])
|
|
159
|
+
residuals = np.asarray(result_fit.resid)
|
|
160
|
+
observations = np.arange(1, len(frame) + 1)
|
|
161
|
+
plot_frame = pd.DataFrame({"Fitted": fitted, "Actual": actual, "Residual": residuals, "Observation": observations})
|
|
162
|
+
try:
|
|
163
|
+
influence = result_fit.get_influence()
|
|
164
|
+
leverage_values = np.asarray(influence.hat_matrix_diag)
|
|
165
|
+
cooks = np.asarray(influence.cooks_distance[0])
|
|
166
|
+
studentized = np.asarray(influence.resid_studentized_internal)
|
|
167
|
+
plot_frame["Leverage"] = leverage_values
|
|
168
|
+
plot_frame["Cooks"] = cooks
|
|
169
|
+
plot_frame["StdResidual"] = studentized
|
|
170
|
+
plot_frame["SqrtAbsStdResidual"] = np.sqrt(np.abs(studentized))
|
|
171
|
+
threshold = 4 / max(1, len(frame))
|
|
172
|
+
influential = plot_frame.sort_values("Cooks", ascending=False).head(10)
|
|
173
|
+
result.add_table(
|
|
174
|
+
"Influence Diagnostics",
|
|
175
|
+
influential.loc[:, ["Observation", "Leverage", "Cooks", "StdResidual"]].reset_index(drop=True),
|
|
176
|
+
notes=f"Cook's distance threshold 4/n = {threshold:.4g}. Rows above the threshold may be influential.",
|
|
177
|
+
)
|
|
178
|
+
result.add_plot("residual_order", {}, title="Residuals vs Observation Order", data=plot_frame)
|
|
179
|
+
result.add_plot("scale_location", {}, title="Scale-Location", data=plot_frame)
|
|
180
|
+
result.add_plot("leverage", {"cook_threshold": threshold}, title="Leverage vs Standardized Residuals", data=plot_frame)
|
|
181
|
+
result.add_plot("cooks_distance", {"cook_threshold": threshold}, title="Cook's Distance", data=plot_frame)
|
|
182
|
+
except Exception:
|
|
183
|
+
pass
|
|
184
|
+
result.add_plot("actual_predicted", {"actual": "Actual", "predicted": "Fitted", "identity": True}, title="Actual vs Predicted", data=plot_frame)
|
|
185
|
+
result.add_plot("residual_fitted", {"fitted": "Fitted", "residual": "Residual", "zero": True}, title="Residuals vs Fitted", data=plot_frame)
|
|
186
|
+
result.add_plot("qq", {"column": "Residual"}, title="Normal Q-Q Plot of Residuals", data=plot_frame)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _is_numeric(series: pd.Series) -> bool:
|
|
190
|
+
return pd.api.types.is_numeric_dtype(series) and not pd.api.types.is_bool_dtype(series)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _baseline_value(series: pd.Series) -> Any:
|
|
194
|
+
if _is_numeric(series):
|
|
195
|
+
values = pd.to_numeric(series, errors="coerce").dropna()
|
|
196
|
+
return float(values.median()) if not values.empty else 0.0
|
|
197
|
+
values = series.dropna()
|
|
198
|
+
if values.empty:
|
|
199
|
+
return None
|
|
200
|
+
modes = values.mode(dropna=True)
|
|
201
|
+
return modes.iloc[0] if not modes.empty else values.iloc[0]
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _profiler_session(fitted: FittedRegression, points: int = 9) -> ProfilerSession:
|
|
205
|
+
frame = fitted.frame
|
|
206
|
+
predictors = [name for name in fitted.predictors if name in frame.columns]
|
|
207
|
+
if not predictors:
|
|
208
|
+
raise ValueError("No predictors are available for profiling.")
|
|
209
|
+
base: dict[str, Any] = {}
|
|
210
|
+
factors: list[ProfilerFactor] = []
|
|
211
|
+
for column in frame.columns:
|
|
212
|
+
series = frame[column]
|
|
213
|
+
if column in predictors:
|
|
214
|
+
if _is_numeric(series):
|
|
215
|
+
values = pd.to_numeric(series, errors="coerce").dropna()
|
|
216
|
+
if values.empty:
|
|
217
|
+
continue
|
|
218
|
+
low = float(values.min())
|
|
219
|
+
high = float(values.max())
|
|
220
|
+
initial = float(values.median())
|
|
221
|
+
factors.append(
|
|
222
|
+
ProfilerFactor(
|
|
223
|
+
column,
|
|
224
|
+
"continuous",
|
|
225
|
+
low=low,
|
|
226
|
+
high=high,
|
|
227
|
+
current=initial,
|
|
228
|
+
initial=initial,
|
|
229
|
+
)
|
|
230
|
+
)
|
|
231
|
+
base[column] = initial
|
|
232
|
+
else:
|
|
233
|
+
values = series.dropna()
|
|
234
|
+
if values.empty:
|
|
235
|
+
continue
|
|
236
|
+
try:
|
|
237
|
+
levels = sorted(str(value) for value in pd.unique(values))
|
|
238
|
+
except TypeError:
|
|
239
|
+
levels = sorted((str(value) for value in pd.unique(values)), key=str)
|
|
240
|
+
initial = str(_baseline_value(series))
|
|
241
|
+
if levels and initial not in levels:
|
|
242
|
+
initial = levels[0]
|
|
243
|
+
factors.append(
|
|
244
|
+
ProfilerFactor(
|
|
245
|
+
column,
|
|
246
|
+
"categorical",
|
|
247
|
+
levels=levels,
|
|
248
|
+
current=initial,
|
|
249
|
+
initial=initial,
|
|
250
|
+
)
|
|
251
|
+
)
|
|
252
|
+
base[column] = initial
|
|
253
|
+
else:
|
|
254
|
+
values = series.dropna()
|
|
255
|
+
base[column] = values.iloc[0] if not values.empty else None
|
|
256
|
+
|
|
257
|
+
def predict(settings: dict[str, Any]) -> float:
|
|
258
|
+
row = dict(base)
|
|
259
|
+
row.update(settings)
|
|
260
|
+
predicted = np.asarray(fitted.model.predict(pd.DataFrame([row])), dtype=float).reshape(-1)
|
|
261
|
+
return float(predicted[0])
|
|
262
|
+
|
|
263
|
+
return ProfilerSession(
|
|
264
|
+
response=fitted.response,
|
|
265
|
+
factors=factors,
|
|
266
|
+
predict=predict,
|
|
267
|
+
response_label=fitted.label,
|
|
268
|
+
points=points,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _profile_frame(fitted: FittedRegression, points: int = 9) -> pd.DataFrame:
|
|
273
|
+
frame = fitted.frame
|
|
274
|
+
predictors = [name for name in fitted.predictors if name in frame.columns]
|
|
275
|
+
if not predictors:
|
|
276
|
+
raise ValueError("No predictors are available for profiling.")
|
|
277
|
+
base: dict[str, Any] = {}
|
|
278
|
+
for column in frame.columns:
|
|
279
|
+
series = frame[column]
|
|
280
|
+
if column in predictors:
|
|
281
|
+
base[column] = _baseline_value(series)
|
|
282
|
+
else:
|
|
283
|
+
values = series.dropna()
|
|
284
|
+
base[column] = values.iloc[0] if not values.empty else None
|
|
285
|
+
rows: list[dict[str, Any]] = []
|
|
286
|
+
for factor in predictors:
|
|
287
|
+
series = frame[factor]
|
|
288
|
+
if _is_numeric(series):
|
|
289
|
+
values = pd.to_numeric(series, errors="coerce").dropna()
|
|
290
|
+
if values.empty:
|
|
291
|
+
continue
|
|
292
|
+
low = float(values.min())
|
|
293
|
+
high = float(values.max())
|
|
294
|
+
grid = np.linspace(low, high, max(3, int(points))) if low != high else np.array([low])
|
|
295
|
+
for value in grid:
|
|
296
|
+
settings = dict(base)
|
|
297
|
+
settings[factor] = float(value)
|
|
298
|
+
rows.append(
|
|
299
|
+
{
|
|
300
|
+
"Factor": factor,
|
|
301
|
+
"Level": float(value),
|
|
302
|
+
"Level Label": f"{float(value):.6g}",
|
|
303
|
+
"Categorical": False,
|
|
304
|
+
"Predicted": np.nan,
|
|
305
|
+
"_settings": settings,
|
|
306
|
+
}
|
|
307
|
+
)
|
|
308
|
+
else:
|
|
309
|
+
levels = pd.unique(series.dropna())
|
|
310
|
+
if len(levels) == 0:
|
|
311
|
+
continue
|
|
312
|
+
try:
|
|
313
|
+
levels = sorted(levels)
|
|
314
|
+
except TypeError:
|
|
315
|
+
levels = sorted(levels, key=str)
|
|
316
|
+
for index, value in enumerate(levels):
|
|
317
|
+
settings = dict(base)
|
|
318
|
+
settings[factor] = value
|
|
319
|
+
rows.append(
|
|
320
|
+
{
|
|
321
|
+
"Factor": factor,
|
|
322
|
+
"Level": float(index),
|
|
323
|
+
"Level Label": str(value),
|
|
324
|
+
"Categorical": True,
|
|
325
|
+
"Predicted": np.nan,
|
|
326
|
+
"_settings": settings,
|
|
327
|
+
}
|
|
328
|
+
)
|
|
329
|
+
columns = ["Factor", "Level", "Level Label", "Categorical", "Predicted"]
|
|
330
|
+
if not rows:
|
|
331
|
+
return pd.DataFrame(columns=columns)
|
|
332
|
+
profiler = pd.DataFrame(rows)
|
|
333
|
+
settings_frame = pd.DataFrame(list(profiler.pop("_settings")))
|
|
334
|
+
try:
|
|
335
|
+
predicted = np.asarray(fitted.model.predict(settings_frame), dtype=float).reshape(-1)
|
|
336
|
+
except Exception as exc:
|
|
337
|
+
raise ValueError(f"Prediction failed: {exc}") from exc
|
|
338
|
+
profiler["Predicted"] = predicted[: len(profiler)]
|
|
339
|
+
return profiler.loc[:, columns]
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _attach_prediction_profiler(result: AnalysisResult, fitted: FittedRegression, points: int = 9) -> None:
|
|
343
|
+
result.add_model("regression", fitted)
|
|
344
|
+
if any(plot.kind == "profiler" for plot in result.plots):
|
|
345
|
+
return
|
|
346
|
+
try:
|
|
347
|
+
profiler = _profile_frame(fitted, points)
|
|
348
|
+
except Exception as exc:
|
|
349
|
+
message = f"Prediction profiler unavailable: {exc}"
|
|
350
|
+
result.notes = f"{result.notes} {message}".strip()
|
|
351
|
+
return
|
|
352
|
+
if profiler.empty:
|
|
353
|
+
return
|
|
354
|
+
result.add_table("Profiler Grid", profiler)
|
|
355
|
+
result.add_plot(
|
|
356
|
+
"profiler",
|
|
357
|
+
{
|
|
358
|
+
"factor": "Factor",
|
|
359
|
+
"level": "Level",
|
|
360
|
+
"label": "Level Label",
|
|
361
|
+
"categorical": "Categorical",
|
|
362
|
+
"predicted": "Predicted",
|
|
363
|
+
"y_label": fitted.label,
|
|
364
|
+
"x_label": "",
|
|
365
|
+
},
|
|
366
|
+
title="Prediction Profiler",
|
|
367
|
+
data=profiler,
|
|
368
|
+
)
|
|
369
|
+
try:
|
|
370
|
+
result.profiler_session = _profiler_session(fitted, points)
|
|
371
|
+
except Exception:
|
|
372
|
+
result.profiler_session = None
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def profile_result(fitted: FittedRegression, points: int = 9, params: dict[str, Any] | None = None) -> AnalysisResult:
|
|
376
|
+
profiler = _profile_frame(fitted, points)
|
|
377
|
+
result = AnalysisResult(
|
|
378
|
+
title=f"Prediction Profiler: {fitted.response}",
|
|
379
|
+
analysis_type="regression_prediction_profiler",
|
|
380
|
+
params=dict(params or {}),
|
|
381
|
+
)
|
|
382
|
+
result.params.setdefault("response", fitted.response)
|
|
383
|
+
result.params["points"] = int(points)
|
|
384
|
+
result.add_table("Profiler Grid", profiler)
|
|
385
|
+
result.add_plot(
|
|
386
|
+
"profiler",
|
|
387
|
+
{
|
|
388
|
+
"factor": "Factor",
|
|
389
|
+
"level": "Level",
|
|
390
|
+
"label": "Level Label",
|
|
391
|
+
"categorical": "Categorical",
|
|
392
|
+
"predicted": "Predicted",
|
|
393
|
+
"y_label": fitted.label,
|
|
394
|
+
"x_label": "",
|
|
395
|
+
},
|
|
396
|
+
title="Prediction Profiler",
|
|
397
|
+
data=profiler,
|
|
398
|
+
)
|
|
399
|
+
result.add_model("regression", fitted)
|
|
400
|
+
try:
|
|
401
|
+
result.profiler_session = _profiler_session(fitted, points)
|
|
402
|
+
except Exception:
|
|
403
|
+
result.profiler_session = None
|
|
404
|
+
result.summary = (
|
|
405
|
+
f"Prediction profiler for {fitted.response} across {len(fitted.predictors)} predictor(s), "
|
|
406
|
+
"holding other predictors at their baseline."
|
|
407
|
+
)
|
|
408
|
+
return result
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def linear_regression(
|
|
412
|
+
df: pd.DataFrame,
|
|
413
|
+
response: str,
|
|
414
|
+
predictors: Sequence[str],
|
|
415
|
+
interactions: bool = False,
|
|
416
|
+
robust: bool = False,
|
|
417
|
+
weight: str | None = None,
|
|
418
|
+
test_size: float = 0.0,
|
|
419
|
+
) -> AnalysisResult:
|
|
420
|
+
if not predictors:
|
|
421
|
+
raise ValueError("Choose at least one predictor.")
|
|
422
|
+
columns = [response] + [p for p in predictors if p != response] + ([weight] if weight else [])
|
|
423
|
+
frame = _clean(df, response, columns)
|
|
424
|
+
if len(frame) <= len(predictors) + 1:
|
|
425
|
+
raise ValueError("Not enough complete observations for the model.")
|
|
426
|
+
if weight:
|
|
427
|
+
frame[weight] = pd.to_numeric(frame[weight], errors="coerce")
|
|
428
|
+
frame = frame.dropna(subset=[weight])
|
|
429
|
+
if (frame[weight] < 0).any():
|
|
430
|
+
raise ValueError("Weights cannot be negative.")
|
|
431
|
+
formula = _formula(response, predictors, frame, interactions)
|
|
432
|
+
model = smf.wls(formula, data=frame, weights=frame[weight]).fit() if weight else smf.ols(formula, data=frame).fit()
|
|
433
|
+
result_fit = model.get_robustcov_results(cov_type="HC3") if robust else model
|
|
434
|
+
result = AnalysisResult(
|
|
435
|
+
title=f"Linear Regression: {response}",
|
|
436
|
+
analysis_type="linear_regression",
|
|
437
|
+
params={"response": response, "predictors": list(predictors), "interactions": interactions, "robust": robust, "formula": formula, "weight": weight, "test_size": test_size},
|
|
438
|
+
)
|
|
439
|
+
result.add_table("Coefficients", _coefficient_table(result_fit))
|
|
440
|
+
result.add_table("Model Metrics", _metrics(result_fit, response, frame, "OLS" + (" (robust HC3)" if robust else "")))
|
|
441
|
+
try:
|
|
442
|
+
anova = anova_lm(model, typ=2).reset_index().rename(columns={"index": "Source"})
|
|
443
|
+
anova["Source"] = anova["Source"].map(display_formula)
|
|
444
|
+
result.add_table("ANOVA", anova)
|
|
445
|
+
except Exception:
|
|
446
|
+
pass
|
|
447
|
+
diagnostics = _diagnostics(model, frame, response)
|
|
448
|
+
try:
|
|
449
|
+
influence = model.get_influence()
|
|
450
|
+
press_residuals = np.asarray(influence.resid_press)
|
|
451
|
+
diagnostics_rows = diagnostics.to_dict("records")
|
|
452
|
+
diagnostics_rows.append({"Diagnostic": "PRESS", "Value": float(np.sum(press_residuals**2))})
|
|
453
|
+
diagnostics = pd.DataFrame(diagnostics_rows)
|
|
454
|
+
except Exception:
|
|
455
|
+
pass
|
|
456
|
+
result.add_table("Diagnostics", diagnostics)
|
|
457
|
+
if test_size and 0 < test_size < 1 and len(frame) >= 12:
|
|
458
|
+
split = max(2, min(len(frame) - 2, int(round(len(frame) * (1 - test_size)))))
|
|
459
|
+
train = frame.iloc[:split]
|
|
460
|
+
test = frame.iloc[split:]
|
|
461
|
+
try:
|
|
462
|
+
holdout = smf.wls(formula, data=train, weights=train[weight]).fit() if weight else smf.ols(formula, data=train).fit()
|
|
463
|
+
predicted = np.asarray(holdout.predict(test))
|
|
464
|
+
actual = np.asarray(test[response], dtype=float)
|
|
465
|
+
ss_res = float(np.sum((actual - predicted) ** 2))
|
|
466
|
+
ss_tot = float(np.sum((actual - actual.mean()) ** 2))
|
|
467
|
+
result.add_table("Holdout Validation", pd.DataFrame([{
|
|
468
|
+
"Train N": len(train), "Test N": len(test), "Holdout R-squared": 1 - ss_res / ss_tot if ss_tot else np.nan,
|
|
469
|
+
"Holdout RMSE": math.sqrt(ss_res / max(1, len(test))), "Holdout MAE": float(np.mean(np.abs(actual - predicted))),
|
|
470
|
+
}]))
|
|
471
|
+
except Exception:
|
|
472
|
+
pass
|
|
473
|
+
vif = _vif_table(model, predictors)
|
|
474
|
+
if not vif.empty:
|
|
475
|
+
result.add_table("Variance Inflation Factors", vif)
|
|
476
|
+
_add_regression_plots(result, model, frame, response)
|
|
477
|
+
result.summary = (
|
|
478
|
+
f"R² = {model.rsquared:.4f}, adjusted R² = {model.rsquared_adj:.4f}, "
|
|
479
|
+
f"F = {model.fvalue:.4g}, p = {model.f_pvalue:.4g}, N = {int(model.nobs)}. Formula: {display_formula(formula)}"
|
|
480
|
+
)
|
|
481
|
+
_attach_prediction_profiler(
|
|
482
|
+
result,
|
|
483
|
+
FittedRegression(model=model, frame=frame, response=response, predictors=list(predictors), kind="linear"),
|
|
484
|
+
)
|
|
485
|
+
return result
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def polynomial_regression(df: pd.DataFrame, response: str, predictor: str, degree: int = 2) -> AnalysisResult:
|
|
489
|
+
if degree < 1 or degree > 8:
|
|
490
|
+
raise ValueError("Degree must be between 1 and 8.")
|
|
491
|
+
frame = _clean(df, response, [predictor])
|
|
492
|
+
terms = [f'Q("{predictor}")'] + [f'I(Q("{predictor}")**{power})' for power in range(2, degree + 1)]
|
|
493
|
+
formula = f'Q("{response}") ~ ' + " + ".join(terms)
|
|
494
|
+
model = smf.ols(formula, data=frame).fit()
|
|
495
|
+
result = AnalysisResult(
|
|
496
|
+
title=f"Polynomial Regression: {response} vs {predictor}",
|
|
497
|
+
analysis_type="polynomial_regression",
|
|
498
|
+
params={"response": response, "predictor": predictor, "degree": degree, "formula": formula},
|
|
499
|
+
)
|
|
500
|
+
result.add_table("Coefficients", _coefficient_table(model))
|
|
501
|
+
result.add_table("Model Metrics", _metrics(model, response, frame, f"Polynomial degree {degree}"))
|
|
502
|
+
_add_regression_plots(result, model, frame, response)
|
|
503
|
+
result.summary = f"Degree {degree}; R² = {model.rsquared:.4f}, p = {model.f_pvalue:.4g}, N = {int(model.nobs)}."
|
|
504
|
+
_attach_prediction_profiler(
|
|
505
|
+
result,
|
|
506
|
+
FittedRegression(
|
|
507
|
+
model=model,
|
|
508
|
+
frame=frame,
|
|
509
|
+
response=response,
|
|
510
|
+
predictors=[predictor],
|
|
511
|
+
kind="polynomial",
|
|
512
|
+
extra={"degree": degree},
|
|
513
|
+
),
|
|
514
|
+
)
|
|
515
|
+
return result
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def logistic_regression(df: pd.DataFrame, response: str, predictors: Sequence[str], interactions: bool = False) -> AnalysisResult:
|
|
519
|
+
if not predictors:
|
|
520
|
+
raise ValueError("Choose at least one predictor.")
|
|
521
|
+
columns = [response] + [p for p in predictors if p != response]
|
|
522
|
+
missing = [c for c in columns if c not in df.columns]
|
|
523
|
+
if missing:
|
|
524
|
+
raise KeyError(f"Missing columns: {', '.join(missing)}")
|
|
525
|
+
frame = df.loc[:, columns].dropna().copy()
|
|
526
|
+
values = pd.unique(frame[response])
|
|
527
|
+
if len(values) != 2:
|
|
528
|
+
raise ValueError("Logistic regression requires a binary response with exactly two observed values.")
|
|
529
|
+
positive = max(values)
|
|
530
|
+
frame[response] = (frame[response] == positive).astype(int)
|
|
531
|
+
formula = _formula(response, predictors, frame, interactions)
|
|
532
|
+
try:
|
|
533
|
+
model = smf.logit(formula, data=frame).fit(disp=0)
|
|
534
|
+
except Exception as exc:
|
|
535
|
+
raise ValueError(f"Logistic model failed: {exc}") from exc
|
|
536
|
+
result = AnalysisResult(
|
|
537
|
+
title=f"Logistic Regression: {response}",
|
|
538
|
+
analysis_type="logistic_regression",
|
|
539
|
+
params={"response": response, "predictors": list(predictors), "interactions": interactions, "positive": str(positive), "formula": formula},
|
|
540
|
+
)
|
|
541
|
+
result.add_table("Coefficients", _coefficient_table(model, exponential=True))
|
|
542
|
+
predicted = np.asarray(model.predict(frame))
|
|
543
|
+
actual = frame[response].to_numpy()
|
|
544
|
+
threshold = 0.5
|
|
545
|
+
classification = pd.crosstab(
|
|
546
|
+
pd.Series(actual, name="Actual"),
|
|
547
|
+
pd.Series((predicted >= threshold).astype(int), name="Predicted"),
|
|
548
|
+
).reset_index()
|
|
549
|
+
result.add_table("Classification (threshold 0.5)", classification)
|
|
550
|
+
accuracy = float(np.mean((predicted >= threshold) == actual))
|
|
551
|
+
pseudo = 1 - (model.llf / model.llnull) if model.llnull else np.nan
|
|
552
|
+
result.add_table(
|
|
553
|
+
"Model Metrics",
|
|
554
|
+
pd.DataFrame(
|
|
555
|
+
[
|
|
556
|
+
("N", int(model.nobs)),
|
|
557
|
+
("Positive value", positive),
|
|
558
|
+
("Pseudo R-squared (McFadden)", pseudo),
|
|
559
|
+
("Log likelihood", model.llf),
|
|
560
|
+
("AIC", model.aic),
|
|
561
|
+
("BIC", model.bic),
|
|
562
|
+
("Accuracy", accuracy),
|
|
563
|
+
],
|
|
564
|
+
columns=["Metric", "Value"],
|
|
565
|
+
),
|
|
566
|
+
)
|
|
567
|
+
try:
|
|
568
|
+
from sklearn.metrics import roc_auc_score, roc_curve
|
|
569
|
+
|
|
570
|
+
fpr, tpr, _ = roc_curve(actual, predicted)
|
|
571
|
+
auc = roc_auc_score(actual, predicted)
|
|
572
|
+
result.add_plot("roc", {"fpr": fpr.tolist(), "tpr": tpr.tolist(), "auc": auc}, title="ROC Curve")
|
|
573
|
+
result.summary = f"McFadden R² = {pseudo:.4f}, AUC = {auc:.4f}, accuracy = {accuracy:.3f}, N = {int(model.nobs)}."
|
|
574
|
+
except Exception:
|
|
575
|
+
result.summary = f"McFadden R² = {pseudo:.4f}, accuracy = {accuracy:.3f}, N = {int(model.nobs)}."
|
|
576
|
+
_attach_prediction_profiler(
|
|
577
|
+
result,
|
|
578
|
+
FittedRegression(
|
|
579
|
+
model=model,
|
|
580
|
+
frame=frame,
|
|
581
|
+
response=response,
|
|
582
|
+
predictors=list(predictors),
|
|
583
|
+
kind="logistic",
|
|
584
|
+
label=f"Predicted probability ({positive})",
|
|
585
|
+
extra={"positive": positive},
|
|
586
|
+
),
|
|
587
|
+
)
|
|
588
|
+
return result
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def glm_regression(
|
|
592
|
+
df: pd.DataFrame,
|
|
593
|
+
response: str,
|
|
594
|
+
predictors: Sequence[str],
|
|
595
|
+
family: str = "gaussian",
|
|
596
|
+
interactions: bool = False,
|
|
597
|
+
link: str | None = None,
|
|
598
|
+
test_size: float = 0.0,
|
|
599
|
+
) -> AnalysisResult:
|
|
600
|
+
if not predictors:
|
|
601
|
+
raise ValueError("Choose at least one predictor.")
|
|
602
|
+
if family == "binomial":
|
|
603
|
+
columns = [response] + [p for p in predictors if p != response]
|
|
604
|
+
frame = df.loc[:, columns].dropna().copy()
|
|
605
|
+
else:
|
|
606
|
+
frame = _clean(df, response, predictors)
|
|
607
|
+
families = {
|
|
608
|
+
"gaussian": sm.families.Gaussian,
|
|
609
|
+
"binomial": sm.families.Binomial,
|
|
610
|
+
"poisson": sm.families.Poisson,
|
|
611
|
+
"gamma": sm.families.Gamma,
|
|
612
|
+
"inverse_gaussian": sm.families.InverseGaussian,
|
|
613
|
+
"negative_binomial": sm.families.NegativeBinomial,
|
|
614
|
+
}
|
|
615
|
+
links = {
|
|
616
|
+
"identity": sm.families.links.Identity,
|
|
617
|
+
"log": sm.families.links.Log,
|
|
618
|
+
"logit": sm.families.links.Logit,
|
|
619
|
+
"probit": sm.families.links.Probit,
|
|
620
|
+
"inverse": sm.families.links.InversePower,
|
|
621
|
+
"sqrt": sm.families.links.Sqrt,
|
|
622
|
+
"cloglog": sm.families.links.CLogLog,
|
|
623
|
+
}
|
|
624
|
+
if family not in families:
|
|
625
|
+
raise ValueError(f"Unknown family: {family}")
|
|
626
|
+
if link and link not in links:
|
|
627
|
+
raise ValueError(f"Unknown link: {link}")
|
|
628
|
+
if family == "binomial":
|
|
629
|
+
values = pd.unique(frame[response])
|
|
630
|
+
if len(values) == 2:
|
|
631
|
+
positive = max(values)
|
|
632
|
+
frame[response] = (frame[response] == positive).astype(int)
|
|
633
|
+
formula = _formula(response, predictors, frame, interactions)
|
|
634
|
+
try:
|
|
635
|
+
family_instance = families[family](link=links[link]()) if link else families[family]()
|
|
636
|
+
model = smf.glm(formula, data=frame, family=family_instance).fit()
|
|
637
|
+
except Exception as exc:
|
|
638
|
+
raise ValueError(f"GLM failed: {exc}") from exc
|
|
639
|
+
result = AnalysisResult(
|
|
640
|
+
title=f"GLM ({family}{' / ' + link if link else ''}): {response}",
|
|
641
|
+
analysis_type="glm",
|
|
642
|
+
params={"response": response, "predictors": list(predictors), "family": family, "interactions": interactions, "formula": formula, "link": link, "test_size": test_size},
|
|
643
|
+
)
|
|
644
|
+
result.add_table("Coefficients", _coefficient_table(model, exponential=family in {"binomial", "poisson"}))
|
|
645
|
+
result.add_table("Model Metrics", _metrics(model, response, frame, f"GLM {family}"))
|
|
646
|
+
try:
|
|
647
|
+
lr_statistic = float(2 * (model.llf - model.llnull))
|
|
648
|
+
lr_df = max(1, int(model.df_model))
|
|
649
|
+
from scipy import stats as scipy_stats
|
|
650
|
+
result.add_table("Likelihood Ratio Test", pd.DataFrame([{"Statistic": lr_statistic, "df": lr_df, "p-value": float(scipy_stats.chi2.sf(lr_statistic, lr_df))}]))
|
|
651
|
+
except Exception:
|
|
652
|
+
pass
|
|
653
|
+
if test_size and 0 < test_size < 1 and len(frame) >= 12:
|
|
654
|
+
split = max(2, min(len(frame) - 2, int(round(len(frame) * (1 - test_size)))))
|
|
655
|
+
train, test = frame.iloc[:split], frame.iloc[split:]
|
|
656
|
+
try:
|
|
657
|
+
holdout = smf.glm(formula, data=train, family=family_instance).fit()
|
|
658
|
+
predicted = np.asarray(holdout.predict(test))
|
|
659
|
+
actual = np.asarray(test[response], dtype=float)
|
|
660
|
+
result.add_table("Holdout Validation", pd.DataFrame([{
|
|
661
|
+
"Train N": len(train), "Test N": len(test),
|
|
662
|
+
"Holdout RMSE": float(np.sqrt(np.mean((actual - predicted) ** 2))),
|
|
663
|
+
"Holdout MAE": float(np.mean(np.abs(actual - predicted))),
|
|
664
|
+
}]))
|
|
665
|
+
except Exception:
|
|
666
|
+
pass
|
|
667
|
+
result.add_model("glm", model)
|
|
668
|
+
result.summary = f"Family: {family}{' / ' + link if link else ''}; deviance = {model.deviance:.4g}, AIC = {model.aic:.4g}, N = {int(model.nobs)}."
|
|
669
|
+
label = "Predicted probability" if family in {"binomial"} else "Predicted mean"
|
|
670
|
+
_attach_prediction_profiler(
|
|
671
|
+
result,
|
|
672
|
+
FittedRegression(
|
|
673
|
+
model=model,
|
|
674
|
+
frame=frame,
|
|
675
|
+
response=response,
|
|
676
|
+
predictors=list(predictors),
|
|
677
|
+
kind="glm",
|
|
678
|
+
label=label,
|
|
679
|
+
extra={"family": family, "link": link},
|
|
680
|
+
),
|
|
681
|
+
)
|
|
682
|
+
return result
|
|
683
|
+
|
|
684
|
+
|
|
685
|
+
def mixed_model(
|
|
686
|
+
df: pd.DataFrame,
|
|
687
|
+
response: str,
|
|
688
|
+
predictors: Sequence[str],
|
|
689
|
+
group: str,
|
|
690
|
+
random_slope: str | None = None,
|
|
691
|
+
) -> AnalysisResult:
|
|
692
|
+
if not predictors:
|
|
693
|
+
raise ValueError("Choose at least one predictor.")
|
|
694
|
+
if group not in df.columns:
|
|
695
|
+
raise KeyError(group)
|
|
696
|
+
frame = _clean(df, response, [p for p in predictors if p != group] + [group])
|
|
697
|
+
fixed_predictors = [p for p in predictors if p != group]
|
|
698
|
+
terms = [
|
|
699
|
+
f'Q("{name}")'
|
|
700
|
+
if pd.api.types.is_numeric_dtype(frame[name]) and not pd.api.types.is_bool_dtype(frame[name])
|
|
701
|
+
else f'C(Q("{name}"), Sum)'
|
|
702
|
+
for name in fixed_predictors
|
|
703
|
+
]
|
|
704
|
+
formula = f'{_term(response, frame)} ~ ' + (" + ".join(terms) if terms else "1")
|
|
705
|
+
try:
|
|
706
|
+
if random_slope:
|
|
707
|
+
model = smf.mixedlm(formula, frame, groups=frame[group], re_formula=f'~Q("{random_slope}")')
|
|
708
|
+
else:
|
|
709
|
+
model = smf.mixedlm(formula, frame, groups=frame[group])
|
|
710
|
+
try:
|
|
711
|
+
fit = model.fit(reml=True, method="cg", maxiter=2000)
|
|
712
|
+
except Exception:
|
|
713
|
+
fit = model.fit(reml=True)
|
|
714
|
+
except Exception as exc:
|
|
715
|
+
raise ValueError(f"Mixed model failed: {exc}") from exc
|
|
716
|
+
result = AnalysisResult(
|
|
717
|
+
title=f"Mixed Model: {response}",
|
|
718
|
+
analysis_type="mixed_model",
|
|
719
|
+
params={"response": response, "predictors": list(predictors), "group": group, "random_slope": random_slope, "formula": formula},
|
|
720
|
+
)
|
|
721
|
+
coef = pd.DataFrame(
|
|
722
|
+
{
|
|
723
|
+
"Term": [display_formula(name) for name in fit.params.index],
|
|
724
|
+
"Estimate": fit.params.values,
|
|
725
|
+
"Std Error": fit.bse.values,
|
|
726
|
+
"z": fit.tvalues.values,
|
|
727
|
+
"p-value": fit.pvalues.values,
|
|
728
|
+
}
|
|
729
|
+
)
|
|
730
|
+
coef["Significance"] = coef["p-value"].map(p_stars)
|
|
731
|
+
result.add_table("Fixed Effects", coef)
|
|
732
|
+
result.add_table(
|
|
733
|
+
"Model Metrics",
|
|
734
|
+
pd.DataFrame(
|
|
735
|
+
[
|
|
736
|
+
("Groups", frame[group].nunique()),
|
|
737
|
+
("Observations", len(frame)),
|
|
738
|
+
("Log likelihood", fit.llf),
|
|
739
|
+
("AIC", fit.aic),
|
|
740
|
+
("BIC", fit.bic),
|
|
741
|
+
("Converged", fit.converged),
|
|
742
|
+
],
|
|
743
|
+
columns=["Metric", "Value"],
|
|
744
|
+
),
|
|
745
|
+
)
|
|
746
|
+
_add_mixed_extras(result, fit, model, frame, response, list(predictors))
|
|
747
|
+
result.notes = "Fixed-effect p-values use Wald z inference; EMM comparisons use residual-df t approximations."
|
|
748
|
+
result.summary = f"Grouping: {group}, {frame[group].nunique()} groups, N = {len(frame)}. Formula: {display_formula(formula)}"
|
|
749
|
+
_attach_prediction_profiler(
|
|
750
|
+
result,
|
|
751
|
+
FittedRegression(
|
|
752
|
+
model=fit,
|
|
753
|
+
frame=frame,
|
|
754
|
+
response=response,
|
|
755
|
+
predictors=fixed_predictors,
|
|
756
|
+
kind="mixed",
|
|
757
|
+
label="Predicted fixed-effect mean",
|
|
758
|
+
extra={"group": group, "random_slope": random_slope},
|
|
759
|
+
),
|
|
760
|
+
)
|
|
761
|
+
return result
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
def _add_mixed_extras(result: AnalysisResult, fit, model, frame: pd.DataFrame, response: str, predictors: list[str]) -> None:
|
|
765
|
+
# Fixed-effect Wald tests
|
|
766
|
+
try:
|
|
767
|
+
tests = fit.wald_test_terms(skip_single=False).table
|
|
768
|
+
tests = tests.reset_index().rename(columns={"index": "Effect"})
|
|
769
|
+
tests["Effect"] = tests["Effect"].map(display_formula)
|
|
770
|
+
tests["Significance"] = tests["pvalue"].map(p_stars) if "pvalue" in tests else ""
|
|
771
|
+
result.add_table("Fixed Effects Tests (Wald)", tests)
|
|
772
|
+
except Exception:
|
|
773
|
+
pass
|
|
774
|
+
# Random-effects variance components, BLUPs, and approximate R-squared.
|
|
775
|
+
try:
|
|
776
|
+
rows = []
|
|
777
|
+
cov_re = np.asarray(fit.cov_re)
|
|
778
|
+
names = list(getattr(fit.cov_re, "index", range(cov_re.shape[0])))
|
|
779
|
+
for index, name in enumerate(names):
|
|
780
|
+
rows.append({"Effect": str(name), "Variance": float(cov_re[index, index]), "Std Dev": float(np.sqrt(cov_re[index, index]))})
|
|
781
|
+
rows.append({"Effect": "Residual", "Variance": float(fit.scale), "Std Dev": float(np.sqrt(fit.scale))})
|
|
782
|
+
result.add_table("Random Effects", pd.DataFrame(rows))
|
|
783
|
+
blup_rows = []
|
|
784
|
+
for group_value, effects in (fit.random_effects or {}).items():
|
|
785
|
+
row = {"Group": str(group_value)}
|
|
786
|
+
for name, value in effects.items():
|
|
787
|
+
row[f"BLUP {name}"] = float(value)
|
|
788
|
+
blup_rows.append(row)
|
|
789
|
+
if blup_rows:
|
|
790
|
+
result.add_table("Random Effects BLUPs", pd.DataFrame(blup_rows))
|
|
791
|
+
weights = np.ones(cov_re.shape[0])
|
|
792
|
+
random_variance = float(weights @ cov_re @ weights)
|
|
793
|
+
fixed = np.asarray(model.exog @ fit.fe_params, dtype=float)
|
|
794
|
+
var_fixed = float(np.var(fixed, ddof=1)) if fixed.size > 1 else 0.0
|
|
795
|
+
total_variance = var_fixed + random_variance + float(fit.scale)
|
|
796
|
+
icc = random_variance / (random_variance + float(fit.scale)) if random_variance + float(fit.scale) > 0 else np.nan
|
|
797
|
+
marginal = var_fixed / total_variance if total_variance > 0 else np.nan
|
|
798
|
+
conditional = (var_fixed + random_variance) / total_variance if total_variance > 0 else np.nan
|
|
799
|
+
result.add_table(
|
|
800
|
+
"Variance Components",
|
|
801
|
+
pd.DataFrame(
|
|
802
|
+
[{
|
|
803
|
+
"Random Variance": random_variance,
|
|
804
|
+
"Residual Variance": float(fit.scale),
|
|
805
|
+
"ICC": icc,
|
|
806
|
+
"Marginal R2": marginal,
|
|
807
|
+
"Conditional R2": conditional,
|
|
808
|
+
}]
|
|
809
|
+
),
|
|
810
|
+
)
|
|
811
|
+
except Exception:
|
|
812
|
+
pass
|
|
813
|
+
# Estimated marginal means and pairwise comparisons for categorical predictors
|
|
814
|
+
try:
|
|
815
|
+
from patsy import dmatrix
|
|
816
|
+
|
|
817
|
+
design_info = model.model.data.design_info
|
|
818
|
+
params = fit.params
|
|
819
|
+
cov = np.asarray(fit.cov_params())
|
|
820
|
+
names = list(params.index)
|
|
821
|
+
numeric_means = {p: float(pd.to_numeric(frame[p], errors="coerce").mean()) for p in predictors if pd.api.types.is_numeric_dtype(frame[p])}
|
|
822
|
+
degrees = float(getattr(fit, "df_resid", np.inf))
|
|
823
|
+
critical = float(stats.t.ppf(0.975, degrees)) if np.isfinite(degrees) and degrees > 0 else 1.96
|
|
824
|
+
categorical = [p for p in predictors if not pd.api.types.is_numeric_dtype(frame[p])]
|
|
825
|
+
emm_rows = []
|
|
826
|
+
comparison_rows = []
|
|
827
|
+
for factor in categorical:
|
|
828
|
+
levels = list(pd.unique(frame[factor].dropna()))
|
|
829
|
+
predictions = []
|
|
830
|
+
for level in levels:
|
|
831
|
+
grid = pd.DataFrame([{**numeric_means, **{p: frame[p].dropna().iloc[0] for p in categorical if p != factor}, factor: level}])
|
|
832
|
+
X = dmatrix(design_info, grid, return_type="dataframe").reindex(columns=names, fill_value=0.0)
|
|
833
|
+
estimate = float(np.asarray(X.to_numpy() @ params.to_numpy())[0])
|
|
834
|
+
var = float(np.asarray(X.to_numpy() @ cov @ X.to_numpy().T)[0, 0])
|
|
835
|
+
se = np.sqrt(max(var, 0.0))
|
|
836
|
+
emm_rows.append({"Factor": factor, "Level": str(level), "EMM": estimate, "Std Error": se, "CI Low": estimate - critical * se, "CI High": estimate + critical * se})
|
|
837
|
+
predictions.append((level, X.to_numpy(), estimate, se))
|
|
838
|
+
for i in range(len(predictions)):
|
|
839
|
+
for j in range(i + 1, len(predictions)):
|
|
840
|
+
level_i, X_i, est_i, _ = predictions[i]
|
|
841
|
+
level_j, X_j, est_j, _ = predictions[j]
|
|
842
|
+
diff = est_i - est_j
|
|
843
|
+
var = float(np.asarray((X_i - X_j) @ cov @ (X_i - X_j).T)[0, 0])
|
|
844
|
+
se = np.sqrt(max(var, 0.0))
|
|
845
|
+
if se > 0:
|
|
846
|
+
t_value = diff / se
|
|
847
|
+
pvalue = float(2 * stats.t.sf(abs(t_value), degrees)) if np.isfinite(degrees) and degrees > 0 else float(2 * stats.norm.sf(abs(t_value)))
|
|
848
|
+
else:
|
|
849
|
+
t_value = np.nan
|
|
850
|
+
pvalue = np.nan
|
|
851
|
+
comparison_rows.append({"Factor": factor, "Level 1": str(level_i), "Level 2": str(level_j), "Difference": diff, "Std Error": se, "t": t_value, "p-value": pvalue, "Significance": p_stars(pvalue)})
|
|
852
|
+
if emm_rows:
|
|
853
|
+
result.add_table("Estimated Marginal Means", pd.DataFrame(emm_rows))
|
|
854
|
+
if comparison_rows:
|
|
855
|
+
result.add_table("Pairwise Comparisons", pd.DataFrame(comparison_rows))
|
|
856
|
+
except Exception:
|
|
857
|
+
pass
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def stepwise_regression(
|
|
861
|
+
df: pd.DataFrame,
|
|
862
|
+
response: str,
|
|
863
|
+
predictors: Sequence[str],
|
|
864
|
+
criterion: str = "pvalue",
|
|
865
|
+
threshold: float = 0.05,
|
|
866
|
+
) -> AnalysisResult:
|
|
867
|
+
frame = _clean(df, response, predictors)
|
|
868
|
+
remaining = list(predictors)
|
|
869
|
+
selected: list[str] = []
|
|
870
|
+
history: list[dict[str, object]] = []
|
|
871
|
+
current_score = np.inf
|
|
872
|
+
while remaining:
|
|
873
|
+
best = None
|
|
874
|
+
try:
|
|
875
|
+
reduced = smf.ols(_formula(response, selected, frame, False), data=frame).fit()
|
|
876
|
+
except Exception:
|
|
877
|
+
break
|
|
878
|
+
for candidate in remaining:
|
|
879
|
+
try:
|
|
880
|
+
model = smf.ols(_formula(response, selected + [candidate], frame, False), data=frame).fit()
|
|
881
|
+
pvalue = float(model.compare_f_test(reduced)[1])
|
|
882
|
+
except Exception:
|
|
883
|
+
continue
|
|
884
|
+
if criterion == "aic":
|
|
885
|
+
score = model.aic
|
|
886
|
+
elif criterion == "bic":
|
|
887
|
+
score = model.bic
|
|
888
|
+
else:
|
|
889
|
+
score = pvalue
|
|
890
|
+
if pvalue > threshold:
|
|
891
|
+
continue
|
|
892
|
+
if best is None or score < best[0]:
|
|
893
|
+
best = (score, candidate, model, pvalue)
|
|
894
|
+
if best is None:
|
|
895
|
+
break
|
|
896
|
+
if criterion in {"aic", "bic"}:
|
|
897
|
+
if best[0] >= current_score:
|
|
898
|
+
break
|
|
899
|
+
current_score = best[0]
|
|
900
|
+
selected.append(best[1])
|
|
901
|
+
remaining.remove(best[1])
|
|
902
|
+
history.append(
|
|
903
|
+
{
|
|
904
|
+
"Step": len(selected),
|
|
905
|
+
"Added": best[1],
|
|
906
|
+
"AIC": best[2].aic,
|
|
907
|
+
"BIC": best[2].bic,
|
|
908
|
+
"R-squared": best[2].rsquared,
|
|
909
|
+
"p-value": best[3],
|
|
910
|
+
}
|
|
911
|
+
)
|
|
912
|
+
if not selected:
|
|
913
|
+
raise ValueError("No predictors met the selection criterion.")
|
|
914
|
+
final = linear_regression(frame, response, selected)
|
|
915
|
+
final.title = f"Stepwise Regression: {response}"
|
|
916
|
+
final.analysis_type = "stepwise_regression"
|
|
917
|
+
final.params = {
|
|
918
|
+
"response": response,
|
|
919
|
+
"predictors": list(predictors),
|
|
920
|
+
"criterion": criterion,
|
|
921
|
+
"threshold": threshold,
|
|
922
|
+
}
|
|
923
|
+
fitted = final.models.get("regression")
|
|
924
|
+
if isinstance(fitted, FittedRegression):
|
|
925
|
+
fitted.kind = "stepwise"
|
|
926
|
+
fitted.label = "Predicted"
|
|
927
|
+
fitted.extra = {"criterion": criterion, "threshold": threshold, "selected": list(selected)}
|
|
928
|
+
final.tables.insert(0, result_table("Selection History", pd.DataFrame(history)))
|
|
929
|
+
final.summary = f"Selected {len(selected)} predictor(s): {', '.join(selected)}. " + final.summary
|
|
930
|
+
return final
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
def _gee_qic(fit) -> float:
|
|
934
|
+
try:
|
|
935
|
+
value = fit.qic()
|
|
936
|
+
except Exception:
|
|
937
|
+
return float("nan")
|
|
938
|
+
try:
|
|
939
|
+
return float(value[0])
|
|
940
|
+
except (TypeError, IndexError):
|
|
941
|
+
try:
|
|
942
|
+
return float(value)
|
|
943
|
+
except (TypeError, ValueError):
|
|
944
|
+
return float("nan")
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
def result_table(title: str, frame: pd.DataFrame):
|
|
948
|
+
from statstudio.stats.results import ResultTable
|
|
949
|
+
|
|
950
|
+
return ResultTable(title=title, frame=frame)
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def gee_regression(
|
|
954
|
+
df: pd.DataFrame,
|
|
955
|
+
response: str,
|
|
956
|
+
predictors: Sequence[str],
|
|
957
|
+
group: str,
|
|
958
|
+
correlation: str = "exchangeable",
|
|
959
|
+
family: str = "gaussian",
|
|
960
|
+
compare_structures: bool = False,
|
|
961
|
+
) -> AnalysisResult:
|
|
962
|
+
if not predictors:
|
|
963
|
+
raise ValueError("Choose at least one predictor.")
|
|
964
|
+
frame = _clean(df, response, [p for p in predictors if p != group] + [group])
|
|
965
|
+
fixed_predictors = [p for p in predictors if p != group]
|
|
966
|
+
terms = [
|
|
967
|
+
f'Q("{name}")'
|
|
968
|
+
if pd.api.types.is_numeric_dtype(frame[name]) and not pd.api.types.is_bool_dtype(frame[name])
|
|
969
|
+
else f'C(Q("{name}"), Sum)'
|
|
970
|
+
for name in fixed_predictors
|
|
971
|
+
]
|
|
972
|
+
formula = f'{_term(response, frame)} ~ ' + (" + ".join(terms) if terms else "1")
|
|
973
|
+
families = {"gaussian": sm.families.Gaussian(), "binomial": sm.families.Binomial(), "poisson": sm.families.Poisson()}
|
|
974
|
+
if family not in families:
|
|
975
|
+
raise ValueError(f"Unknown GEE family: {family}")
|
|
976
|
+
structures = {
|
|
977
|
+
"independence": sm.cov_struct.Independence,
|
|
978
|
+
"exchangeable": sm.cov_struct.Exchangeable,
|
|
979
|
+
"ar": sm.cov_struct.Autoregressive,
|
|
980
|
+
"autoregressive": sm.cov_struct.Autoregressive,
|
|
981
|
+
"stationary": sm.cov_struct.Stationary,
|
|
982
|
+
}
|
|
983
|
+
if correlation.lower() not in structures:
|
|
984
|
+
raise ValueError(f"Unknown correlation structure: {correlation}")
|
|
985
|
+
try:
|
|
986
|
+
model = smf.gee(
|
|
987
|
+
formula,
|
|
988
|
+
groups=frame[group],
|
|
989
|
+
data=frame,
|
|
990
|
+
family=families[family],
|
|
991
|
+
cov_struct=structures[correlation.lower()](),
|
|
992
|
+
)
|
|
993
|
+
fit = model.fit()
|
|
994
|
+
except Exception as exc:
|
|
995
|
+
raise ValueError(f"GEE model failed: {exc}") from exc
|
|
996
|
+
conf = np.asarray(fit.conf_int())
|
|
997
|
+
table = pd.DataFrame({
|
|
998
|
+
"Term": [display_formula(name) for name in fit.params.index],
|
|
999
|
+
"Estimate": fit.params.to_numpy(),
|
|
1000
|
+
"Std Error": fit.bse.to_numpy(),
|
|
1001
|
+
"z": fit.tvalues.to_numpy(),
|
|
1002
|
+
"p-value": fit.pvalues.to_numpy(),
|
|
1003
|
+
"CI Low": conf[:, 0],
|
|
1004
|
+
"CI High": conf[:, 1],
|
|
1005
|
+
})
|
|
1006
|
+
table["Significance"] = table["p-value"].map(p_stars)
|
|
1007
|
+
result = AnalysisResult(
|
|
1008
|
+
title=f"GEE ({family}, {correlation}): {response}",
|
|
1009
|
+
analysis_type="gee",
|
|
1010
|
+
params={
|
|
1011
|
+
"response": response,
|
|
1012
|
+
"predictors": list(predictors),
|
|
1013
|
+
"group": group,
|
|
1014
|
+
"correlation": correlation,
|
|
1015
|
+
"family": family,
|
|
1016
|
+
"formula": formula,
|
|
1017
|
+
"compare_structures": bool(compare_structures),
|
|
1018
|
+
},
|
|
1019
|
+
)
|
|
1020
|
+
result.add_table("Coefficients", table)
|
|
1021
|
+
result.add_table("Model Metrics", pd.DataFrame([{"Groups": frame[group].nunique(), "Observations": len(frame), "QIC": _gee_qic(fit), "Scale": getattr(fit, "scale", np.nan)}]))
|
|
1022
|
+
if compare_structures:
|
|
1023
|
+
rows = []
|
|
1024
|
+
seen = set()
|
|
1025
|
+
for name, structure in structures.items():
|
|
1026
|
+
if name in {"autoregressive"} or name in seen:
|
|
1027
|
+
continue
|
|
1028
|
+
seen.add(name)
|
|
1029
|
+
try:
|
|
1030
|
+
candidate = smf.gee(formula, groups=frame[group], data=frame, family=families[family], cov_struct=structure()).fit()
|
|
1031
|
+
rows.append({"Correlation": name, "QIC": _gee_qic(candidate), "Scale": float(getattr(candidate, "scale", np.nan))})
|
|
1032
|
+
except Exception as exc:
|
|
1033
|
+
rows.append({"Correlation": name, "QIC": np.nan, "Scale": np.nan, "Note": str(exc)})
|
|
1034
|
+
if rows:
|
|
1035
|
+
result.add_table("Correlation Structure Comparison", pd.DataFrame(rows).sort_values("QIC", na_position="last").reset_index(drop=True))
|
|
1036
|
+
result.add_model("gee", fit)
|
|
1037
|
+
result.summary = f"GEE with {correlation} working correlation over {frame[group].nunique()} groups and {len(frame)} observations."
|
|
1038
|
+
label = "Predicted probability" if family == "binomial" else "Predicted mean"
|
|
1039
|
+
_attach_prediction_profiler(
|
|
1040
|
+
result,
|
|
1041
|
+
FittedRegression(
|
|
1042
|
+
model=fit,
|
|
1043
|
+
frame=frame,
|
|
1044
|
+
response=response,
|
|
1045
|
+
predictors=fixed_predictors,
|
|
1046
|
+
kind="gee",
|
|
1047
|
+
label=label,
|
|
1048
|
+
extra={"group": group, "correlation": correlation, "family": family},
|
|
1049
|
+
),
|
|
1050
|
+
)
|
|
1051
|
+
return result
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def fit_regression(
|
|
1055
|
+
df: pd.DataFrame,
|
|
1056
|
+
response: str,
|
|
1057
|
+
predictors: Sequence[str],
|
|
1058
|
+
model_type: str = "Linear",
|
|
1059
|
+
interactions: bool = False,
|
|
1060
|
+
robust: bool = False,
|
|
1061
|
+
weight: str | None = None,
|
|
1062
|
+
test_size: float = 0.0,
|
|
1063
|
+
degree: int = 2,
|
|
1064
|
+
family: str = "gaussian",
|
|
1065
|
+
link: str | None = None,
|
|
1066
|
+
group: str | None = None,
|
|
1067
|
+
random_slope: str | None = None,
|
|
1068
|
+
correlation: str = "exchangeable",
|
|
1069
|
+
compare_structures: bool = False,
|
|
1070
|
+
criterion: str = "pvalue",
|
|
1071
|
+
threshold: float = 0.05,
|
|
1072
|
+
) -> FittedRegression:
|
|
1073
|
+
kind = str(model_type or "Linear").strip().lower()
|
|
1074
|
+
predictors = [predictor for predictor in predictors if predictor != response]
|
|
1075
|
+
if kind in {"linear", "regression"}:
|
|
1076
|
+
result = linear_regression(df, response, predictors, interactions, robust, weight, test_size)
|
|
1077
|
+
elif kind == "logistic":
|
|
1078
|
+
result = logistic_regression(df, response, predictors, interactions)
|
|
1079
|
+
elif kind == "glm":
|
|
1080
|
+
result = glm_regression(df, response, predictors, family, interactions, link, test_size)
|
|
1081
|
+
elif kind == "polynomial":
|
|
1082
|
+
if len(predictors) != 1:
|
|
1083
|
+
raise ValueError("Polynomial regression uses exactly one predictor.")
|
|
1084
|
+
result = polynomial_regression(df, response, predictors[0], degree)
|
|
1085
|
+
elif kind == "mixed":
|
|
1086
|
+
if not group:
|
|
1087
|
+
raise ValueError("Choose a group column for a mixed model.")
|
|
1088
|
+
result = mixed_model(df, response, predictors, group, random_slope)
|
|
1089
|
+
elif kind == "gee":
|
|
1090
|
+
if not group:
|
|
1091
|
+
raise ValueError("Choose a group column for GEE.")
|
|
1092
|
+
result = gee_regression(df, response, predictors, group, correlation, family, compare_structures)
|
|
1093
|
+
elif kind == "stepwise":
|
|
1094
|
+
result = stepwise_regression(df, response, predictors, criterion, threshold)
|
|
1095
|
+
else:
|
|
1096
|
+
raise ValueError(f"Unknown regression model: {model_type}")
|
|
1097
|
+
fitted = result.models.get("regression")
|
|
1098
|
+
if not isinstance(fitted, FittedRegression):
|
|
1099
|
+
raise ValueError("The fitted regression model is not available.")
|
|
1100
|
+
return fitted
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
def prediction_profiler(
|
|
1104
|
+
df: pd.DataFrame,
|
|
1105
|
+
response: str,
|
|
1106
|
+
predictors: Sequence[str],
|
|
1107
|
+
model_type: str = "Linear",
|
|
1108
|
+
points: int = 9,
|
|
1109
|
+
interactions: bool = False,
|
|
1110
|
+
robust: bool = False,
|
|
1111
|
+
weight: str | None = None,
|
|
1112
|
+
test_size: float = 0.0,
|
|
1113
|
+
degree: int = 2,
|
|
1114
|
+
family: str = "gaussian",
|
|
1115
|
+
link: str | None = None,
|
|
1116
|
+
group: str | None = None,
|
|
1117
|
+
random_slope: str | None = None,
|
|
1118
|
+
correlation: str = "exchangeable",
|
|
1119
|
+
compare_structures: bool = False,
|
|
1120
|
+
criterion: str = "pvalue",
|
|
1121
|
+
threshold: float = 0.05,
|
|
1122
|
+
**_: Any,
|
|
1123
|
+
) -> AnalysisResult:
|
|
1124
|
+
fitted = fit_regression(
|
|
1125
|
+
df,
|
|
1126
|
+
response,
|
|
1127
|
+
predictors,
|
|
1128
|
+
model_type,
|
|
1129
|
+
interactions,
|
|
1130
|
+
robust,
|
|
1131
|
+
weight,
|
|
1132
|
+
test_size,
|
|
1133
|
+
degree,
|
|
1134
|
+
family,
|
|
1135
|
+
link,
|
|
1136
|
+
group,
|
|
1137
|
+
random_slope,
|
|
1138
|
+
correlation,
|
|
1139
|
+
compare_structures,
|
|
1140
|
+
criterion,
|
|
1141
|
+
threshold,
|
|
1142
|
+
)
|
|
1143
|
+
params = {
|
|
1144
|
+
"response": fitted.response,
|
|
1145
|
+
"predictors": list(fitted.predictors),
|
|
1146
|
+
"model_type": model_type,
|
|
1147
|
+
"points": int(points),
|
|
1148
|
+
"interactions": interactions,
|
|
1149
|
+
"robust": robust,
|
|
1150
|
+
"weight": weight,
|
|
1151
|
+
"test_size": test_size,
|
|
1152
|
+
"degree": degree,
|
|
1153
|
+
"family": family,
|
|
1154
|
+
"link": link,
|
|
1155
|
+
"group": group,
|
|
1156
|
+
"random_slope": random_slope,
|
|
1157
|
+
"correlation": correlation,
|
|
1158
|
+
"compare_structures": compare_structures,
|
|
1159
|
+
"criterion": criterion,
|
|
1160
|
+
"threshold": threshold,
|
|
1161
|
+
}
|
|
1162
|
+
return profile_result(fitted, points, params)
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
def _goal_value(value: Any) -> float | None:
|
|
1166
|
+
if value is None:
|
|
1167
|
+
return None
|
|
1168
|
+
if isinstance(value, str) and not value.strip():
|
|
1169
|
+
return None
|
|
1170
|
+
try:
|
|
1171
|
+
parsed = float(value)
|
|
1172
|
+
except (TypeError, ValueError) as exc:
|
|
1173
|
+
raise ValueError(f"Invalid goal bound: {value!r}") from exc
|
|
1174
|
+
return parsed if math.isfinite(parsed) else None
|
|
1175
|
+
|
|
1176
|
+
|
|
1177
|
+
def _goal_name(value: Any) -> str:
|
|
1178
|
+
key = str(value or "none").strip().lower()
|
|
1179
|
+
aliases = {
|
|
1180
|
+
"none": "none",
|
|
1181
|
+
"": "none",
|
|
1182
|
+
"max": "maximize",
|
|
1183
|
+
"maximize": "maximize",
|
|
1184
|
+
"maximum": "maximize",
|
|
1185
|
+
"min": "minimize",
|
|
1186
|
+
"minimize": "minimize",
|
|
1187
|
+
"minimum": "minimize",
|
|
1188
|
+
"target": "target",
|
|
1189
|
+
"nominal": "target",
|
|
1190
|
+
"within": "within",
|
|
1191
|
+
"range": "within",
|
|
1192
|
+
"within range": "within",
|
|
1193
|
+
}
|
|
1194
|
+
if key not in aliases:
|
|
1195
|
+
raise ValueError(f"Unknown desirability goal: {value}")
|
|
1196
|
+
return aliases[key]
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
def _normalize_goals(
|
|
1200
|
+
fitted_models: dict[str, FittedRegression],
|
|
1201
|
+
goals: dict[str, dict[str, Any]] | None,
|
|
1202
|
+
) -> dict[str, dict[str, Any]]:
|
|
1203
|
+
goals = goals or {}
|
|
1204
|
+
normalized: dict[str, dict[str, Any]] = {}
|
|
1205
|
+
for response, fitted in fitted_models.items():
|
|
1206
|
+
raw = dict(goals.get(response) or {})
|
|
1207
|
+
goal = _goal_name(raw.get("goal", "none"))
|
|
1208
|
+
values = pd.to_numeric(fitted.frame[fitted.response], errors="coerce").dropna()
|
|
1209
|
+
values = values[np.isfinite(values)]
|
|
1210
|
+
observed_low = float(values.min()) if not values.empty else None
|
|
1211
|
+
observed_high = float(values.max()) if not values.empty else None
|
|
1212
|
+
low = _goal_value(raw.get("low"))
|
|
1213
|
+
high = _goal_value(raw.get("high"))
|
|
1214
|
+
target = _goal_value(raw.get("target"))
|
|
1215
|
+
weight = _goal_value(raw.get("weight"))
|
|
1216
|
+
importance = _goal_value(raw.get("importance"))
|
|
1217
|
+
weight = 1.0 if weight is None else max(weight, 1e-9)
|
|
1218
|
+
importance = 1.0 if importance is None else max(importance, 1e-9)
|
|
1219
|
+
if goal == "none":
|
|
1220
|
+
normalized[response] = {
|
|
1221
|
+
"goal": goal,
|
|
1222
|
+
"low": low,
|
|
1223
|
+
"high": high,
|
|
1224
|
+
"target": target,
|
|
1225
|
+
"weight": weight,
|
|
1226
|
+
"importance": importance,
|
|
1227
|
+
}
|
|
1228
|
+
continue
|
|
1229
|
+
if low is None:
|
|
1230
|
+
low = observed_low
|
|
1231
|
+
if high is None:
|
|
1232
|
+
high = observed_high
|
|
1233
|
+
if low is None or high is None:
|
|
1234
|
+
raise ValueError(f"{response}: enter lower and upper goal bounds.")
|
|
1235
|
+
if low > high:
|
|
1236
|
+
raise ValueError(f"{response}: lower goal bound must not exceed the upper bound.")
|
|
1237
|
+
if goal == "target":
|
|
1238
|
+
if target is None:
|
|
1239
|
+
target = (low + high) / 2
|
|
1240
|
+
if target < low or target > high:
|
|
1241
|
+
raise ValueError(f"{response}: target must be within the lower and upper bounds.")
|
|
1242
|
+
else:
|
|
1243
|
+
target = None
|
|
1244
|
+
normalized[response] = {
|
|
1245
|
+
"goal": goal,
|
|
1246
|
+
"low": low,
|
|
1247
|
+
"high": high,
|
|
1248
|
+
"target": target,
|
|
1249
|
+
"weight": weight,
|
|
1250
|
+
"importance": importance,
|
|
1251
|
+
}
|
|
1252
|
+
if not any(goal["goal"] != "none" for goal in normalized.values()):
|
|
1253
|
+
raise ValueError("Choose a desirability goal for at least one response.")
|
|
1254
|
+
return normalized
|
|
1255
|
+
|
|
1256
|
+
|
|
1257
|
+
def _optimization_variables(
|
|
1258
|
+
fitted_models: dict[str, FittedRegression],
|
|
1259
|
+
predictors: Sequence[str],
|
|
1260
|
+
) -> list[dict[str, Any]]:
|
|
1261
|
+
variables = []
|
|
1262
|
+
for name in dict.fromkeys(str(predictor) for predictor in predictors):
|
|
1263
|
+
series = [fitted.frame[name] for fitted in fitted_models.values() if name in fitted.frame.columns]
|
|
1264
|
+
if not series:
|
|
1265
|
+
continue
|
|
1266
|
+
if all(_is_numeric(item) for item in series):
|
|
1267
|
+
values = pd.concat([pd.to_numeric(item, errors="coerce") for item in series]).dropna()
|
|
1268
|
+
values = values[np.isfinite(values)]
|
|
1269
|
+
if values.empty:
|
|
1270
|
+
continue
|
|
1271
|
+
low = float(values.min())
|
|
1272
|
+
high = float(values.max())
|
|
1273
|
+
variables.append(
|
|
1274
|
+
{
|
|
1275
|
+
"name": name,
|
|
1276
|
+
"numeric": True,
|
|
1277
|
+
"low": low,
|
|
1278
|
+
"high": high,
|
|
1279
|
+
"center": float(values.median()),
|
|
1280
|
+
"levels": [],
|
|
1281
|
+
}
|
|
1282
|
+
)
|
|
1283
|
+
else:
|
|
1284
|
+
levels = []
|
|
1285
|
+
for item in series:
|
|
1286
|
+
for value in pd.unique(item.dropna()):
|
|
1287
|
+
if value not in levels:
|
|
1288
|
+
levels.append(value)
|
|
1289
|
+
if not levels:
|
|
1290
|
+
continue
|
|
1291
|
+
try:
|
|
1292
|
+
levels = sorted(levels)
|
|
1293
|
+
except TypeError:
|
|
1294
|
+
levels = sorted(levels, key=str)
|
|
1295
|
+
variables.append(
|
|
1296
|
+
{
|
|
1297
|
+
"name": name,
|
|
1298
|
+
"numeric": False,
|
|
1299
|
+
"low": None,
|
|
1300
|
+
"high": None,
|
|
1301
|
+
"center": None,
|
|
1302
|
+
"levels": levels,
|
|
1303
|
+
}
|
|
1304
|
+
)
|
|
1305
|
+
if not variables:
|
|
1306
|
+
raise ValueError("No predictors are available for optimization.")
|
|
1307
|
+
return variables
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def _categorical_combinations(variables: Sequence[dict[str, Any]], limit: int) -> list[dict[str, Any]]:
|
|
1311
|
+
categorical = [variable for variable in variables if not variable["numeric"]]
|
|
1312
|
+
count = 1
|
|
1313
|
+
for variable in categorical:
|
|
1314
|
+
count *= max(1, len(variable["levels"]))
|
|
1315
|
+
if count > max(1, int(limit)):
|
|
1316
|
+
raise ValueError(
|
|
1317
|
+
f"Too many categorical predictor combinations ({count}). "
|
|
1318
|
+
"Reduce categorical predictors or increase the combination limit."
|
|
1319
|
+
)
|
|
1320
|
+
combinations: list[dict[str, Any]] = [{}]
|
|
1321
|
+
for variable in categorical:
|
|
1322
|
+
combinations = [
|
|
1323
|
+
{**combination, variable["name"]: level}
|
|
1324
|
+
for combination in combinations
|
|
1325
|
+
for level in variable["levels"]
|
|
1326
|
+
]
|
|
1327
|
+
return combinations or [{}]
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
def _optimization_settings(fitted: FittedRegression, base: dict[str, Any], values: dict[str, Any]) -> pd.DataFrame:
|
|
1331
|
+
settings = dict(base)
|
|
1332
|
+
for name, value in values.items():
|
|
1333
|
+
if name in fitted.frame.columns:
|
|
1334
|
+
settings[name] = value
|
|
1335
|
+
return pd.DataFrame([settings])
|
|
1336
|
+
|
|
1337
|
+
|
|
1338
|
+
def _optimization_base(fitted: FittedRegression) -> dict[str, Any]:
|
|
1339
|
+
base: dict[str, Any] = {}
|
|
1340
|
+
for column in fitted.frame.columns:
|
|
1341
|
+
series = fitted.frame[column]
|
|
1342
|
+
if column in fitted.predictors:
|
|
1343
|
+
base[column] = _baseline_value(series)
|
|
1344
|
+
else:
|
|
1345
|
+
values = series.dropna()
|
|
1346
|
+
base[column] = values.iloc[0] if not values.empty else None
|
|
1347
|
+
return base
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
def _evaluate_optimization(
|
|
1351
|
+
values: dict[str, Any],
|
|
1352
|
+
fitted_models: dict[str, FittedRegression],
|
|
1353
|
+
bases: dict[str, dict[str, Any]],
|
|
1354
|
+
goals: dict[str, dict[str, Any]],
|
|
1355
|
+
) -> tuple[float, dict[str, float], dict[str, float]] | None:
|
|
1356
|
+
predictions: dict[str, float] = {}
|
|
1357
|
+
scores: dict[str, float] = {}
|
|
1358
|
+
for response, fitted in fitted_models.items():
|
|
1359
|
+
settings = _optimization_settings(fitted, bases[response], values)
|
|
1360
|
+
try:
|
|
1361
|
+
predicted = np.asarray(fitted.model.predict(settings), dtype=float).reshape(-1)
|
|
1362
|
+
except Exception:
|
|
1363
|
+
return None
|
|
1364
|
+
if predicted.size == 0 or not np.isfinite(predicted[0]):
|
|
1365
|
+
return None
|
|
1366
|
+
prediction = float(predicted[0])
|
|
1367
|
+
predictions[response] = prediction
|
|
1368
|
+
goal = goals[response]
|
|
1369
|
+
if goal["goal"] == "none":
|
|
1370
|
+
continue
|
|
1371
|
+
score = desirability_score(
|
|
1372
|
+
prediction,
|
|
1373
|
+
goal["low"],
|
|
1374
|
+
goal["high"],
|
|
1375
|
+
goal["target"],
|
|
1376
|
+
goal["weight"],
|
|
1377
|
+
goal["goal"],
|
|
1378
|
+
)
|
|
1379
|
+
if not np.isfinite(score):
|
|
1380
|
+
return None
|
|
1381
|
+
scores[response] = float(score)
|
|
1382
|
+
importance = [goals[response]["importance"] for response in scores]
|
|
1383
|
+
return overall_desirability(list(scores.values()), importance), scores, predictions
|
|
1384
|
+
|
|
1385
|
+
|
|
1386
|
+
def _model_metric(fitted: FittedRegression, name: str) -> float:
|
|
1387
|
+
model = fitted.model
|
|
1388
|
+
if name == "rsquared":
|
|
1389
|
+
value = getattr(model, "rsquared", None)
|
|
1390
|
+
if value is None:
|
|
1391
|
+
value = getattr(model, "prsquared", None)
|
|
1392
|
+
return float(value) if value is not None else float("nan")
|
|
1393
|
+
return float(getattr(model, name, float("nan")))
|
|
1394
|
+
|
|
1395
|
+
|
|
1396
|
+
def multi_response_optimize(
|
|
1397
|
+
df: pd.DataFrame,
|
|
1398
|
+
responses: Sequence[str],
|
|
1399
|
+
predictors: Sequence[str],
|
|
1400
|
+
model_type: str = "Linear",
|
|
1401
|
+
goals: dict[str, dict[str, Any]] | None = None,
|
|
1402
|
+
starts: int = 20,
|
|
1403
|
+
seed: int = 42,
|
|
1404
|
+
interactions: bool = False,
|
|
1405
|
+
robust: bool = False,
|
|
1406
|
+
weight: str | None = None,
|
|
1407
|
+
test_size: float = 0.0,
|
|
1408
|
+
degree: int = 2,
|
|
1409
|
+
family: str = "gaussian",
|
|
1410
|
+
link: str | None = None,
|
|
1411
|
+
group: str | None = None,
|
|
1412
|
+
random_slope: str | None = None,
|
|
1413
|
+
correlation: str = "exchangeable",
|
|
1414
|
+
compare_structures: bool = False,
|
|
1415
|
+
criterion: str = "pvalue",
|
|
1416
|
+
threshold: float = 0.05,
|
|
1417
|
+
max_categorical_combinations: int = 256,
|
|
1418
|
+
**_: Any,
|
|
1419
|
+
) -> AnalysisResult:
|
|
1420
|
+
response_names = list(dict.fromkeys(str(response) for response in responses if str(response)))
|
|
1421
|
+
predictor_names = list(
|
|
1422
|
+
dict.fromkeys(
|
|
1423
|
+
str(predictor)
|
|
1424
|
+
for predictor in predictors
|
|
1425
|
+
if str(predictor) and str(predictor) not in response_names
|
|
1426
|
+
)
|
|
1427
|
+
)
|
|
1428
|
+
if not response_names:
|
|
1429
|
+
raise ValueError("Choose at least one response.")
|
|
1430
|
+
if not predictor_names:
|
|
1431
|
+
raise ValueError("Choose at least one predictor.")
|
|
1432
|
+
fitted_models: dict[str, FittedRegression] = {}
|
|
1433
|
+
for response in response_names:
|
|
1434
|
+
try:
|
|
1435
|
+
fitted_models[response] = fit_regression(
|
|
1436
|
+
df,
|
|
1437
|
+
response,
|
|
1438
|
+
predictor_names,
|
|
1439
|
+
model_type,
|
|
1440
|
+
interactions,
|
|
1441
|
+
robust,
|
|
1442
|
+
weight,
|
|
1443
|
+
test_size,
|
|
1444
|
+
degree,
|
|
1445
|
+
family,
|
|
1446
|
+
link,
|
|
1447
|
+
group,
|
|
1448
|
+
random_slope,
|
|
1449
|
+
correlation,
|
|
1450
|
+
compare_structures,
|
|
1451
|
+
criterion,
|
|
1452
|
+
threshold,
|
|
1453
|
+
)
|
|
1454
|
+
except Exception as exc:
|
|
1455
|
+
raise ValueError(f"{response}: {exc}") from exc
|
|
1456
|
+
normalized_goals = _normalize_goals(fitted_models, goals)
|
|
1457
|
+
optimization_predictors = list(
|
|
1458
|
+
dict.fromkeys(
|
|
1459
|
+
predictor
|
|
1460
|
+
for fitted in fitted_models.values()
|
|
1461
|
+
for predictor in fitted.predictors
|
|
1462
|
+
if predictor in predictor_names
|
|
1463
|
+
)
|
|
1464
|
+
)
|
|
1465
|
+
variables = _optimization_variables(fitted_models, optimization_predictors)
|
|
1466
|
+
combinations = _categorical_combinations(variables, max_categorical_combinations)
|
|
1467
|
+
numeric = [variable for variable in variables if variable["numeric"]]
|
|
1468
|
+
bases = {response: _optimization_base(fitted) for response, fitted in fitted_models.items()}
|
|
1469
|
+
rng = np.random.default_rng(seed)
|
|
1470
|
+
per_combination = max(1, int(starts) // max(1, len(combinations)))
|
|
1471
|
+
best: dict[str, Any] | None = None
|
|
1472
|
+
|
|
1473
|
+
def consider(values: dict[str, Any]) -> None:
|
|
1474
|
+
nonlocal best
|
|
1475
|
+
evaluation = _evaluate_optimization(values, fitted_models, bases, normalized_goals)
|
|
1476
|
+
if evaluation is None:
|
|
1477
|
+
return
|
|
1478
|
+
score, individual, predictions = evaluation
|
|
1479
|
+
if best is None or score > best["score"]:
|
|
1480
|
+
best = {
|
|
1481
|
+
"score": score,
|
|
1482
|
+
"individual": individual,
|
|
1483
|
+
"predictions": predictions,
|
|
1484
|
+
"values": dict(values),
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
for combination in combinations:
|
|
1488
|
+
if not numeric:
|
|
1489
|
+
consider(combination)
|
|
1490
|
+
continue
|
|
1491
|
+
bounds = [(variable["low"], variable["high"]) for variable in numeric]
|
|
1492
|
+
start_values = [np.asarray([variable["center"] for variable in numeric], dtype=float)]
|
|
1493
|
+
for _ in range(per_combination - 1):
|
|
1494
|
+
start_values.append(
|
|
1495
|
+
np.asarray(
|
|
1496
|
+
[rng.uniform(variable["low"], variable["high"]) for variable in numeric],
|
|
1497
|
+
dtype=float,
|
|
1498
|
+
)
|
|
1499
|
+
)
|
|
1500
|
+
|
|
1501
|
+
def objective(vector: np.ndarray) -> float:
|
|
1502
|
+
values = dict(combination)
|
|
1503
|
+
values.update({variable["name"]: float(value) for variable, value in zip(numeric, vector)})
|
|
1504
|
+
evaluation = _evaluate_optimization(values, fitted_models, bases, normalized_goals)
|
|
1505
|
+
return 1e6 if evaluation is None else -evaluation[0]
|
|
1506
|
+
|
|
1507
|
+
for start in start_values:
|
|
1508
|
+
start_settings = dict(combination)
|
|
1509
|
+
start_settings.update({variable["name"]: float(value) for variable, value in zip(numeric, start)})
|
|
1510
|
+
consider(start_settings)
|
|
1511
|
+
try:
|
|
1512
|
+
outcome = minimize(objective, start, bounds=bounds, method="L-BFGS-B")
|
|
1513
|
+
except Exception:
|
|
1514
|
+
continue
|
|
1515
|
+
values = dict(combination)
|
|
1516
|
+
values.update({variable["name"]: float(value) for variable, value in zip(numeric, outcome.x)})
|
|
1517
|
+
consider(values)
|
|
1518
|
+
if best is None:
|
|
1519
|
+
raise ValueError("Optimization failed. Try different goals or goal bounds.")
|
|
1520
|
+
|
|
1521
|
+
score = float(best["score"])
|
|
1522
|
+
individual = best["individual"]
|
|
1523
|
+
predictions = best["predictions"]
|
|
1524
|
+
values = best["values"]
|
|
1525
|
+
row: dict[str, Any] = {"Overall Desirability": score}
|
|
1526
|
+
for variable in variables:
|
|
1527
|
+
value = values.get(variable["name"])
|
|
1528
|
+
row[variable["name"]] = float(value) if variable["numeric"] else str(value)
|
|
1529
|
+
for response in response_names:
|
|
1530
|
+
row[f"Predicted {response}"] = predictions[response]
|
|
1531
|
+
if response in individual:
|
|
1532
|
+
row[f"Desirability {response}"] = individual[response]
|
|
1533
|
+
detail_rows = []
|
|
1534
|
+
for response in response_names:
|
|
1535
|
+
goal = normalized_goals[response]
|
|
1536
|
+
detail_rows.append(
|
|
1537
|
+
{
|
|
1538
|
+
"Response": response,
|
|
1539
|
+
"Goal": goal["goal"].title(),
|
|
1540
|
+
"Lower": goal["low"],
|
|
1541
|
+
"Upper": goal["high"],
|
|
1542
|
+
"Target": goal["target"],
|
|
1543
|
+
"Weight": goal["weight"],
|
|
1544
|
+
"Importance": goal["importance"],
|
|
1545
|
+
"Prediction": predictions[response],
|
|
1546
|
+
"Desirability": individual.get(response, np.nan),
|
|
1547
|
+
}
|
|
1548
|
+
)
|
|
1549
|
+
detail = pd.DataFrame(detail_rows)
|
|
1550
|
+
model_rows = []
|
|
1551
|
+
for response, fitted in fitted_models.items():
|
|
1552
|
+
model_rows.append(
|
|
1553
|
+
{
|
|
1554
|
+
"Response": response,
|
|
1555
|
+
"Model": fitted.kind.title(),
|
|
1556
|
+
"N": int(getattr(fitted.model, "nobs", len(fitted.frame))),
|
|
1557
|
+
"Predictors": ", ".join(fitted.predictors),
|
|
1558
|
+
"R-squared": _model_metric(fitted, "rsquared"),
|
|
1559
|
+
"AIC": _model_metric(fitted, "aic"),
|
|
1560
|
+
}
|
|
1561
|
+
)
|
|
1562
|
+
result = AnalysisResult(
|
|
1563
|
+
title=f"Multi-Response Optimization: {', '.join(response_names)}",
|
|
1564
|
+
analysis_type="regression_multi_response_optimization",
|
|
1565
|
+
params={
|
|
1566
|
+
"responses": response_names,
|
|
1567
|
+
"predictors": predictor_names,
|
|
1568
|
+
"model_type": model_type,
|
|
1569
|
+
"goals": normalized_goals,
|
|
1570
|
+
"starts": int(starts),
|
|
1571
|
+
"seed": int(seed),
|
|
1572
|
+
"interactions": interactions,
|
|
1573
|
+
"robust": robust,
|
|
1574
|
+
"weight": weight,
|
|
1575
|
+
"test_size": test_size,
|
|
1576
|
+
"degree": degree,
|
|
1577
|
+
"family": family,
|
|
1578
|
+
"link": link,
|
|
1579
|
+
"group": group,
|
|
1580
|
+
"random_slope": random_slope,
|
|
1581
|
+
"correlation": correlation,
|
|
1582
|
+
"compare_structures": compare_structures,
|
|
1583
|
+
"criterion": criterion,
|
|
1584
|
+
"threshold": threshold,
|
|
1585
|
+
"max_categorical_combinations": int(max_categorical_combinations),
|
|
1586
|
+
},
|
|
1587
|
+
)
|
|
1588
|
+
result.add_table("Optimal Settings", pd.DataFrame([row]))
|
|
1589
|
+
result.add_table("Response Desirability", detail)
|
|
1590
|
+
result.add_table("Response Models", pd.DataFrame(model_rows))
|
|
1591
|
+
plot_detail = detail[detail["Desirability"].notna()]
|
|
1592
|
+
result.add_plot("bar", {"x": "Response", "y": "Desirability"}, title="Desirability by Response", data=plot_detail)
|
|
1593
|
+
result.add_model("regression_models", fitted_models)
|
|
1594
|
+
result.summary = f"Overall desirability = {score:.4f} across {len(individual)} active response(s)."
|
|
1595
|
+
result.notes = (
|
|
1596
|
+
"Numeric predictors are optimized within their observed ranges; categorical predictors use "
|
|
1597
|
+
"observed levels in the desirability plot and optimal settings. Search is local and may depend "
|
|
1598
|
+
"on the number of starts."
|
|
1599
|
+
)
|
|
1600
|
+
return result
|