rstatspython 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.
- rstats/__init__.py +11 -0
- rstats/_data.py +164 -0
- rstats/_posthoc.py +278 -0
- rstats/anova.py +422 -0
- rstats/categorical.py +180 -0
- rstats/descriptive.py +100 -0
- rstats/regression.py +302 -0
- rstats/result.py +68 -0
- rstats/visualization.py +180 -0
- rstatspython-0.1.0.dist-info/METADATA +177 -0
- rstatspython-0.1.0.dist-info/RECORD +13 -0
- rstatspython-0.1.0.dist-info/WHEEL +4 -0
- rstatspython-0.1.0.dist-info/licenses/LICENSE +21 -0
rstats/descriptive.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Detailed descriptive statistics without model fitting."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from scipy import stats
|
|
6
|
+
|
|
7
|
+
from ._data import alpha_value, dataframe, names
|
|
8
|
+
from .result import AnalysisResult
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def descriptives(*, data, columns=None, by=None, alpha=0.05):
|
|
12
|
+
"""Summarize selected columns, optionally within groups.
|
|
13
|
+
|
|
14
|
+
Missingness is per variable. SD/variance use n-1, skewness is bias-corrected,
|
|
15
|
+
and kurtosis is bias-corrected excess kurtosis. Mean CIs use Student's t.
|
|
16
|
+
"""
|
|
17
|
+
alpha_value(alpha)
|
|
18
|
+
dataframe(data, []) # Validate the container before reading its columns.
|
|
19
|
+
groups = names(by)
|
|
20
|
+
columns = (
|
|
21
|
+
names(columns) if columns is not None else [c for c in data.columns if c not in groups]
|
|
22
|
+
)
|
|
23
|
+
if not columns:
|
|
24
|
+
raise ValueError("Select at least one column to summarize.")
|
|
25
|
+
if set(groups) & set(columns):
|
|
26
|
+
raise ValueError("Grouping columns must not also be summarized columns.")
|
|
27
|
+
frame = dataframe(data, [*groups, *columns])
|
|
28
|
+
numeric_rows, frequency_rows = [], []
|
|
29
|
+
chunks = (
|
|
30
|
+
frame.groupby(groups, observed=True, dropna=False, sort=False) if groups else [((), frame)]
|
|
31
|
+
)
|
|
32
|
+
for key, chunk in chunks:
|
|
33
|
+
key = key if isinstance(key, tuple) else (key,)
|
|
34
|
+
labels = dict(zip(groups, key))
|
|
35
|
+
for col in columns:
|
|
36
|
+
values = chunk[col].dropna()
|
|
37
|
+
n = len(values)
|
|
38
|
+
base = {**labels, "variable": col, "n": n, "missing": int(chunk[col].isna().sum())}
|
|
39
|
+
if pd.api.types.is_numeric_dtype(values) and not pd.api.types.is_bool_dtype(values):
|
|
40
|
+
if np.isinf(values.to_numpy(dtype=float)).any():
|
|
41
|
+
raise ValueError(f"{col!r} contains infinite values.")
|
|
42
|
+
x = values.to_numpy(dtype=float)
|
|
43
|
+
sd = np.std(x, ddof=1) if n > 1 else np.nan
|
|
44
|
+
mean = np.mean(x) if n else np.nan
|
|
45
|
+
margin = stats.t.ppf(1 - alpha / 2, n - 1) * sd / np.sqrt(n) if n > 1 else np.nan
|
|
46
|
+
q = np.quantile(x, [0.25, 0.5, 0.75]) if n else [np.nan] * 3
|
|
47
|
+
numeric_rows.append(
|
|
48
|
+
{
|
|
49
|
+
**base,
|
|
50
|
+
"mean": mean,
|
|
51
|
+
"median": q[1],
|
|
52
|
+
"modes": ", ".join(map(str, values.mode().tolist())),
|
|
53
|
+
"sd": sd,
|
|
54
|
+
"variance": sd**2,
|
|
55
|
+
"min": np.min(x) if n else np.nan,
|
|
56
|
+
"max": np.max(x) if n else np.nan,
|
|
57
|
+
"range": np.ptp(x) if n else np.nan,
|
|
58
|
+
"q1": q[0],
|
|
59
|
+
"q3": q[2],
|
|
60
|
+
"iqr": q[2] - q[0],
|
|
61
|
+
"mad": stats.median_abs_deviation(x) if n else np.nan,
|
|
62
|
+
"skewness": stats.skew(x, bias=False) if n > 2 and sd > 0 else np.nan,
|
|
63
|
+
"excess_kurtosis": stats.kurtosis(x, bias=False)
|
|
64
|
+
if n > 3 and sd > 0
|
|
65
|
+
else np.nan,
|
|
66
|
+
"mean_ci_low": mean - margin,
|
|
67
|
+
"mean_ci_high": mean + margin,
|
|
68
|
+
}
|
|
69
|
+
)
|
|
70
|
+
else:
|
|
71
|
+
counts = values.value_counts(sort=False, dropna=True)
|
|
72
|
+
for level, count in counts.items():
|
|
73
|
+
if count:
|
|
74
|
+
frequency_rows.append(
|
|
75
|
+
{
|
|
76
|
+
**base,
|
|
77
|
+
"level": level,
|
|
78
|
+
"count": int(count),
|
|
79
|
+
"percent": 100 * count / n,
|
|
80
|
+
}
|
|
81
|
+
)
|
|
82
|
+
if not n:
|
|
83
|
+
frequency_rows.append(
|
|
84
|
+
{**base, "level": "(no valid observations)", "count": 0, "percent": np.nan}
|
|
85
|
+
)
|
|
86
|
+
tables = {}
|
|
87
|
+
if numeric_rows:
|
|
88
|
+
tables["descriptives"] = pd.DataFrame(numeric_rows)
|
|
89
|
+
if frequency_rows:
|
|
90
|
+
tables["frequencies"] = pd.DataFrame(frequency_rows)
|
|
91
|
+
return AnalysisResult(
|
|
92
|
+
"Descriptive statistics",
|
|
93
|
+
tables,
|
|
94
|
+
[
|
|
95
|
+
"Available values are used per variable; missing grouping values form a separate group.",
|
|
96
|
+
f"Sample SD/variance use n−1. Mean CIs are {100 * (1 - alpha):g}% t intervals; MAD is unscaled and kurtosis is excess kurtosis.",
|
|
97
|
+
"Modes list all tied most-frequent values. Descriptives do not establish causal effects.",
|
|
98
|
+
],
|
|
99
|
+
{"alpha": alpha, "by": groups},
|
|
100
|
+
)
|
rstats/regression.py
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
"""Linear and binary logistic regression with complete reports."""
|
|
2
|
+
|
|
3
|
+
import warnings
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import statsmodels.formula.api as smf
|
|
8
|
+
from patsy import ModelDesc
|
|
9
|
+
from scipy import stats
|
|
10
|
+
from statsmodels.stats.diagnostic import het_breuschpagan
|
|
11
|
+
from statsmodels.stats.outliers_influence import variance_inflation_factor
|
|
12
|
+
from statsmodels.tools.sm_exceptions import PerfectSeparationError, PerfectSeparationWarning
|
|
13
|
+
|
|
14
|
+
from ._data import (
|
|
15
|
+
alpha_value,
|
|
16
|
+
clean_term,
|
|
17
|
+
complete,
|
|
18
|
+
factorize,
|
|
19
|
+
names,
|
|
20
|
+
numeric,
|
|
21
|
+
parse,
|
|
22
|
+
sample_table,
|
|
23
|
+
)
|
|
24
|
+
from .result import AnalysisResult
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def prepare_regression(formula, data, categorical, reference, missing):
|
|
28
|
+
spec = parse(formula)
|
|
29
|
+
if spec.outcome in spec.predictors:
|
|
30
|
+
raise ValueError("The outcome cannot also be a predictor.")
|
|
31
|
+
explicit = names(categorical) + spec.forced
|
|
32
|
+
if set(explicit) - set(spec.predictors):
|
|
33
|
+
raise ValueError("categorical must name predictors in the formula.")
|
|
34
|
+
frame, notes = complete(data, [spec.outcome, *spec.predictors], missing)
|
|
35
|
+
factors = list(
|
|
36
|
+
dict.fromkeys(
|
|
37
|
+
explicit
|
|
38
|
+
+ [
|
|
39
|
+
col
|
|
40
|
+
for col in spec.predictors
|
|
41
|
+
if not pd.api.types.is_numeric_dtype(frame[col])
|
|
42
|
+
or pd.api.types.is_bool_dtype(frame[col])
|
|
43
|
+
]
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
coding = factorize(frame, factors, reference)
|
|
47
|
+
return spec, frame, factors, coding, notes
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def validate_model(model):
|
|
51
|
+
x = model.model.exog
|
|
52
|
+
if np.linalg.matrix_rank(x) < x.shape[1]:
|
|
53
|
+
raise ValueError(
|
|
54
|
+
"The model is rank deficient: remove redundant predictors or empty interaction cells."
|
|
55
|
+
)
|
|
56
|
+
if model.df_resid <= 0:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"The model has no residual degrees of freedom; add observations or simplify it."
|
|
59
|
+
)
|
|
60
|
+
if (
|
|
61
|
+
not np.isfinite(np.asarray(model.params)).all()
|
|
62
|
+
or not np.isfinite(np.asarray(model.cov_params())).all()
|
|
63
|
+
):
|
|
64
|
+
raise ValueError(
|
|
65
|
+
"Model estimates or uncertainty are not finite; check for a degenerate model."
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def fit_ols(formula, frame):
|
|
70
|
+
unfitted = smf.ols(formula, data=frame)
|
|
71
|
+
if np.linalg.matrix_rank(unfitted.exog) < unfitted.exog.shape[1]:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
"The model is rank deficient: remove redundant predictors or empty interaction cells."
|
|
74
|
+
)
|
|
75
|
+
if len(unfitted.endog) <= unfitted.exog.shape[1]:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
"The model has no residual degrees of freedom; add observations or simplify it."
|
|
78
|
+
)
|
|
79
|
+
model = unfitted.fit()
|
|
80
|
+
validate_model(model)
|
|
81
|
+
if model.ssr <= np.finfo(float).eps * max(1, model.centered_tss):
|
|
82
|
+
raise ValueError(
|
|
83
|
+
"The model has effectively zero residual variance; ordinary inferential tests are undefined."
|
|
84
|
+
)
|
|
85
|
+
return model
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def coefficients(model, spec, alpha, logistic=False):
|
|
89
|
+
ci = model.conf_int(alpha=alpha)
|
|
90
|
+
result = pd.DataFrame(
|
|
91
|
+
{
|
|
92
|
+
"estimate": model.params,
|
|
93
|
+
"std_error": model.bse,
|
|
94
|
+
"z" if logistic else "t": model.tvalues,
|
|
95
|
+
"p": model.pvalues,
|
|
96
|
+
"ci_low": ci.iloc[:, 0],
|
|
97
|
+
"ci_high": ci.iloc[:, 1],
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
if logistic:
|
|
101
|
+
with np.errstate(over="ignore"):
|
|
102
|
+
result["odds_ratio"] = np.exp(model.params)
|
|
103
|
+
result["or_ci_low"] = np.exp(ci.iloc[:, 0])
|
|
104
|
+
result["or_ci_high"] = np.exp(ci.iloc[:, 1])
|
|
105
|
+
result.index = [clean_term(str(v), spec) for v in result.index]
|
|
106
|
+
result.index.name = "term"
|
|
107
|
+
return result
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def coding_table(coding):
|
|
111
|
+
return pd.DataFrame(
|
|
112
|
+
[
|
|
113
|
+
{
|
|
114
|
+
"predictor": col,
|
|
115
|
+
"reference": value["reference"],
|
|
116
|
+
"levels": ", ".join(map(str, value["levels"])),
|
|
117
|
+
}
|
|
118
|
+
for col, value in coding.items()
|
|
119
|
+
],
|
|
120
|
+
columns=["predictor", "reference", "levels"],
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def ols_diagnostics(model):
|
|
125
|
+
notes, rows = [], []
|
|
126
|
+
residuals = np.asarray(model.resid)
|
|
127
|
+
if len(residuals) >= 3 and np.std(residuals) > 0:
|
|
128
|
+
jb = stats.jarque_bera(residuals)
|
|
129
|
+
rows.append(
|
|
130
|
+
{
|
|
131
|
+
"diagnostic": "Residual normality (Jarque–Bera)",
|
|
132
|
+
"statistic": jb.statistic,
|
|
133
|
+
"p": jb.pvalue,
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
if "Intercept" in model.model.exog_names and model.model.exog.shape[1] > 1:
|
|
137
|
+
_, _, f, p = het_breuschpagan(residuals, model.model.exog)
|
|
138
|
+
rows.append({"diagnostic": "Constant variance (Breusch–Pagan F)", "statistic": f, "p": p})
|
|
139
|
+
if model.model.exog.shape[1] > 2:
|
|
140
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
141
|
+
vifs = [
|
|
142
|
+
variance_inflation_factor(model.model.exog, i)
|
|
143
|
+
for i, name in enumerate(model.model.exog_names)
|
|
144
|
+
if name != "Intercept"
|
|
145
|
+
]
|
|
146
|
+
if vifs and max(vifs) > 5:
|
|
147
|
+
notes.append("Some predictor VIFs exceed 5; inspect collinearity and factor coding.")
|
|
148
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
149
|
+
cooks = model.get_influence().cooks_distance[0]
|
|
150
|
+
count = int(np.sum(cooks > 4 / model.nobs))
|
|
151
|
+
notes.append(f"{count} observations have Cook's distance > 4/n; inspect influential cases.")
|
|
152
|
+
notes.append(
|
|
153
|
+
"Diagnostics do not change the fitted method. Independence follows from the study design."
|
|
154
|
+
)
|
|
155
|
+
return pd.DataFrame(rows, columns=["diagnostic", "statistic", "p"]), notes
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def lm(formula, *, data, categorical=None, reference=None, alpha=0.05, missing="drop"):
|
|
159
|
+
"""Fit simple/multiple OLS regression and display a complete teaching report.
|
|
160
|
+
|
|
161
|
+
Numeric-coded groups: ``lm('score ~ age + group', data=df,
|
|
162
|
+
categorical=['group'], reference={'group': 'control'})``.
|
|
163
|
+
"""
|
|
164
|
+
alpha_value(alpha)
|
|
165
|
+
spec, frame, factors, coding, notes = prepare_regression(
|
|
166
|
+
formula, data, categorical, reference, missing
|
|
167
|
+
)
|
|
168
|
+
numeric(frame[spec.outcome], spec.outcome)
|
|
169
|
+
if frame[spec.outcome].nunique() < 2:
|
|
170
|
+
raise ValueError("The outcome must vary to fit a regression.")
|
|
171
|
+
model = fit_ols(spec.backend(factors, reference), frame)
|
|
172
|
+
diag, extra = ols_diagnostics(model)
|
|
173
|
+
notes.extend(extra)
|
|
174
|
+
notes.append(
|
|
175
|
+
f"OLS with {100 * (1 - alpha):g}% confidence intervals. Coefficients are adjusted for the other predictors."
|
|
176
|
+
)
|
|
177
|
+
if "Intercept" not in model.model.exog_names:
|
|
178
|
+
notes.append(
|
|
179
|
+
"This model has no intercept; R² is uncentered and is not directly comparable to ordinary centered R²."
|
|
180
|
+
)
|
|
181
|
+
tables = {
|
|
182
|
+
"sample": sample_table(len(data), len(frame)),
|
|
183
|
+
"model": pd.DataFrame(
|
|
184
|
+
[
|
|
185
|
+
{
|
|
186
|
+
"n": int(model.nobs),
|
|
187
|
+
"F": model.fvalue,
|
|
188
|
+
"df_model": model.df_model,
|
|
189
|
+
"df_residual": model.df_resid,
|
|
190
|
+
"p": model.f_pvalue,
|
|
191
|
+
"r_squared": model.rsquared,
|
|
192
|
+
"adjusted_r_squared": model.rsquared_adj,
|
|
193
|
+
"residual_sd": np.sqrt(model.mse_resid),
|
|
194
|
+
}
|
|
195
|
+
]
|
|
196
|
+
),
|
|
197
|
+
"coefficients": coefficients(model, spec, alpha),
|
|
198
|
+
"descriptives": frame.select_dtypes(include="number").describe().T,
|
|
199
|
+
"diagnostics": diag,
|
|
200
|
+
}
|
|
201
|
+
if coding:
|
|
202
|
+
tables["coding"] = coding_table(coding)
|
|
203
|
+
return AnalysisResult(
|
|
204
|
+
"Linear regression (OLS)",
|
|
205
|
+
tables,
|
|
206
|
+
notes,
|
|
207
|
+
{"formula": formula, "method": "OLS", "alpha": alpha, "coding": coding},
|
|
208
|
+
model,
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def logmodel(
|
|
213
|
+
formula, *, data, categorical=None, reference=None, event=None, alpha=0.05, missing="drop"
|
|
214
|
+
):
|
|
215
|
+
"""Fit binary logistic regression, with odds ratios and an overall LR test.
|
|
216
|
+
|
|
217
|
+
Numeric 0/1 outcomes model 1 by default. For other binary outcomes, specify
|
|
218
|
+
``event='passed'``. Reference groups refer to predictors, not the outcome.
|
|
219
|
+
"""
|
|
220
|
+
alpha_value(alpha)
|
|
221
|
+
spec, frame, factors, coding, notes = prepare_regression(
|
|
222
|
+
formula, data, categorical, reference, missing
|
|
223
|
+
)
|
|
224
|
+
observed = frame[spec.outcome].unique().tolist()
|
|
225
|
+
if len(observed) != 2:
|
|
226
|
+
raise ValueError("logmodel needs exactly two observed outcome values.")
|
|
227
|
+
if event is None:
|
|
228
|
+
if not pd.api.types.is_numeric_dtype(frame[spec.outcome]) or set(observed) != {0, 1}:
|
|
229
|
+
raise ValueError("Specify event= for a binary outcome other than numeric 0/1.")
|
|
230
|
+
event = 1
|
|
231
|
+
if event not in observed:
|
|
232
|
+
raise ValueError(f"event={event!r} is not an observed outcome value.")
|
|
233
|
+
baseline = next(v for v in observed if v != event)
|
|
234
|
+
frame[spec.outcome] = (frame[spec.outcome] == event).astype(int)
|
|
235
|
+
if not any(
|
|
236
|
+
len(t.factors) == 0 for t in ModelDesc.from_formula("y ~ " + spec.expression).rhs_termlist
|
|
237
|
+
):
|
|
238
|
+
raise ValueError("logmodel requires an intercept for its reported null-model comparison.")
|
|
239
|
+
try:
|
|
240
|
+
with warnings.catch_warnings():
|
|
241
|
+
warnings.simplefilter("error", PerfectSeparationWarning)
|
|
242
|
+
warnings.simplefilter("error", RuntimeWarning)
|
|
243
|
+
model = smf.logit(spec.backend(factors, reference), data=frame).fit(
|
|
244
|
+
disp=False, maxiter=200
|
|
245
|
+
)
|
|
246
|
+
except (
|
|
247
|
+
PerfectSeparationWarning,
|
|
248
|
+
PerfectSeparationError,
|
|
249
|
+
np.linalg.LinAlgError,
|
|
250
|
+
RuntimeWarning,
|
|
251
|
+
) as exc:
|
|
252
|
+
raise ValueError(
|
|
253
|
+
"Logistic inference failed: inspect separation, redundant predictors, and sparse groups."
|
|
254
|
+
) from exc
|
|
255
|
+
if not model.mle_retvals.get("converged", False):
|
|
256
|
+
raise ValueError(
|
|
257
|
+
"Logistic regression did not converge; inspect separation and predictor scales."
|
|
258
|
+
)
|
|
259
|
+
validate_model(model)
|
|
260
|
+
notes.extend(
|
|
261
|
+
[
|
|
262
|
+
f"Models P({spec.outcome} = {event!r}); the other outcome is {baseline!r}.",
|
|
263
|
+
f"Odds ratios compare a one-unit change, or a category against its reference, holding other predictors constant. {100 * (1 - alpha):g}% Wald confidence intervals.",
|
|
264
|
+
"McFadden pseudo-R² is not the proportion of variance explained. Predictions are in model.predict().",
|
|
265
|
+
]
|
|
266
|
+
)
|
|
267
|
+
if np.max(np.abs(model.params)) > 15 or np.max(model.bse) > 100:
|
|
268
|
+
notes.append(
|
|
269
|
+
"Large estimates or standard errors suggest possible quasi-separation; interpret with caution."
|
|
270
|
+
)
|
|
271
|
+
tables = {
|
|
272
|
+
"sample": sample_table(len(data), len(frame)),
|
|
273
|
+
"outcome_counts": pd.DataFrame(
|
|
274
|
+
{
|
|
275
|
+
"outcome": [baseline, event],
|
|
276
|
+
"n": [int((frame[spec.outcome] == 0).sum()), int(frame[spec.outcome].sum())],
|
|
277
|
+
}
|
|
278
|
+
),
|
|
279
|
+
"model": pd.DataFrame(
|
|
280
|
+
[
|
|
281
|
+
{
|
|
282
|
+
"n": int(model.nobs),
|
|
283
|
+
"LR_chi2": model.llr,
|
|
284
|
+
"df": model.df_model,
|
|
285
|
+
"p": model.llr_pvalue,
|
|
286
|
+
"mcfadden_pseudo_r_squared": model.prsquared,
|
|
287
|
+
"AIC": model.aic,
|
|
288
|
+
"converged": True,
|
|
289
|
+
}
|
|
290
|
+
]
|
|
291
|
+
),
|
|
292
|
+
"coefficients": coefficients(model, spec, alpha, logistic=True),
|
|
293
|
+
}
|
|
294
|
+
if coding:
|
|
295
|
+
tables["coding"] = coding_table(coding)
|
|
296
|
+
return AnalysisResult(
|
|
297
|
+
"Binary logistic regression",
|
|
298
|
+
tables,
|
|
299
|
+
notes,
|
|
300
|
+
{"formula": formula, "method": "logit", "event": event, "alpha": alpha, "coding": coding},
|
|
301
|
+
model,
|
|
302
|
+
)
|
rstats/result.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""A single result interface for notebooks and scripts."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from html import escape
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _display_table(frame):
|
|
11
|
+
out = frame.copy()
|
|
12
|
+
for col in out:
|
|
13
|
+
if pd.api.types.is_numeric_dtype(out[col]):
|
|
14
|
+
if str(col).startswith("p_") or col == "p":
|
|
15
|
+
out[col] = out[col].map(
|
|
16
|
+
lambda v: "—" if pd.isna(v) else "< .001" if v < 0.001 else f"{v:.3f}"
|
|
17
|
+
)
|
|
18
|
+
elif not pd.api.types.is_integer_dtype(out[col]):
|
|
19
|
+
out[col] = out[col].map(lambda v: "—" if pd.isna(v) else f"{v:.3f}")
|
|
20
|
+
return out
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class AnalysisResult:
|
|
25
|
+
"""Reusable full-precision tables and a rich notebook representation.
|
|
26
|
+
|
|
27
|
+
``model`` is the underlying statsmodels result when available. Diagnostics
|
|
28
|
+
are explanatory notes, not automatic changes to the requested analysis.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
title: str
|
|
32
|
+
tables: dict[str, pd.DataFrame]
|
|
33
|
+
diagnostics: list[str] = field(default_factory=list)
|
|
34
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
35
|
+
model: Any = field(default=None, repr=False)
|
|
36
|
+
|
|
37
|
+
def __str__(self):
|
|
38
|
+
parts = [self.title]
|
|
39
|
+
for name, frame in self.tables.items():
|
|
40
|
+
parts.extend(["", name.replace("_", " ").title(), _display_table(frame).to_string()])
|
|
41
|
+
if self.diagnostics:
|
|
42
|
+
parts.extend(["", "Notes", *[f"• {note}" for note in self.diagnostics]])
|
|
43
|
+
return "\n".join(parts)
|
|
44
|
+
|
|
45
|
+
def _repr_html_(self):
|
|
46
|
+
parts = [f"<section><h2>{escape(self.title)}</h2>"]
|
|
47
|
+
for name, frame in self.tables.items():
|
|
48
|
+
parts.append(f"<h3>{escape(name.replace('_', ' ').title())}</h3>")
|
|
49
|
+
parts.append(_display_table(frame).to_html(escape=True, border=0))
|
|
50
|
+
if self.diagnostics:
|
|
51
|
+
parts.append("<h3>Notes</h3><ul>")
|
|
52
|
+
parts.extend(f"<li>{escape(str(note))}</li>" for note in self.diagnostics)
|
|
53
|
+
parts.append("</ul>")
|
|
54
|
+
return "".join(parts) + "</section>"
|
|
55
|
+
|
|
56
|
+
def show(self):
|
|
57
|
+
"""Display this result in a notebook, or print it in a script."""
|
|
58
|
+
try:
|
|
59
|
+
from IPython import get_ipython
|
|
60
|
+
from IPython.display import display
|
|
61
|
+
|
|
62
|
+
shell = get_ipython()
|
|
63
|
+
if shell is not None and shell.__class__.__name__ == "ZMQInteractiveShell":
|
|
64
|
+
display(self)
|
|
65
|
+
return
|
|
66
|
+
except ImportError:
|
|
67
|
+
pass
|
|
68
|
+
print(self)
|
rstats/visualization.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""Standalone Seaborn plots with type-aware defaults and no global styling."""
|
|
2
|
+
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import seaborn as sns
|
|
6
|
+
|
|
7
|
+
from ._data import complete, names, numeric, parse
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def vis(
|
|
11
|
+
formula,
|
|
12
|
+
*,
|
|
13
|
+
data,
|
|
14
|
+
type=None,
|
|
15
|
+
categorical=None,
|
|
16
|
+
hue=None,
|
|
17
|
+
palette=None,
|
|
18
|
+
colors="default",
|
|
19
|
+
xlabel=None,
|
|
20
|
+
ylabel=None,
|
|
21
|
+
title=None,
|
|
22
|
+
estimator=None,
|
|
23
|
+
normalize=None,
|
|
24
|
+
units=None,
|
|
25
|
+
ax=None,
|
|
26
|
+
**kwargs,
|
|
27
|
+
):
|
|
28
|
+
"""Create a standalone plot and return its Matplotlib Axes.
|
|
29
|
+
|
|
30
|
+
``vis('score ~ age', data=df)`` defaults to scatter. ``vis('score', data=df)``
|
|
31
|
+
defaults to histogram. ``line`` needs estimator='mean'/'median' or units=;
|
|
32
|
+
``proportion`` needs normalize='row'/'column'/'total'. Seaborn keyword
|
|
33
|
+
options pass through after the shared arguments.
|
|
34
|
+
"""
|
|
35
|
+
if isinstance(formula, str) and "~" not in formula:
|
|
36
|
+
x, y = formula.strip().strip("`"), None
|
|
37
|
+
else:
|
|
38
|
+
spec = parse(formula)
|
|
39
|
+
if len(spec.predictors) != 1 or spec.expression.strip() != next(iter(spec.tokens), ""):
|
|
40
|
+
raise ValueError(
|
|
41
|
+
"For a two-variable plot use 'outcome ~ predictor' without interactions."
|
|
42
|
+
)
|
|
43
|
+
y, x = spec.outcome, spec.predictors[0]
|
|
44
|
+
columns = list(dict.fromkeys([c for c in [x, y, hue, units] if c is not None]))
|
|
45
|
+
frame, _ = complete(data, columns)
|
|
46
|
+
marked = names(categorical)
|
|
47
|
+
if set(marked) - set(columns):
|
|
48
|
+
raise ValueError("categorical must name variables used in the plot.")
|
|
49
|
+
for col in marked:
|
|
50
|
+
frame[col] = frame[col].astype("category")
|
|
51
|
+
is_numeric = lambda col: (
|
|
52
|
+
col is not None
|
|
53
|
+
and pd.api.types.is_numeric_dtype(frame[col])
|
|
54
|
+
and not pd.api.types.is_bool_dtype(frame[col])
|
|
55
|
+
)
|
|
56
|
+
if type is None:
|
|
57
|
+
type = (
|
|
58
|
+
("hist" if is_numeric(x) else "count")
|
|
59
|
+
if y is None
|
|
60
|
+
else (
|
|
61
|
+
"scatter"
|
|
62
|
+
if is_numeric(x) and is_numeric(y)
|
|
63
|
+
else "box"
|
|
64
|
+
if is_numeric(x) != is_numeric(y)
|
|
65
|
+
else "heatmap"
|
|
66
|
+
)
|
|
67
|
+
)
|
|
68
|
+
allowed = {
|
|
69
|
+
"scatter",
|
|
70
|
+
"box",
|
|
71
|
+
"violin",
|
|
72
|
+
"hist",
|
|
73
|
+
"density",
|
|
74
|
+
"count",
|
|
75
|
+
"proportion",
|
|
76
|
+
"heatmap",
|
|
77
|
+
"line",
|
|
78
|
+
}
|
|
79
|
+
if type not in allowed:
|
|
80
|
+
raise ValueError(f"type must be one of {sorted(allowed)}.")
|
|
81
|
+
if palette is not None and colors != "default":
|
|
82
|
+
raise ValueError("Choose palette= or colors=, not both.")
|
|
83
|
+
selected_palette = (
|
|
84
|
+
palette if palette is not None else "colorblind" if colors == "default" else colors
|
|
85
|
+
)
|
|
86
|
+
if ax is None:
|
|
87
|
+
_, ax = plt.subplots(figsize=(7, 4.5))
|
|
88
|
+
style = (
|
|
89
|
+
{"palette": selected_palette}
|
|
90
|
+
if hue is not None
|
|
91
|
+
else {"color": sns.color_palette(selected_palette)[0]}
|
|
92
|
+
)
|
|
93
|
+
common = {"data": frame, "ax": ax, **style}
|
|
94
|
+
if hue is not None:
|
|
95
|
+
common["hue"] = hue
|
|
96
|
+
if type == "scatter":
|
|
97
|
+
if y is None:
|
|
98
|
+
raise ValueError("Scatter plots need 'y ~ x'.")
|
|
99
|
+
numeric(frame[x], x)
|
|
100
|
+
numeric(frame[y], y)
|
|
101
|
+
sns.scatterplot(x=x, y=y, **common, **kwargs)
|
|
102
|
+
elif type in {"box", "violin"}:
|
|
103
|
+
if y is None or not (is_numeric(x) or is_numeric(y)):
|
|
104
|
+
raise ValueError("Box/violin plots need a numeric outcome and grouping variable.")
|
|
105
|
+
plot = sns.boxplot if type == "box" else sns.violinplot
|
|
106
|
+
if is_numeric(y):
|
|
107
|
+
frame[x] = frame[x].astype("category")
|
|
108
|
+
plot(x=x, y=y, **common, **kwargs)
|
|
109
|
+
else:
|
|
110
|
+
frame[y] = frame[y].astype("category")
|
|
111
|
+
plot(x=x, y=y, orient="h", **common, **kwargs)
|
|
112
|
+
elif type in {"hist", "density"}:
|
|
113
|
+
if y is not None:
|
|
114
|
+
raise ValueError(
|
|
115
|
+
"For a distribution use vis('score', data=df, type='hist' or 'density')."
|
|
116
|
+
)
|
|
117
|
+
numeric(frame[x], x)
|
|
118
|
+
(sns.histplot if type == "hist" else sns.kdeplot)(x=x, **common, **kwargs)
|
|
119
|
+
elif type == "count":
|
|
120
|
+
if y is not None:
|
|
121
|
+
if hue is not None:
|
|
122
|
+
raise ValueError("A two-variable count plot already uses the outcome as hue.")
|
|
123
|
+
common.pop("color", None)
|
|
124
|
+
common.update(hue=y, palette=selected_palette)
|
|
125
|
+
sns.countplot(x=x, **common, **kwargs)
|
|
126
|
+
elif type == "heatmap":
|
|
127
|
+
if y is None or hue is not None:
|
|
128
|
+
raise ValueError("Contingency heatmaps need 'row ~ column' and no hue.")
|
|
129
|
+
counts = pd.crosstab(frame[y], frame[x])
|
|
130
|
+
options = {"annot": True, "fmt": "g", "cmap": "Blues", **kwargs}
|
|
131
|
+
sns.heatmap(counts, ax=ax, **options)
|
|
132
|
+
elif type == "proportion":
|
|
133
|
+
if normalize not in {"row", "column", "total"} or y is None or hue is not None:
|
|
134
|
+
raise ValueError(
|
|
135
|
+
"Proportion plots need 'outcome ~ group', normalize='row'/'column'/'total', and no hue."
|
|
136
|
+
)
|
|
137
|
+
counts = pd.crosstab(
|
|
138
|
+
frame[x],
|
|
139
|
+
frame[y],
|
|
140
|
+
normalize={"row": "index", "column": "columns", "total": "all"}[normalize],
|
|
141
|
+
)
|
|
142
|
+
long = (
|
|
143
|
+
counts.rename_axis(index="_group", columns="_outcome")
|
|
144
|
+
.stack()
|
|
145
|
+
.rename("percent")
|
|
146
|
+
.reset_index()
|
|
147
|
+
)
|
|
148
|
+
long["percent"] *= 100
|
|
149
|
+
sns.barplot(
|
|
150
|
+
data=long,
|
|
151
|
+
x="_group",
|
|
152
|
+
y="percent",
|
|
153
|
+
hue="_outcome",
|
|
154
|
+
palette=selected_palette,
|
|
155
|
+
ax=ax,
|
|
156
|
+
**kwargs,
|
|
157
|
+
)
|
|
158
|
+
ax.set_xlabel(x)
|
|
159
|
+
ax.set_ylabel(f"Percent ({normalize} denominator)")
|
|
160
|
+
elif type == "line":
|
|
161
|
+
if y is None:
|
|
162
|
+
raise ValueError("Line plots need 'y ~ x'.")
|
|
163
|
+
numeric(frame[y], y)
|
|
164
|
+
if estimator not in {"mean", "median", None}:
|
|
165
|
+
raise ValueError("Line estimator must be 'mean', 'median', or None.")
|
|
166
|
+
if estimator is None and units is None:
|
|
167
|
+
raise ValueError("Line plots require estimator='mean'/'median' or units='subject_id'.")
|
|
168
|
+
if estimator is not None and units is not None:
|
|
169
|
+
raise ValueError("Use an aggregate estimator or individual units, not both.")
|
|
170
|
+
options = {"estimator": estimator, **kwargs}
|
|
171
|
+
if units is not None:
|
|
172
|
+
options.update(units=units, errorbar=None)
|
|
173
|
+
sns.lineplot(x=x, y=y, **common, **options)
|
|
174
|
+
if xlabel is not None:
|
|
175
|
+
ax.set_xlabel(xlabel)
|
|
176
|
+
if ylabel is not None:
|
|
177
|
+
ax.set_ylabel(ylabel)
|
|
178
|
+
if title is not None:
|
|
179
|
+
ax.set_title(title)
|
|
180
|
+
return ax
|