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,1094 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from typing import Any, Sequence
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
from statstudio.stats.results import AnalysisResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _backend():
|
|
13
|
+
try:
|
|
14
|
+
import arviz as az
|
|
15
|
+
import pymc as pm
|
|
16
|
+
except Exception as exc:
|
|
17
|
+
raise ValueError(
|
|
18
|
+
"Bayesian analyses require PyMC and ArviZ. Install the optional 'bayesian' extra, e.g. "
|
|
19
|
+
"pip install 'statstudio[bayesian]'."
|
|
20
|
+
) from exc
|
|
21
|
+
return pm, az
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _clean_numeric(df: pd.DataFrame, columns: Sequence[str]) -> pd.DataFrame:
|
|
25
|
+
missing = [column for column in columns if column not in df.columns]
|
|
26
|
+
if missing:
|
|
27
|
+
raise KeyError(f"Missing columns: {', '.join(missing)}")
|
|
28
|
+
frame = df.loc[:, list(columns)].copy()
|
|
29
|
+
for column in columns:
|
|
30
|
+
frame[column] = pd.to_numeric(frame[column], errors="coerce")
|
|
31
|
+
frame = frame.replace([np.inf, -np.inf], np.nan).dropna()
|
|
32
|
+
if len(frame) < 8:
|
|
33
|
+
raise ValueError("At least eight complete observations are required for a Bayesian model.")
|
|
34
|
+
return frame
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _clean_regression(frame: pd.DataFrame, response: str, predictors: Sequence[str]) -> tuple[pd.DataFrame, list[str]]:
|
|
38
|
+
predictors = [predictor for predictor in dict.fromkeys(predictors) if predictor != response]
|
|
39
|
+
if not predictors:
|
|
40
|
+
raise ValueError("Select at least one predictor.")
|
|
41
|
+
cleaned = _clean_numeric(frame, [response, *predictors])
|
|
42
|
+
if cleaned[response].std(ddof=0) == 0:
|
|
43
|
+
raise ValueError("The response column must vary.")
|
|
44
|
+
constant = [column for column in predictors if cleaned[column].std(ddof=0) == 0]
|
|
45
|
+
if constant:
|
|
46
|
+
raise ValueError(f"Predictors must vary: {', '.join(constant)}")
|
|
47
|
+
return cleaned, predictors
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _clean_binary(
|
|
51
|
+
frame: pd.DataFrame,
|
|
52
|
+
response: str,
|
|
53
|
+
predictors: Sequence[str] = (),
|
|
54
|
+
event_level: str | None = None,
|
|
55
|
+
) -> tuple[pd.DataFrame, np.ndarray, list[str]]:
|
|
56
|
+
if response not in frame.columns:
|
|
57
|
+
raise KeyError(response)
|
|
58
|
+
columns = [response, *[str(predictor) for predictor in predictors if str(predictor) != response]]
|
|
59
|
+
missing = [column for column in columns if column not in frame.columns]
|
|
60
|
+
if missing:
|
|
61
|
+
raise KeyError(f"Missing columns: {', '.join(missing)}")
|
|
62
|
+
work = frame.loc[:, list(dict.fromkeys(columns))].copy()
|
|
63
|
+
numeric = pd.to_numeric(work[response], errors="coerce")
|
|
64
|
+
values = numeric.dropna()
|
|
65
|
+
if len(values) and set(values.unique()).issubset({0.0, 1.0}):
|
|
66
|
+
work[response] = numeric
|
|
67
|
+
levels = ["0", "1"]
|
|
68
|
+
else:
|
|
69
|
+
text = work[response].astype("string")
|
|
70
|
+
work = work.loc[text.notna()]
|
|
71
|
+
text = text.loc[text.notna()]
|
|
72
|
+
levels = sorted(pd.unique(text).tolist())
|
|
73
|
+
if len(levels) != 2:
|
|
74
|
+
raise ValueError(f"Logistic regression requires exactly two response levels; found {len(levels)}.")
|
|
75
|
+
if event_level is not None:
|
|
76
|
+
selected = str(event_level)
|
|
77
|
+
if selected not in levels:
|
|
78
|
+
raise ValueError(f"Event level {selected!r} is not present in {response!r}.")
|
|
79
|
+
levels = [level for level in levels if level != selected] + [selected]
|
|
80
|
+
work[response] = (text == levels[1]).astype(int)
|
|
81
|
+
work = work.replace([np.inf, -np.inf], np.nan).dropna()
|
|
82
|
+
if len(work) < 8:
|
|
83
|
+
raise ValueError("At least eight complete observations are required for a Bayesian model.")
|
|
84
|
+
return work, work[response].to_numpy(dtype=int), [str(level) for level in levels]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _clean_group(frame: pd.DataFrame, response: str, group: str, minimum: int = 2) -> tuple[pd.DataFrame, np.ndarray, list[str]]:
|
|
88
|
+
if response not in frame.columns:
|
|
89
|
+
raise KeyError(response)
|
|
90
|
+
if group not in frame.columns:
|
|
91
|
+
raise KeyError(group)
|
|
92
|
+
if group == response:
|
|
93
|
+
raise ValueError("The grouping column must be different from the response.")
|
|
94
|
+
cleaned = frame.loc[:, [response, group]].copy()
|
|
95
|
+
cleaned[response] = pd.to_numeric(cleaned[response], errors="coerce")
|
|
96
|
+
cleaned = cleaned.replace([np.inf, -np.inf], np.nan).dropna()
|
|
97
|
+
levels = sorted(cleaned[group].astype(str).unique().tolist())
|
|
98
|
+
if len(levels) < minimum:
|
|
99
|
+
raise ValueError(f"The grouping column needs at least {minimum} levels.")
|
|
100
|
+
labels = cleaned[group].astype(str)
|
|
101
|
+
cleaned["__group_index__"] = labels.map({level: index for index, level in enumerate(levels)}).astype(int)
|
|
102
|
+
if len(cleaned) < 8:
|
|
103
|
+
raise ValueError("At least eight complete observations are required for a Bayesian model.")
|
|
104
|
+
if cleaned[response].std(ddof=0) == 0:
|
|
105
|
+
raise ValueError("The response column must vary.")
|
|
106
|
+
return cleaned, cleaned["__group_index__"].to_numpy(dtype=int), levels
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _check_sampling(draws: int, tune: int, chains: int, target_accept: float) -> None:
|
|
110
|
+
if draws < 100:
|
|
111
|
+
raise ValueError("At least 100 posterior draws are required.")
|
|
112
|
+
if tune < 0:
|
|
113
|
+
raise ValueError("Tuning steps cannot be negative.")
|
|
114
|
+
if chains < 1:
|
|
115
|
+
raise ValueError("At least one chain is required.")
|
|
116
|
+
if not 0 < target_accept < 1:
|
|
117
|
+
raise ValueError("Target acceptance must be between 0 and 1.")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _check_hdi(value: float) -> float:
|
|
121
|
+
if not 0 < value < 1:
|
|
122
|
+
raise ValueError("Credible-interval mass must be between 0 and 1.")
|
|
123
|
+
return value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _check_positive(value: float, name: str) -> float:
|
|
127
|
+
value = float(value)
|
|
128
|
+
if value <= 0:
|
|
129
|
+
raise ValueError(f"{name} must be positive.")
|
|
130
|
+
return value
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _check_improvement_pct(value: float | None) -> float | None:
|
|
134
|
+
if value is None:
|
|
135
|
+
return None
|
|
136
|
+
value = float(value)
|
|
137
|
+
if not math.isfinite(value) or value < 0:
|
|
138
|
+
raise ValueError("Improvement threshold must be zero or a positive percentage.")
|
|
139
|
+
return value
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _check_improvement_direction(value: str) -> str:
|
|
143
|
+
key = str(value or "group2").strip().lower().replace("_", " ")
|
|
144
|
+
if key in {"group2", "group 2", "second", "2", "group 2 over group 1"}:
|
|
145
|
+
return "group2"
|
|
146
|
+
if key in {"group1", "group 1", "first", "1", "group 1 over group 2"}:
|
|
147
|
+
return "group1"
|
|
148
|
+
raise ValueError("Improvement direction must be 'group1' or 'group2'.")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _sample(pm, model, draws: int, tune: int, chains: int, target_accept: float, seed: int):
|
|
152
|
+
with model:
|
|
153
|
+
idata = pm.sample(
|
|
154
|
+
draws=draws,
|
|
155
|
+
tune=tune,
|
|
156
|
+
chains=chains,
|
|
157
|
+
cores=min(2, chains),
|
|
158
|
+
target_accept=target_accept,
|
|
159
|
+
random_seed=seed,
|
|
160
|
+
progressbar=False,
|
|
161
|
+
return_inferencedata=True,
|
|
162
|
+
compute_convergence_checks=False,
|
|
163
|
+
)
|
|
164
|
+
try:
|
|
165
|
+
if "log_likelihood" not in idata.groups():
|
|
166
|
+
pm.compute_log_likelihood(idata)
|
|
167
|
+
except Exception:
|
|
168
|
+
pass
|
|
169
|
+
return idata
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _flat(idata, name: str) -> np.ndarray:
|
|
173
|
+
values = np.asarray(idata.posterior[name].values, dtype=float)
|
|
174
|
+
if values.ndim <= 2:
|
|
175
|
+
return values.reshape(-1)
|
|
176
|
+
return values.reshape(-1, values.shape[-1])
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _hdi(values: Sequence[float], probability: float) -> tuple[float, float]:
|
|
180
|
+
array = np.asarray(values, dtype=float).reshape(-1)
|
|
181
|
+
array = array[np.isfinite(array)]
|
|
182
|
+
if array.size == 0:
|
|
183
|
+
return math.nan, math.nan
|
|
184
|
+
array = np.sort(array)
|
|
185
|
+
count = min(max(int(math.floor(probability * array.size)), 0), array.size - 1)
|
|
186
|
+
if count == 0:
|
|
187
|
+
return float(array[0]), float(array[0])
|
|
188
|
+
widths = array[count:] - array[: array.size - count]
|
|
189
|
+
start = int(np.argmin(widths))
|
|
190
|
+
return float(array[start]), float(array[start + count])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _interval_labels(probability: float) -> tuple[str, str]:
|
|
196
|
+
tail = (1.0 - probability) / 2.0 * 100.0
|
|
197
|
+
return f"HDI {tail:.1f}%", f"HDI {100.0 - tail:.1f}%"
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _summary(az, idata, variables: Sequence[str], hdi_prob: float):
|
|
201
|
+
try:
|
|
202
|
+
return az.summary(idata, var_names=list(variables), hdi_prob=hdi_prob, round_to=None)
|
|
203
|
+
except Exception:
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _summary_row(summary, name: str):
|
|
208
|
+
if summary is None:
|
|
209
|
+
return None
|
|
210
|
+
try:
|
|
211
|
+
if name in summary.index:
|
|
212
|
+
return summary.loc[name]
|
|
213
|
+
except Exception:
|
|
214
|
+
pass
|
|
215
|
+
for index in summary.index:
|
|
216
|
+
if str(index) == name:
|
|
217
|
+
return summary.loc[index]
|
|
218
|
+
return None
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _summary_stat(summary, name: str, column: str) -> float:
|
|
222
|
+
row = _summary_row(summary, name)
|
|
223
|
+
if row is None:
|
|
224
|
+
return math.nan
|
|
225
|
+
try:
|
|
226
|
+
return float(row[column])
|
|
227
|
+
except Exception:
|
|
228
|
+
return math.nan
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _convergence(summary, variables: Sequence[str]) -> tuple[float, float, float, float]:
|
|
232
|
+
rhats: list[float] = []
|
|
233
|
+
ess_bulk: list[float] = []
|
|
234
|
+
ess_tail: list[float] = []
|
|
235
|
+
mcse: list[float] = []
|
|
236
|
+
if summary is not None:
|
|
237
|
+
for index in summary.index:
|
|
238
|
+
name = str(index)
|
|
239
|
+
if not any(name == variable or name.startswith(f"{variable}[") for variable in variables):
|
|
240
|
+
continue
|
|
241
|
+
row = summary.loc[index]
|
|
242
|
+
for target, column in (
|
|
243
|
+
(rhats, "r_hat"),
|
|
244
|
+
(ess_bulk, "ess_bulk"),
|
|
245
|
+
(ess_tail, "ess_tail"),
|
|
246
|
+
(mcse, "mcse_mean"),
|
|
247
|
+
):
|
|
248
|
+
try:
|
|
249
|
+
value = float(row[column])
|
|
250
|
+
if np.isfinite(value):
|
|
251
|
+
target.append(value)
|
|
252
|
+
except Exception:
|
|
253
|
+
pass
|
|
254
|
+
return (
|
|
255
|
+
max(rhats) if rhats else math.nan,
|
|
256
|
+
min(ess_bulk) if ess_bulk else math.nan,
|
|
257
|
+
min(ess_tail) if ess_tail else math.nan,
|
|
258
|
+
max(mcse) if mcse else math.nan,
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _diagnostics_table(idata, summary, variables: Sequence[str]) -> pd.DataFrame:
|
|
263
|
+
max_rhat, min_ess_bulk, min_ess_tail, max_mcse = _convergence(summary, variables)
|
|
264
|
+
try:
|
|
265
|
+
diverging = int(idata.sample_stats["diverging"].sum().item())
|
|
266
|
+
except Exception:
|
|
267
|
+
diverging = 0
|
|
268
|
+
chains = int(idata.posterior.sizes.get("chain", 1))
|
|
269
|
+
draws = int(idata.posterior.sizes.get("draw", 0))
|
|
270
|
+
warnings: list[str] = []
|
|
271
|
+
if diverging:
|
|
272
|
+
warnings.append(f"{diverging} divergent transition(s)")
|
|
273
|
+
if np.isfinite(max_rhat) and max_rhat > 1.01:
|
|
274
|
+
warnings.append(f"maximum R-hat {max_rhat:.3f} > 1.01")
|
|
275
|
+
if np.isfinite(min_ess_bulk) and min_ess_bulk < 100:
|
|
276
|
+
warnings.append(f"minimum bulk ESS {min_ess_bulk:.1f} < 100")
|
|
277
|
+
if chains < 2:
|
|
278
|
+
warnings.append("only one chain; R-hat is not informative")
|
|
279
|
+
rows = [
|
|
280
|
+
("Chains", chains),
|
|
281
|
+
("Draws per chain", draws),
|
|
282
|
+
("Total posterior draws", chains * draws),
|
|
283
|
+
("Divergent transitions", diverging),
|
|
284
|
+
("Maximum R-hat", max_rhat),
|
|
285
|
+
("Minimum ESS (bulk)", min_ess_bulk),
|
|
286
|
+
("Minimum ESS (tail)", min_ess_tail),
|
|
287
|
+
("Maximum MCSE", max_mcse),
|
|
288
|
+
("Convergence warning", "; ".join(warnings) if warnings else "None"),
|
|
289
|
+
]
|
|
290
|
+
return pd.DataFrame(rows, columns=["Diagnostic", "Value"])
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _fit_table(
|
|
294
|
+
az,
|
|
295
|
+
idata,
|
|
296
|
+
n_observations: int,
|
|
297
|
+
terms: int,
|
|
298
|
+
draws: int,
|
|
299
|
+
chains: int,
|
|
300
|
+
hdi_prob: float,
|
|
301
|
+
extra: Sequence[tuple[str, Any]] = (),
|
|
302
|
+
term_label: str = "Predictors",
|
|
303
|
+
) -> pd.DataFrame:
|
|
304
|
+
rows: list[tuple[str, Any]] = [
|
|
305
|
+
("N", n_observations),
|
|
306
|
+
(term_label, terms),
|
|
307
|
+
("Chains", chains),
|
|
308
|
+
("Draws per chain", draws),
|
|
309
|
+
("Credible interval", f"{hdi_prob:.0%}"),
|
|
310
|
+
]
|
|
311
|
+
rows.extend(extra)
|
|
312
|
+
try:
|
|
313
|
+
loo = az.loo(idata)
|
|
314
|
+
rows.extend(
|
|
315
|
+
[
|
|
316
|
+
("LOO ELPD", float(getattr(loo, "elpd_loo", math.nan))),
|
|
317
|
+
("LOO SE", float(getattr(loo, "se", math.nan))),
|
|
318
|
+
("LOO p", float(getattr(loo, "p_loo", math.nan))),
|
|
319
|
+
]
|
|
320
|
+
)
|
|
321
|
+
except Exception:
|
|
322
|
+
pass
|
|
323
|
+
try:
|
|
324
|
+
waic = az.waic(idata)
|
|
325
|
+
rows.extend(
|
|
326
|
+
[
|
|
327
|
+
("WAIC", float(getattr(waic, "elpd_waic", math.nan))),
|
|
328
|
+
("WAIC SE", float(getattr(waic, "se", math.nan))),
|
|
329
|
+
]
|
|
330
|
+
)
|
|
331
|
+
except Exception:
|
|
332
|
+
pass
|
|
333
|
+
return pd.DataFrame(rows, columns=["Metric", "Value"])
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _specification_table(likelihood: str, priors: Sequence[str]) -> pd.DataFrame:
|
|
337
|
+
rows = [("Likelihood", likelihood)]
|
|
338
|
+
rows.extend((f"Prior {index + 1}", prior) for index, prior in enumerate(priors))
|
|
339
|
+
return pd.DataFrame(rows, columns=["Model Component", "Specification"])
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _coefficient_row(
|
|
343
|
+
term: str,
|
|
344
|
+
samples: np.ndarray,
|
|
345
|
+
summary,
|
|
346
|
+
summary_name: str,
|
|
347
|
+
hdi_prob: float,
|
|
348
|
+
exponential: bool = False,
|
|
349
|
+
) -> dict[str, Any]:
|
|
350
|
+
low, high = _hdi(samples, hdi_prob)
|
|
351
|
+
row: dict[str, Any] = {
|
|
352
|
+
"Term": term,
|
|
353
|
+
"Mean": float(np.mean(samples)),
|
|
354
|
+
"SD": float(np.std(samples, ddof=1)),
|
|
355
|
+
"HDI Low": low,
|
|
356
|
+
"HDI High": high,
|
|
357
|
+
"R-hat": _summary_stat(summary, summary_name, "r_hat"),
|
|
358
|
+
"ESS Bulk": _summary_stat(summary, summary_name, "ess_bulk"),
|
|
359
|
+
}
|
|
360
|
+
if exponential:
|
|
361
|
+
row["Odds Ratio"] = math.exp(row["Mean"])
|
|
362
|
+
row["OR HDI Low"] = math.exp(low)
|
|
363
|
+
row["OR HDI High"] = math.exp(high)
|
|
364
|
+
return row
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _posterior_long(idata, arrays: Sequence[tuple[str, np.ndarray]]) -> pd.DataFrame:
|
|
368
|
+
chains = int(idata.posterior.sizes.get("chain", 1))
|
|
369
|
+
draws = int(idata.posterior.sizes.get("draw", 0))
|
|
370
|
+
chain_values = np.repeat(np.arange(chains), draws)
|
|
371
|
+
draw_values = np.tile(np.arange(draws), chains)
|
|
372
|
+
frames = []
|
|
373
|
+
for label, values in arrays:
|
|
374
|
+
values = np.asarray(values, dtype=float)
|
|
375
|
+
columns = [values] if values.ndim == 1 else [values[:, index] for index in range(values.shape[1])]
|
|
376
|
+
for column in columns:
|
|
377
|
+
frames.append(
|
|
378
|
+
pd.DataFrame(
|
|
379
|
+
{
|
|
380
|
+
"Parameter": label,
|
|
381
|
+
"Chain": chain_values,
|
|
382
|
+
"Draw": draw_values,
|
|
383
|
+
"Value": column.reshape(-1),
|
|
384
|
+
}
|
|
385
|
+
)
|
|
386
|
+
)
|
|
387
|
+
return pd.concat(frames, ignore_index=True) if frames else pd.DataFrame(columns=["Parameter", "Chain", "Draw", "Value"])
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _forest_frame(rows: Sequence[dict[str, Any]]) -> pd.DataFrame:
|
|
391
|
+
return pd.DataFrame(
|
|
392
|
+
[{"Term": row["Term"], "Mean": row["Mean"], "HDI Low": row["HDI Low"], "HDI High": row["HDI High"]} for row in rows]
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _ppc_frame(observed: np.ndarray, predicted: np.ndarray, lower: np.ndarray, upper: np.ndarray) -> pd.DataFrame:
|
|
397
|
+
return pd.DataFrame(
|
|
398
|
+
{
|
|
399
|
+
"Index": np.arange(1, len(observed) + 1),
|
|
400
|
+
"Observed": np.asarray(observed, dtype=float),
|
|
401
|
+
"Predicted": np.asarray(predicted, dtype=float),
|
|
402
|
+
"Lower": np.asarray(lower, dtype=float),
|
|
403
|
+
"Upper": np.asarray(upper, dtype=float),
|
|
404
|
+
}
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _interval(values: np.ndarray, probability: float) -> tuple[np.ndarray, np.ndarray]:
|
|
409
|
+
tail = (1.0 - probability) / 2.0 * 100.0
|
|
410
|
+
return np.percentile(values, tail, axis=0), np.percentile(values, 100.0 - tail, axis=0)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def bayesian_linear_regression(
|
|
414
|
+
df: pd.DataFrame,
|
|
415
|
+
response: str,
|
|
416
|
+
predictors: Sequence[str],
|
|
417
|
+
*,
|
|
418
|
+
prior_scale: float = 2.5,
|
|
419
|
+
sigma_prior: float = 1.0,
|
|
420
|
+
hdi_prob: float = 0.95,
|
|
421
|
+
draws: int = 500,
|
|
422
|
+
tune: int = 500,
|
|
423
|
+
chains: int = 2,
|
|
424
|
+
target_accept: float = 0.9,
|
|
425
|
+
seed: int = 42,
|
|
426
|
+
) -> AnalysisResult:
|
|
427
|
+
pm, az = _backend()
|
|
428
|
+
prior_scale = _check_positive(prior_scale, "Prior scale")
|
|
429
|
+
sigma_prior = _check_positive(sigma_prior, "Sigma prior")
|
|
430
|
+
hdi_prob = _check_hdi(hdi_prob)
|
|
431
|
+
_check_sampling(draws, tune, chains, target_accept)
|
|
432
|
+
frame, predictors = _clean_regression(df, response, predictors)
|
|
433
|
+
|
|
434
|
+
x = frame[predictors].to_numpy(dtype=float)
|
|
435
|
+
y = frame[response].to_numpy(dtype=float)
|
|
436
|
+
x_mean = x.mean(axis=0)
|
|
437
|
+
x_sd = x.std(axis=0, ddof=0)
|
|
438
|
+
x_sd[x_sd == 0] = 1.0
|
|
439
|
+
y_mean = float(y.mean())
|
|
440
|
+
y_sd = float(y.std(ddof=0)) or 1.0
|
|
441
|
+
xs = (x - x_mean) / x_sd
|
|
442
|
+
ys = (y - y_mean) / y_sd
|
|
443
|
+
|
|
444
|
+
with pm.Model() as model:
|
|
445
|
+
alpha = pm.Normal("alpha", mu=0.0, sigma=2.5)
|
|
446
|
+
beta = pm.Normal("beta", mu=0.0, sigma=prior_scale, shape=len(predictors))
|
|
447
|
+
sigma = pm.HalfNormal("sigma", sigma=sigma_prior)
|
|
448
|
+
mu = pm.Deterministic("mu", alpha + pm.math.dot(xs, beta))
|
|
449
|
+
pm.Normal("y", mu=mu, sigma=sigma, observed=ys)
|
|
450
|
+
|
|
451
|
+
idata = _sample(pm, model, draws, tune, chains, target_accept, seed)
|
|
452
|
+
summary = _summary(az, idata, ["alpha", "beta", "sigma"], hdi_prob)
|
|
453
|
+
|
|
454
|
+
alpha_std = _flat(idata, "alpha")
|
|
455
|
+
beta_std = _flat(idata, "beta")
|
|
456
|
+
sigma_std = _flat(idata, "sigma")
|
|
457
|
+
beta_raw = beta_std * (y_sd / x_sd)
|
|
458
|
+
alpha_raw = y_mean + y_sd * (alpha_std - np.sum(beta_std * x_mean / x_sd, axis=1))
|
|
459
|
+
sigma_raw = sigma_std * y_sd
|
|
460
|
+
|
|
461
|
+
rows = [
|
|
462
|
+
_coefficient_row("Intercept", alpha_raw, summary, "alpha", hdi_prob),
|
|
463
|
+
]
|
|
464
|
+
rows.extend(
|
|
465
|
+
_coefficient_row(predictor, beta_raw[:, index], summary, f"beta[{index}]", hdi_prob)
|
|
466
|
+
for index, predictor in enumerate(predictors)
|
|
467
|
+
)
|
|
468
|
+
coefficient_frame = pd.DataFrame(rows)
|
|
469
|
+
low_label, high_label = _interval_labels(hdi_prob)
|
|
470
|
+
coefficient_frame = coefficient_frame.rename(columns={"HDI Low": low_label, "HDI High": high_label})
|
|
471
|
+
|
|
472
|
+
y_hat = alpha_raw[:, None] + beta_raw @ x.T
|
|
473
|
+
residual = y[None, :] - y_hat
|
|
474
|
+
r2 = 1.0 - np.var(residual, axis=1) / max(float(np.var(y)), 1e-12)
|
|
475
|
+
fit_frame = _fit_table(
|
|
476
|
+
az,
|
|
477
|
+
idata,
|
|
478
|
+
len(frame),
|
|
479
|
+
len(predictors),
|
|
480
|
+
draws,
|
|
481
|
+
chains,
|
|
482
|
+
hdi_prob,
|
|
483
|
+
(
|
|
484
|
+
("Posterior mean R-squared", float(np.mean(r2))),
|
|
485
|
+
("Posterior mean residual SD", float(np.mean(sigma_raw))),
|
|
486
|
+
),
|
|
487
|
+
)
|
|
488
|
+
diagnostics = _diagnostics_table(idata, summary, ["alpha", "beta", "sigma"])
|
|
489
|
+
specification = _specification_table(
|
|
490
|
+
"Normal(alpha + X_std beta, sigma); X and y standardized",
|
|
491
|
+
(
|
|
492
|
+
"alpha ~ Normal(0, 2.5)",
|
|
493
|
+
f"beta ~ Normal(0, {prior_scale:g})",
|
|
494
|
+
f"sigma ~ HalfNormal({sigma_prior:g})",
|
|
495
|
+
"Coefficient and sigma priors apply on the standardized scale",
|
|
496
|
+
),
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
rng = np.random.default_rng(seed)
|
|
500
|
+
sample_index = rng.choice(len(alpha_raw), size=min(200, len(alpha_raw)), replace=False)
|
|
501
|
+
y_rep = rng.normal(y_hat[sample_index], sigma_raw[sample_index, None])
|
|
502
|
+
lower, upper = _interval(y_rep, hdi_prob)
|
|
503
|
+
ppc = _ppc_frame(y, np.mean(y_hat[sample_index], axis=0), lower, upper)
|
|
504
|
+
trace = _posterior_long(
|
|
505
|
+
idata,
|
|
506
|
+
[("Intercept", alpha_raw), *[(predictor, beta_raw[:, index]) for index, predictor in enumerate(predictors)], ("Sigma", sigma_raw)],
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
result = AnalysisResult(
|
|
510
|
+
title=f"Bayesian Linear Regression: {response}",
|
|
511
|
+
analysis_type="bayesian_linear_regression",
|
|
512
|
+
params={
|
|
513
|
+
"response": response,
|
|
514
|
+
"predictors": predictors,
|
|
515
|
+
"prior_scale": prior_scale,
|
|
516
|
+
"sigma_prior": sigma_prior,
|
|
517
|
+
"hdi_prob": hdi_prob,
|
|
518
|
+
"draws": draws,
|
|
519
|
+
"tune": tune,
|
|
520
|
+
"chains": chains,
|
|
521
|
+
"target_accept": target_accept,
|
|
522
|
+
"seed": seed,
|
|
523
|
+
},
|
|
524
|
+
)
|
|
525
|
+
result.add_table("Posterior Coefficients", coefficient_frame)
|
|
526
|
+
result.add_table("Model Fit", fit_frame)
|
|
527
|
+
result.add_table("MCMC Diagnostics", diagnostics)
|
|
528
|
+
result.add_table("Model Specification", specification)
|
|
529
|
+
result.add_plot("bayes_trace", {"parameters": ["Intercept", *predictors, "Sigma"]}, title="Posterior Trace", data=trace)
|
|
530
|
+
result.add_plot("bayes_forest", {}, title="Coefficient Intervals", data=_forest_frame(rows))
|
|
531
|
+
result.add_plot("bayes_posterior", {"parameters": ["Intercept", *predictors, "Sigma"]}, title="Posterior Densities", data=trace)
|
|
532
|
+
result.add_plot("bayes_ppc", {}, title="Posterior Predictive Check", data=ppc)
|
|
533
|
+
result.add_model("idata", idata)
|
|
534
|
+
result.summary = (
|
|
535
|
+
f"Bayesian linear regression for {response} with {len(predictors)} predictor(s), "
|
|
536
|
+
f"{chains} chains and {draws} draws per chain."
|
|
537
|
+
)
|
|
538
|
+
result.notes = (
|
|
539
|
+
"Predictors and the response are standardized for fitting; coefficients are transformed back to the "
|
|
540
|
+
"original scales. Posterior intervals are highest-density intervals. LOO/WAIC are shown when available."
|
|
541
|
+
)
|
|
542
|
+
return result
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def bayesian_logistic_regression(
|
|
546
|
+
df: pd.DataFrame,
|
|
547
|
+
response: str,
|
|
548
|
+
predictors: Sequence[str],
|
|
549
|
+
*,
|
|
550
|
+
prior_scale: float = 2.5,
|
|
551
|
+
hdi_prob: float = 0.95,
|
|
552
|
+
draws: int = 500,
|
|
553
|
+
tune: int = 500,
|
|
554
|
+
chains: int = 2,
|
|
555
|
+
target_accept: float = 0.9,
|
|
556
|
+
seed: int = 42,
|
|
557
|
+
event_level: str | None = None,
|
|
558
|
+
) -> AnalysisResult:
|
|
559
|
+
from scipy.special import expit
|
|
560
|
+
from sklearn.metrics import accuracy_score, log_loss, roc_auc_score
|
|
561
|
+
|
|
562
|
+
pm, az = _backend()
|
|
563
|
+
prior_scale = _check_positive(prior_scale, "Prior scale")
|
|
564
|
+
hdi_prob = _check_hdi(hdi_prob)
|
|
565
|
+
_check_sampling(draws, tune, chains, target_accept)
|
|
566
|
+
|
|
567
|
+
predictors = [predictor for predictor in dict.fromkeys(predictors) if predictor != response]
|
|
568
|
+
if not predictors:
|
|
569
|
+
raise ValueError("Select at least one predictor.")
|
|
570
|
+
frame, _, levels = _clean_binary(df, response, predictors, event_level)
|
|
571
|
+
frame = _clean_numeric(frame, [response, *predictors])
|
|
572
|
+
constant = [column for column in predictors if frame[column].std(ddof=0) == 0]
|
|
573
|
+
if constant:
|
|
574
|
+
raise ValueError(f"Predictors must vary: {', '.join(constant)}")
|
|
575
|
+
y = frame[response].to_numpy(dtype=int)
|
|
576
|
+
x = frame[predictors].to_numpy(dtype=float)
|
|
577
|
+
x_mean = x.mean(axis=0)
|
|
578
|
+
x_sd = x.std(axis=0, ddof=0)
|
|
579
|
+
x_sd[x_sd == 0] = 1.0
|
|
580
|
+
xs = (x - x_mean) / x_sd
|
|
581
|
+
|
|
582
|
+
with pm.Model() as model:
|
|
583
|
+
alpha = pm.Normal("alpha", mu=0.0, sigma=2.5)
|
|
584
|
+
beta = pm.Normal("beta", mu=0.0, sigma=prior_scale, shape=len(predictors))
|
|
585
|
+
mu = pm.Deterministic("mu", alpha + pm.math.dot(xs, beta))
|
|
586
|
+
pm.Bernoulli("y", logit_p=mu, observed=y)
|
|
587
|
+
|
|
588
|
+
idata = _sample(pm, model, draws, tune, chains, target_accept, seed)
|
|
589
|
+
summary = _summary(az, idata, ["alpha", "beta"], hdi_prob)
|
|
590
|
+
|
|
591
|
+
alpha_std = _flat(idata, "alpha")
|
|
592
|
+
beta_std = _flat(idata, "beta")
|
|
593
|
+
beta_raw = beta_std / x_sd
|
|
594
|
+
alpha_raw = alpha_std - np.sum(beta_std * x_mean / x_sd, axis=1)
|
|
595
|
+
|
|
596
|
+
rows = [_coefficient_row("Intercept", alpha_raw, summary, "alpha", hdi_prob, exponential=True)]
|
|
597
|
+
rows.extend(
|
|
598
|
+
_coefficient_row(predictor, beta_raw[:, index], summary, f"beta[{index}]", hdi_prob, exponential=True)
|
|
599
|
+
for index, predictor in enumerate(predictors)
|
|
600
|
+
)
|
|
601
|
+
coefficient_frame = pd.DataFrame(rows)
|
|
602
|
+
low_label, high_label = _interval_labels(hdi_prob)
|
|
603
|
+
coefficient_frame = coefficient_frame.rename(columns={"HDI Low": low_label, "HDI High": high_label})
|
|
604
|
+
|
|
605
|
+
logits = alpha_raw[:, None] + beta_raw @ x.T
|
|
606
|
+
probabilities = expit(logits)
|
|
607
|
+
mean_probability = probabilities.mean(axis=0)
|
|
608
|
+
predicted = (mean_probability >= 0.5).astype(int)
|
|
609
|
+
metrics: list[tuple[str, Any]] = [
|
|
610
|
+
("Accuracy", float(accuracy_score(y, predicted))),
|
|
611
|
+
("Log loss", float(log_loss(y, np.clip(mean_probability, 1e-9, 1 - 1e-9)))),
|
|
612
|
+
]
|
|
613
|
+
try:
|
|
614
|
+
metrics.append(("ROC AUC", float(roc_auc_score(y, mean_probability))))
|
|
615
|
+
except Exception:
|
|
616
|
+
pass
|
|
617
|
+
fit_frame = _fit_table(az, idata, len(frame), len(predictors), draws, chains, hdi_prob, tuple(metrics))
|
|
618
|
+
diagnostics = _diagnostics_table(idata, summary, ["alpha", "beta"])
|
|
619
|
+
specification = _specification_table(
|
|
620
|
+
"Bernoulli(logit(alpha + X_std beta)); X standardized",
|
|
621
|
+
(
|
|
622
|
+
"alpha ~ Normal(0, 2.5)",
|
|
623
|
+
f"beta ~ Normal(0, {prior_scale:g})",
|
|
624
|
+
f"Event level: {levels[1]}",
|
|
625
|
+
"Coefficient priors apply on the standardized predictor scale",
|
|
626
|
+
),
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
rng = np.random.default_rng(seed)
|
|
630
|
+
sample_index = rng.choice(len(alpha_raw), size=min(200, len(alpha_raw)), replace=False)
|
|
631
|
+
y_rep = rng.binomial(1, probabilities[sample_index])
|
|
632
|
+
lower, upper = _interval(y_rep, hdi_prob)
|
|
633
|
+
ppc = _ppc_frame(y, np.mean(probabilities[sample_index], axis=0), lower, upper)
|
|
634
|
+
trace = _posterior_long(
|
|
635
|
+
idata,
|
|
636
|
+
[("Intercept", alpha_raw), *[(predictor, beta_raw[:, index]) for index, predictor in enumerate(predictors)]],
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
result = AnalysisResult(
|
|
640
|
+
title=f"Bayesian Logistic Regression: {response}",
|
|
641
|
+
analysis_type="bayesian_logistic_regression",
|
|
642
|
+
params={
|
|
643
|
+
"response": response,
|
|
644
|
+
"predictors": predictors,
|
|
645
|
+
"prior_scale": prior_scale,
|
|
646
|
+
"hdi_prob": hdi_prob,
|
|
647
|
+
"draws": draws,
|
|
648
|
+
"tune": tune,
|
|
649
|
+
"chains": chains,
|
|
650
|
+
"target_accept": target_accept,
|
|
651
|
+
"seed": seed,
|
|
652
|
+
"levels": levels,
|
|
653
|
+
"event_level": levels[1],
|
|
654
|
+
},
|
|
655
|
+
)
|
|
656
|
+
result.add_table("Posterior Coefficients", coefficient_frame)
|
|
657
|
+
result.add_table("Model Fit", fit_frame)
|
|
658
|
+
result.add_table("MCMC Diagnostics", diagnostics)
|
|
659
|
+
result.add_table("Model Specification", specification)
|
|
660
|
+
result.add_plot("bayes_trace", {"parameters": ["Intercept", *predictors]}, title="Posterior Trace", data=trace)
|
|
661
|
+
forest = pd.DataFrame(
|
|
662
|
+
[
|
|
663
|
+
{
|
|
664
|
+
"Term": row["Term"],
|
|
665
|
+
"Mean": row["Odds Ratio"],
|
|
666
|
+
"HDI Low": row["OR HDI Low"],
|
|
667
|
+
"HDI High": row["OR HDI High"],
|
|
668
|
+
}
|
|
669
|
+
for row in rows
|
|
670
|
+
]
|
|
671
|
+
)
|
|
672
|
+
result.add_plot("bayes_forest", {"reference": 1.0}, title="Odds-Ratio Intervals", data=forest)
|
|
673
|
+
result.add_plot("bayes_posterior", {"parameters": ["Intercept", *predictors]}, title="Posterior Densities", data=trace)
|
|
674
|
+
result.add_plot("bayes_ppc", {}, title="Posterior Predictive Check", data=ppc)
|
|
675
|
+
result.add_model("idata", idata)
|
|
676
|
+
result.summary = (
|
|
677
|
+
f"Bayesian logistic regression for {response}; event level {levels[1]} versus {levels[0]}, "
|
|
678
|
+
f"{chains} chains and {draws} draws per chain."
|
|
679
|
+
)
|
|
680
|
+
result.notes = (
|
|
681
|
+
"Coefficient means and odds ratios are on the log-odds / odds scale, with predictors standardized. "
|
|
682
|
+
"Posterior intervals are highest-density intervals."
|
|
683
|
+
)
|
|
684
|
+
return result
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def bayesian_two_sample(
|
|
688
|
+
df: pd.DataFrame,
|
|
689
|
+
response: str,
|
|
690
|
+
group: str,
|
|
691
|
+
*,
|
|
692
|
+
prior_scale: float = 1.0,
|
|
693
|
+
sigma_prior: float = 1.0,
|
|
694
|
+
hdi_prob: float = 0.95,
|
|
695
|
+
draws: int = 500,
|
|
696
|
+
tune: int = 500,
|
|
697
|
+
chains: int = 2,
|
|
698
|
+
target_accept: float = 0.9,
|
|
699
|
+
seed: int = 42,
|
|
700
|
+
improvement_pct: float | None = None,
|
|
701
|
+
improvement_direction: str = "group2",
|
|
702
|
+
) -> AnalysisResult:
|
|
703
|
+
pm, az = _backend()
|
|
704
|
+
prior_scale = _check_positive(prior_scale, "Difference prior scale")
|
|
705
|
+
sigma_prior = _check_positive(sigma_prior, "Sigma prior")
|
|
706
|
+
hdi_prob = _check_hdi(hdi_prob)
|
|
707
|
+
improvement_pct = _check_improvement_pct(improvement_pct)
|
|
708
|
+
improvement_direction = _check_improvement_direction(improvement_direction)
|
|
709
|
+
_check_sampling(draws, tune, chains, target_accept)
|
|
710
|
+
frame, group_index, levels = _clean_group(df, response, group, minimum=2)
|
|
711
|
+
if len(levels) != 2:
|
|
712
|
+
raise ValueError("The Bayesian two-sample comparison requires exactly two groups.")
|
|
713
|
+
y = frame[response].to_numpy(dtype=float)
|
|
714
|
+
scale = float(y.std(ddof=0)) or 1.0
|
|
715
|
+
center = float(y.mean())
|
|
716
|
+
|
|
717
|
+
with pm.Model() as model:
|
|
718
|
+
mean = pm.Normal("center", mu=center, sigma=2.5 * scale)
|
|
719
|
+
difference = pm.Normal("difference", mu=0.0, sigma=prior_scale * scale)
|
|
720
|
+
sigma = pm.HalfNormal("sigma", sigma=sigma_prior * scale)
|
|
721
|
+
group_mu = pm.Deterministic("group_mu", mean + difference * np.asarray([0.0, 1.0]))
|
|
722
|
+
pm.Normal("y", mu=group_mu[group_index], sigma=sigma, observed=y)
|
|
723
|
+
|
|
724
|
+
idata = _sample(pm, model, draws, tune, chains, target_accept, seed)
|
|
725
|
+
summary = _summary(az, idata, ["center", "difference", "sigma", "group_mu"], hdi_prob)
|
|
726
|
+
group_mu = _flat(idata, "group_mu")
|
|
727
|
+
difference = _flat(idata, "difference")
|
|
728
|
+
sigma = _flat(idata, "sigma")
|
|
729
|
+
effect = difference / sigma
|
|
730
|
+
low_label, high_label = _interval_labels(hdi_prob)
|
|
731
|
+
|
|
732
|
+
group_rows = []
|
|
733
|
+
for index, level in enumerate(levels):
|
|
734
|
+
low, high = _hdi(group_mu[:, index], hdi_prob)
|
|
735
|
+
group_rows.append(
|
|
736
|
+
{
|
|
737
|
+
"Group": level,
|
|
738
|
+
"Mean": float(np.mean(group_mu[:, index])),
|
|
739
|
+
"SD": float(np.std(group_mu[:, index], ddof=1)),
|
|
740
|
+
low_label: low,
|
|
741
|
+
high_label: high,
|
|
742
|
+
"R-hat": _summary_stat(summary, f"group_mu[{index}]", "r_hat"),
|
|
743
|
+
"ESS Bulk": _summary_stat(summary, f"group_mu[{index}]", "ess_bulk"),
|
|
744
|
+
}
|
|
745
|
+
)
|
|
746
|
+
diff_low, diff_high = _hdi(difference, hdi_prob)
|
|
747
|
+
effect_low, effect_high = _hdi(effect, hdi_prob)
|
|
748
|
+
difference_row = {
|
|
749
|
+
"Difference": f"{levels[1]} - {levels[0]}",
|
|
750
|
+
"Mean": float(np.mean(difference)),
|
|
751
|
+
"SD": float(np.std(difference, ddof=1)),
|
|
752
|
+
low_label: diff_low,
|
|
753
|
+
high_label: diff_high,
|
|
754
|
+
"P(Difference > 0)": float(np.mean(difference > 0)),
|
|
755
|
+
"Effect Size": float(np.mean(effect)),
|
|
756
|
+
"Effect HDI Low": effect_low,
|
|
757
|
+
"Effect HDI High": effect_high,
|
|
758
|
+
"R-hat": _summary_stat(summary, "difference", "r_hat"),
|
|
759
|
+
"ESS Bulk": _summary_stat(summary, "difference", "ess_bulk"),
|
|
760
|
+
}
|
|
761
|
+
fit_frame = _fit_table(
|
|
762
|
+
az,
|
|
763
|
+
idata,
|
|
764
|
+
len(frame),
|
|
765
|
+
len(levels),
|
|
766
|
+
draws,
|
|
767
|
+
chains,
|
|
768
|
+
hdi_prob,
|
|
769
|
+
(
|
|
770
|
+
("Posterior mean sigma", float(np.mean(sigma))),
|
|
771
|
+
("Scale", scale),
|
|
772
|
+
),
|
|
773
|
+
term_label="Groups",
|
|
774
|
+
)
|
|
775
|
+
diagnostics = _diagnostics_table(idata, summary, ["center", "difference", "sigma", "group_mu"])
|
|
776
|
+
specification = _specification_table(
|
|
777
|
+
"Normal(group mean, sigma)",
|
|
778
|
+
(
|
|
779
|
+
f"center ~ Normal({center:.6g}, {2.5 * scale:.6g})",
|
|
780
|
+
f"difference ~ Normal(0, {prior_scale * scale:.6g})",
|
|
781
|
+
f"sigma ~ HalfNormal({sigma_prior * scale:.6g})",
|
|
782
|
+
),
|
|
783
|
+
)
|
|
784
|
+
|
|
785
|
+
rng = np.random.default_rng(seed)
|
|
786
|
+
sample_index = rng.choice(len(difference), size=min(200, len(difference)), replace=False)
|
|
787
|
+
y_hat = group_mu[sample_index][:, group_index]
|
|
788
|
+
y_rep = rng.normal(y_hat, sigma[sample_index, None])
|
|
789
|
+
lower, upper = _interval(y_rep, hdi_prob)
|
|
790
|
+
ppc = _ppc_frame(y, np.mean(y_hat, axis=0), lower, upper)
|
|
791
|
+
trace = _posterior_long(
|
|
792
|
+
idata,
|
|
793
|
+
[*[(level, group_mu[:, index]) for index, level in enumerate(levels)], ("Difference", difference), ("Sigma", sigma)],
|
|
794
|
+
)
|
|
795
|
+
forest_rows = [
|
|
796
|
+
{"Term": level, "Mean": float(np.mean(group_mu[:, index])), "HDI Low": _hdi(group_mu[:, index], hdi_prob)[0], "HDI High": _hdi(group_mu[:, index], hdi_prob)[1]}
|
|
797
|
+
for index, level in enumerate(levels)
|
|
798
|
+
]
|
|
799
|
+
forest_rows.append({"Term": "Difference", "Mean": difference_row["Mean"], "HDI Low": diff_low, "HDI High": diff_high})
|
|
800
|
+
|
|
801
|
+
improvement_frame = None
|
|
802
|
+
improvement_probability = None
|
|
803
|
+
comparison_label = ""
|
|
804
|
+
baseline_label = ""
|
|
805
|
+
if improvement_pct is not None:
|
|
806
|
+
if improvement_direction == "group1":
|
|
807
|
+
improvement = -difference
|
|
808
|
+
baseline = group_mu[:, 1]
|
|
809
|
+
comparison_label = f"{levels[0]} over {levels[1]}"
|
|
810
|
+
baseline_label = levels[1]
|
|
811
|
+
else:
|
|
812
|
+
improvement = difference
|
|
813
|
+
baseline = group_mu[:, 0]
|
|
814
|
+
comparison_label = f"{levels[1]} over {levels[0]}"
|
|
815
|
+
baseline_label = levels[0]
|
|
816
|
+
threshold = baseline * improvement_pct / 100.0
|
|
817
|
+
improvement_probability = float(np.mean(improvement > threshold))
|
|
818
|
+
relative = np.divide(
|
|
819
|
+
improvement,
|
|
820
|
+
baseline,
|
|
821
|
+
out=np.full_like(improvement, np.nan),
|
|
822
|
+
where=np.abs(baseline) > 1e-12,
|
|
823
|
+
)
|
|
824
|
+
relative_mean = float(np.nanmean(relative)) if np.isfinite(relative).any() else math.nan
|
|
825
|
+
relative_low, relative_high = _hdi(relative, hdi_prob)
|
|
826
|
+
baseline_low, baseline_high = _hdi(baseline, hdi_prob)
|
|
827
|
+
warning = ""
|
|
828
|
+
if not np.isfinite(relative_mean):
|
|
829
|
+
warning = "Baseline is zero or too close to zero for a relative comparison."
|
|
830
|
+
elif baseline_low <= 0 <= baseline_high:
|
|
831
|
+
warning = "Baseline interval includes zero; relative improvement is unstable."
|
|
832
|
+
improvement_frame = pd.DataFrame(
|
|
833
|
+
[
|
|
834
|
+
{
|
|
835
|
+
"Comparison": comparison_label,
|
|
836
|
+
"Baseline Group": baseline_label,
|
|
837
|
+
"Baseline Mean": float(np.mean(baseline)),
|
|
838
|
+
f"{low_label} Baseline": baseline_low,
|
|
839
|
+
f"{high_label} Baseline": baseline_high,
|
|
840
|
+
"Threshold (%)": improvement_pct,
|
|
841
|
+
"Threshold (Response Units)": float(np.mean(threshold)),
|
|
842
|
+
"P(Improvement > Threshold)": improvement_probability,
|
|
843
|
+
"Mean Improvement": float(np.mean(improvement)),
|
|
844
|
+
"Mean Improvement (%)": 100.0 * relative_mean,
|
|
845
|
+
f"{low_label} Improvement (%)": 100.0 * relative_low,
|
|
846
|
+
f"{high_label} Improvement (%)": 100.0 * relative_high,
|
|
847
|
+
"Warning": warning,
|
|
848
|
+
}
|
|
849
|
+
]
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
result = AnalysisResult(
|
|
853
|
+
title=f"Bayesian Two-Sample Comparison: {response} by {group}",
|
|
854
|
+
analysis_type="bayesian_two_sample",
|
|
855
|
+
params={
|
|
856
|
+
"response": response,
|
|
857
|
+
"group": group,
|
|
858
|
+
"prior_scale": prior_scale,
|
|
859
|
+
"sigma_prior": sigma_prior,
|
|
860
|
+
"hdi_prob": hdi_prob,
|
|
861
|
+
"draws": draws,
|
|
862
|
+
"tune": tune,
|
|
863
|
+
"chains": chains,
|
|
864
|
+
"target_accept": target_accept,
|
|
865
|
+
"seed": seed,
|
|
866
|
+
"levels": levels,
|
|
867
|
+
"improvement_pct": improvement_pct,
|
|
868
|
+
"improvement_direction": improvement_direction,
|
|
869
|
+
},
|
|
870
|
+
)
|
|
871
|
+
result.add_table("Group Means", pd.DataFrame(group_rows))
|
|
872
|
+
result.add_table("Difference", pd.DataFrame([difference_row]))
|
|
873
|
+
if improvement_frame is not None:
|
|
874
|
+
result.add_table("Probability of Improvement", improvement_frame)
|
|
875
|
+
result.add_table("Model Fit", fit_frame)
|
|
876
|
+
result.add_table("MCMC Diagnostics", diagnostics)
|
|
877
|
+
result.add_table("Model Specification", specification)
|
|
878
|
+
result.add_plot("bayes_trace", {"parameters": [*levels, "Difference", "Sigma"]}, title="Posterior Trace", data=trace)
|
|
879
|
+
result.add_plot("bayes_forest", {}, title="Group and Difference Intervals", data=_forest_frame(forest_rows))
|
|
880
|
+
result.add_plot("bayes_posterior", {"parameters": [*levels, "Difference", "Sigma"]}, title="Posterior Densities", data=trace)
|
|
881
|
+
result.add_plot("bayes_ppc", {}, title="Posterior Predictive Check", data=ppc)
|
|
882
|
+
result.add_model("idata", idata)
|
|
883
|
+
summary = (
|
|
884
|
+
f"Bayesian comparison of {levels[1]} versus {levels[0]} for {response}; "
|
|
885
|
+
f"posterior P(difference > 0) = {difference_row['P(Difference > 0)']:.3f}."
|
|
886
|
+
)
|
|
887
|
+
if improvement_probability is not None:
|
|
888
|
+
summary += (
|
|
889
|
+
f" Posterior P({comparison_label} > {improvement_pct:g}% of the {baseline_label} mean)"
|
|
890
|
+
f" = {improvement_probability:.3f}."
|
|
891
|
+
)
|
|
892
|
+
result.summary = summary
|
|
893
|
+
notes = (
|
|
894
|
+
"Group levels are sorted alphabetically; the difference is group 2 minus group 1. "
|
|
895
|
+
"Intervals are highest-density intervals."
|
|
896
|
+
)
|
|
897
|
+
if improvement_probability is not None:
|
|
898
|
+
notes += (
|
|
899
|
+
" Improvement is relative to the baseline group's posterior mean;"
|
|
900
|
+
" each posterior draw is compared with its own baseline."
|
|
901
|
+
)
|
|
902
|
+
result.notes = notes
|
|
903
|
+
return result
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
def bayesian_oneway_anova(
|
|
907
|
+
df: pd.DataFrame,
|
|
908
|
+
response: str,
|
|
909
|
+
factor: str,
|
|
910
|
+
*,
|
|
911
|
+
prior_scale: float = 1.0,
|
|
912
|
+
sigma_prior: float = 1.0,
|
|
913
|
+
hdi_prob: float = 0.95,
|
|
914
|
+
draws: int = 500,
|
|
915
|
+
tune: int = 500,
|
|
916
|
+
chains: int = 2,
|
|
917
|
+
target_accept: float = 0.9,
|
|
918
|
+
seed: int = 42,
|
|
919
|
+
) -> AnalysisResult:
|
|
920
|
+
pm, az = _backend()
|
|
921
|
+
prior_scale = _check_positive(prior_scale, "Group prior scale")
|
|
922
|
+
sigma_prior = _check_positive(sigma_prior, "Sigma prior")
|
|
923
|
+
hdi_prob = _check_hdi(hdi_prob)
|
|
924
|
+
_check_sampling(draws, tune, chains, target_accept)
|
|
925
|
+
frame, group_index, levels = _clean_group(df, response, factor, minimum=2)
|
|
926
|
+
y = frame[response].to_numpy(dtype=float)
|
|
927
|
+
scale = float(y.std(ddof=0)) or 1.0
|
|
928
|
+
center = float(y.mean())
|
|
929
|
+
|
|
930
|
+
with pm.Model() as model:
|
|
931
|
+
global_mean = pm.Normal("global_mean", mu=center, sigma=2.5 * scale)
|
|
932
|
+
between_sd = pm.HalfNormal("group_sd", sigma=prior_scale * scale)
|
|
933
|
+
raw_effects = pm.Normal("raw_effects", mu=0.0, sigma=between_sd, shape=len(levels))
|
|
934
|
+
group_effects = pm.Deterministic("group_effects", raw_effects - pm.math.mean(raw_effects))
|
|
935
|
+
sigma = pm.HalfNormal("sigma", sigma=sigma_prior * scale)
|
|
936
|
+
group_mu = pm.Deterministic("group_mu", global_mean + group_effects)
|
|
937
|
+
pm.Normal("y", mu=group_mu[group_index], sigma=sigma, observed=y)
|
|
938
|
+
|
|
939
|
+
idata = _sample(pm, model, draws, tune, chains, target_accept, seed)
|
|
940
|
+
summary = _summary(az, idata, ["global_mean", "group_effects", "group_sd", "sigma", "group_mu"], hdi_prob)
|
|
941
|
+
group_mu = _flat(idata, "group_mu")
|
|
942
|
+
effects = _flat(idata, "group_effects")
|
|
943
|
+
group_sd = _flat(idata, "group_sd")
|
|
944
|
+
sigma = _flat(idata, "sigma")
|
|
945
|
+
icc = group_sd**2 / np.maximum(group_sd**2 + sigma**2, 1e-12)
|
|
946
|
+
low_label, high_label = _interval_labels(hdi_prob)
|
|
947
|
+
|
|
948
|
+
group_rows = []
|
|
949
|
+
for index, level in enumerate(levels):
|
|
950
|
+
low, high = _hdi(group_mu[:, index], hdi_prob)
|
|
951
|
+
group_rows.append(
|
|
952
|
+
{
|
|
953
|
+
"Group": level,
|
|
954
|
+
"Mean": float(np.mean(group_mu[:, index])),
|
|
955
|
+
"SD": float(np.std(group_mu[:, index], ddof=1)),
|
|
956
|
+
low_label: low,
|
|
957
|
+
high_label: high,
|
|
958
|
+
"R-hat": _summary_stat(summary, f"group_mu[{index}]", "r_hat"),
|
|
959
|
+
"ESS Bulk": _summary_stat(summary, f"group_mu[{index}]", "ess_bulk"),
|
|
960
|
+
}
|
|
961
|
+
)
|
|
962
|
+
|
|
963
|
+
pairwise_rows = []
|
|
964
|
+
for first in range(len(levels)):
|
|
965
|
+
for second in range(first + 1, len(levels)):
|
|
966
|
+
difference = group_mu[:, second] - group_mu[:, first]
|
|
967
|
+
low, high = _hdi(difference, hdi_prob)
|
|
968
|
+
pairwise_rows.append(
|
|
969
|
+
{
|
|
970
|
+
"Comparison": f"{levels[second]} - {levels[first]}",
|
|
971
|
+
"Mean": float(np.mean(difference)),
|
|
972
|
+
"SD": float(np.std(difference, ddof=1)),
|
|
973
|
+
low_label: low,
|
|
974
|
+
high_label: high,
|
|
975
|
+
"P(Difference > 0)": float(np.mean(difference > 0)),
|
|
976
|
+
}
|
|
977
|
+
)
|
|
978
|
+
|
|
979
|
+
group_sd_low, group_sd_high = _hdi(group_sd, hdi_prob)
|
|
980
|
+
icc_low, icc_high = _hdi(icc, hdi_prob)
|
|
981
|
+
variance_frame = pd.DataFrame(
|
|
982
|
+
[
|
|
983
|
+
{
|
|
984
|
+
"Component": "Between-group SD",
|
|
985
|
+
"Mean": float(np.mean(group_sd)),
|
|
986
|
+
"SD": float(np.std(group_sd, ddof=1)),
|
|
987
|
+
low_label: group_sd_low,
|
|
988
|
+
high_label: group_sd_high,
|
|
989
|
+
},
|
|
990
|
+
{
|
|
991
|
+
"Component": "Within-group sigma",
|
|
992
|
+
"Mean": float(np.mean(sigma)),
|
|
993
|
+
"SD": float(np.std(sigma, ddof=1)),
|
|
994
|
+
low_label: _hdi(sigma, hdi_prob)[0],
|
|
995
|
+
high_label: _hdi(sigma, hdi_prob)[1],
|
|
996
|
+
},
|
|
997
|
+
{
|
|
998
|
+
"Component": "Intraclass correlation",
|
|
999
|
+
"Mean": float(np.mean(icc)),
|
|
1000
|
+
"SD": float(np.std(icc, ddof=1)),
|
|
1001
|
+
low_label: icc_low,
|
|
1002
|
+
high_label: icc_high,
|
|
1003
|
+
},
|
|
1004
|
+
]
|
|
1005
|
+
)
|
|
1006
|
+
fit_frame = _fit_table(
|
|
1007
|
+
az,
|
|
1008
|
+
idata,
|
|
1009
|
+
len(frame),
|
|
1010
|
+
len(levels),
|
|
1011
|
+
draws,
|
|
1012
|
+
chains,
|
|
1013
|
+
hdi_prob,
|
|
1014
|
+
(
|
|
1015
|
+
("Posterior mean between-group SD", float(np.mean(group_sd))),
|
|
1016
|
+
("Posterior mean ICC", float(np.mean(icc))),
|
|
1017
|
+
),
|
|
1018
|
+
term_label="Groups",
|
|
1019
|
+
)
|
|
1020
|
+
diagnostics = _diagnostics_table(
|
|
1021
|
+
idata,
|
|
1022
|
+
summary,
|
|
1023
|
+
["global_mean", "group_effects", "group_sd", "sigma", "group_mu"],
|
|
1024
|
+
)
|
|
1025
|
+
specification = _specification_table(
|
|
1026
|
+
"Normal(global mean + group effect, sigma)",
|
|
1027
|
+
(
|
|
1028
|
+
f"global mean ~ Normal({center:.6g}, {2.5 * scale:.6g})",
|
|
1029
|
+
f"group SD ~ HalfNormal({prior_scale * scale:.6g})",
|
|
1030
|
+
"group effect ~ Normal(0, group SD), centered to zero mean",
|
|
1031
|
+
f"sigma ~ HalfNormal({sigma_prior * scale:.6g})",
|
|
1032
|
+
),
|
|
1033
|
+
)
|
|
1034
|
+
|
|
1035
|
+
rng = np.random.default_rng(seed)
|
|
1036
|
+
sample_index = rng.choice(len(sigma), size=min(200, len(sigma)), replace=False)
|
|
1037
|
+
y_hat = group_mu[sample_index][:, group_index]
|
|
1038
|
+
y_rep = rng.normal(y_hat, sigma[sample_index, None])
|
|
1039
|
+
lower, upper = _interval(y_rep, hdi_prob)
|
|
1040
|
+
ppc = _ppc_frame(y, np.mean(y_hat, axis=0), lower, upper)
|
|
1041
|
+
trace = _posterior_long(
|
|
1042
|
+
idata,
|
|
1043
|
+
[
|
|
1044
|
+
("Global mean", _flat(idata, "global_mean")),
|
|
1045
|
+
*[(level, group_mu[:, index]) for index, level in enumerate(levels)],
|
|
1046
|
+
*[(f"{level} effect", effects[:, index]) for index, level in enumerate(levels)],
|
|
1047
|
+
("Between-group SD", group_sd),
|
|
1048
|
+
("Sigma", sigma),
|
|
1049
|
+
],
|
|
1050
|
+
)
|
|
1051
|
+
forest_rows = [
|
|
1052
|
+
{"Term": level, "Mean": float(np.mean(group_mu[:, index])), "HDI Low": _hdi(group_mu[:, index], hdi_prob)[0], "HDI High": _hdi(group_mu[:, index], hdi_prob)[1]}
|
|
1053
|
+
for index, level in enumerate(levels)
|
|
1054
|
+
]
|
|
1055
|
+
|
|
1056
|
+
result = AnalysisResult(
|
|
1057
|
+
title=f"Bayesian One-Way ANOVA: {response} by {factor}",
|
|
1058
|
+
analysis_type="bayesian_anova",
|
|
1059
|
+
params={
|
|
1060
|
+
"response": response,
|
|
1061
|
+
"factor": factor,
|
|
1062
|
+
"prior_scale": prior_scale,
|
|
1063
|
+
"sigma_prior": sigma_prior,
|
|
1064
|
+
"hdi_prob": hdi_prob,
|
|
1065
|
+
"draws": draws,
|
|
1066
|
+
"tune": tune,
|
|
1067
|
+
"chains": chains,
|
|
1068
|
+
"target_accept": target_accept,
|
|
1069
|
+
"seed": seed,
|
|
1070
|
+
"levels": levels,
|
|
1071
|
+
},
|
|
1072
|
+
)
|
|
1073
|
+
result.add_table("Group Means", pd.DataFrame(group_rows))
|
|
1074
|
+
result.add_table("Pairwise Differences", pd.DataFrame(pairwise_rows))
|
|
1075
|
+
result.add_table("Variance Components", variance_frame)
|
|
1076
|
+
result.add_table("Model Fit", fit_frame)
|
|
1077
|
+
result.add_table("MCMC Diagnostics", diagnostics)
|
|
1078
|
+
result.add_table("Model Specification", specification)
|
|
1079
|
+
parameters = ["Global mean", *levels, *[f"{level} effect" for level in levels], "Between-group SD", "Sigma"]
|
|
1080
|
+
result.add_plot("bayes_trace", {"parameters": parameters}, title="Posterior Trace", data=trace)
|
|
1081
|
+
result.add_plot("bayes_forest", {}, title="Group Intervals", data=_forest_frame(forest_rows))
|
|
1082
|
+
result.add_plot("bayes_posterior", {"parameters": parameters}, title="Posterior Densities", data=trace)
|
|
1083
|
+
result.add_plot("bayes_ppc", {}, title="Posterior Predictive Check", data=ppc)
|
|
1084
|
+
result.add_model("idata", idata)
|
|
1085
|
+
result.summary = (
|
|
1086
|
+
f"Bayesian one-way ANOVA for {response} across {len(levels)} levels of {factor}; "
|
|
1087
|
+
f"posterior mean between-group SD = {float(np.mean(group_sd)):.3f}, "
|
|
1088
|
+
f"ICC = {float(np.mean(icc)):.3f}."
|
|
1089
|
+
)
|
|
1090
|
+
result.notes = (
|
|
1091
|
+
"Group effects are deviations from the overall mean. Intervals are highest-density intervals. "
|
|
1092
|
+
"Group levels are sorted alphabetically; pairwise probabilities are unadjusted for multiple comparisons."
|
|
1093
|
+
)
|
|
1094
|
+
return result
|