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 ADDED
@@ -0,0 +1,11 @@
1
+ """Rstats: familiar commands, complete statistical reports."""
2
+
3
+ from .anova import aov
4
+ from .categorical import chisq, table
5
+ from .descriptive import descriptives
6
+ from .regression import lm, logmodel
7
+ from .result import AnalysisResult
8
+ from .visualization import vis
9
+
10
+ __version__ = "0.1.0"
11
+ __all__ = ["AnalysisResult", "aov", "chisq", "descriptives", "lm", "logmodel", "table", "vis"]
rstats/_data.py ADDED
@@ -0,0 +1,164 @@
1
+ """Shared validation and a deliberately small, non-evaluating formula language."""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from patsy import ModelDesc
9
+
10
+
11
+ def names(value):
12
+ return [] if value is None else [value] if isinstance(value, str) else list(value)
13
+
14
+
15
+ def dataframe(data, columns):
16
+ if not isinstance(data, pd.DataFrame):
17
+ raise TypeError("data must be a pandas DataFrame. Load your data with pandas first.")
18
+ if not data.columns.is_unique:
19
+ raise ValueError("Dataframe column names must be unique.")
20
+ absent = [c for c in columns if c not in data.columns]
21
+ if absent:
22
+ raise ValueError(f"Columns not found: {absent}.")
23
+ return data.loc[:, list(dict.fromkeys(columns))].copy(deep=True)
24
+
25
+
26
+ def complete(data, columns, missing="drop"):
27
+ if missing not in {"drop", "raise"}:
28
+ raise ValueError("missing must be 'drop' or 'raise'.")
29
+ out = dataframe(data, columns)
30
+ for col in out.select_dtypes(include="number"):
31
+ if np.isinf(out[col].to_numpy(dtype=float, na_value=np.nan)).any():
32
+ raise ValueError(f"{col!r} contains infinite values; resolve them before analysis.")
33
+ excluded = int(out.isna().any(axis=1).sum())
34
+ if excluded and missing == "raise":
35
+ raise ValueError(
36
+ f"{excluded} rows have missing analysis values; resolve them or use missing='drop'."
37
+ )
38
+ out = out.dropna().reset_index(drop=True)
39
+ if out.empty:
40
+ raise ValueError("No complete observations remain for this analysis.")
41
+ return out, [f"Analyzed {len(out)} of {len(data)} rows; excluded {excluded} incomplete rows."]
42
+
43
+
44
+ def numeric(series, label):
45
+ if not pd.api.types.is_numeric_dtype(series) or pd.api.types.is_bool_dtype(series):
46
+ raise ValueError(f"{label!r} must contain numeric values.")
47
+
48
+
49
+ def alpha_value(alpha):
50
+ if isinstance(alpha, bool) or not 0 < alpha < 1:
51
+ raise ValueError("alpha must be between 0 and 1.")
52
+
53
+
54
+ def levels(series):
55
+ observed = series.dropna().unique().tolist()
56
+ if isinstance(series.dtype, pd.CategoricalDtype):
57
+ return [v for v in series.cat.categories if v in observed]
58
+ try:
59
+ return sorted(observed)
60
+ except TypeError:
61
+ return sorted(observed, key=lambda v: (type(v).__name__, str(v)))
62
+
63
+
64
+ @dataclass
65
+ class Formula:
66
+ outcome: str
67
+ predictors: list[str]
68
+ forced: list[str]
69
+ expression: str
70
+ tokens: dict[str, str]
71
+
72
+ def backend(self, factors=(), reference=None, sum_contrasts=False):
73
+ reference = reference or {}
74
+ replacements = {}
75
+ for token, name in self.tokens.items():
76
+ quoted = f"Q({name!r})"
77
+ if name in factors:
78
+ contrast = (
79
+ "Sum"
80
+ if sum_contrasts
81
+ else (
82
+ f"Treatment(reference={reference[name]!r})"
83
+ if name in reference
84
+ else "Treatment"
85
+ )
86
+ )
87
+ quoted = f"C({quoted}, {contrast})"
88
+ replacements[token] = quoted
89
+ expression = re.sub(r"\bv\d+\b", lambda m: replacements[m[0]], self.expression)
90
+ return f"Q({self.outcome!r}) ~ {expression}"
91
+
92
+
93
+ def parse(formula):
94
+ if not isinstance(formula, str) or formula.count("~") != 1:
95
+ raise ValueError("Use a quoted formula such as 'score ~ group + age'.")
96
+ lhs, rhs = [v.strip() for v in formula.split("~")]
97
+ atom = r"(?:`[^`]+`|[A-Za-z_]\w*)"
98
+ if not re.fullmatch(atom, lhs):
99
+ raise ValueError("Use one outcome column; put names with spaces in backticks.")
100
+ token_pattern = re.compile(rf"(?:factor|C)\(\s*({atom})\s*\)|({atom})|([01])|([+*:\-()])")
101
+ cursor, tokens, predictors, forced, expression = 0, {}, [], [], []
102
+ for match in token_pattern.finditer(rhs):
103
+ if rhs[cursor : match.start()].strip():
104
+ raise ValueError(
105
+ "Supported formulas use column names, factor(name), +, *, :, and intercept 0/1."
106
+ )
107
+ cursor = match.end()
108
+ if match[1] or match[2]:
109
+ name = (match[1] or match[2]).strip("`")
110
+ if name not in predictors:
111
+ predictors.append(name)
112
+ token = f"v{predictors.index(name)}"
113
+ tokens[token] = name
114
+ expression.append(token)
115
+ if match[1] and name not in forced:
116
+ forced.append(name)
117
+ else:
118
+ expression.append(match[3] or match[4])
119
+ if rhs[cursor:].strip() or not expression:
120
+ raise ValueError("Unsupported formula. Example: 'score ~ group * method + age'.")
121
+ expr = " ".join(expression)
122
+ if re.search(r"-\s*(?!1\b)", expr):
123
+ raise ValueError("Only '- 1' is supported for removing an intercept.")
124
+ try:
125
+ ModelDesc.from_formula("y ~ " + expr)
126
+ except Exception as exc:
127
+ raise ValueError(f"Invalid formula: {formula!r}.") from exc
128
+ return Formula(lhs.strip("`"), predictors, forced, expr, tokens)
129
+
130
+
131
+ def factorize(data, candidates, reference=None):
132
+ reference = reference or {}
133
+ unknown = set(reference) - set(candidates)
134
+ if unknown:
135
+ raise ValueError(
136
+ f"Reference groups supplied for non-categorical predictors: {sorted(unknown)}."
137
+ )
138
+ coding = {}
139
+ for col in candidates:
140
+ lev = levels(data[col])
141
+ if len(lev) < 2:
142
+ raise ValueError(f"Categorical predictor {col!r} needs at least two observed levels.")
143
+ if col in reference:
144
+ if reference[col] not in lev:
145
+ raise ValueError(
146
+ f"Reference {reference[col]!r} is not an observed level of {col!r}."
147
+ )
148
+ lev = [reference[col]] + [v for v in lev if v != reference[col]]
149
+ data[col] = pd.Categorical(data[col].to_numpy(), categories=lev)
150
+ coding[col] = {"levels": lev, "reference": lev[0]}
151
+ return coding
152
+
153
+
154
+ def sample_table(total, analyzed):
155
+ return pd.DataFrame(
156
+ [{"input_rows": total, "analyzed_rows": analyzed, "excluded_rows": total - analyzed}]
157
+ )
158
+
159
+
160
+ def clean_term(term, spec):
161
+ for col in sorted(spec.predictors + [spec.outcome], key=len, reverse=True):
162
+ term = term.replace(f"Q({col!r})", col)
163
+ term = re.sub(r"C\(([^,]+), (?:Sum|Treatment(?:\(reference=.*?\))?)\)", r"\1", term)
164
+ return term
rstats/_posthoc.py ADDED
@@ -0,0 +1,278 @@
1
+ """Omnibus-gated comparisons with explicit test and adjustment families."""
2
+
3
+ from itertools import combinations, product
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from patsy import build_design_matrices
8
+ from scipy import stats
9
+ from statsmodels.stats.multitest import multipletests
10
+
11
+ from ._data import levels
12
+
13
+ ADJUSTMENTS = {
14
+ "holm": "holm",
15
+ "bonferroni": "bonferroni",
16
+ "sidak": "sidak",
17
+ "holm-sidak": "holm-sidak",
18
+ "fdr-bh": "fdr_bh",
19
+ "fdr-by": "fdr_by",
20
+ }
21
+ SPECIAL = {"tukey", "games-howell", "dunnett", "scheffe"}
22
+
23
+
24
+ def method_name(value):
25
+ if value is False:
26
+ return None
27
+ if value is True:
28
+ return "tukey"
29
+ if not isinstance(value, str) or value.lower() not in ADJUSTMENTS.keys() | SPECIAL:
30
+ raise ValueError(
31
+ "posthocifsig must be False, True (Tukey), or one of: "
32
+ + ", ".join(sorted(ADJUSTMENTS.keys() | SPECIAL))
33
+ )
34
+ return value.lower()
35
+
36
+
37
+ def validate_method(method, *, factors, covariates, repeated, control, frame):
38
+ if method is None:
39
+ if control is not None:
40
+ raise ValueError("control= is used only with posthocifsig='dunnett'.")
41
+ return
42
+ if method in SPECIAL and (len(factors) != 1 or covariates or repeated):
43
+ raise ValueError(
44
+ f"{method!r} is supported for one independent grouping factor without covariates. "
45
+ "Use posthocifsig='holm' for model-adjusted or repeated/mixed comparisons."
46
+ )
47
+ if method == "dunnett":
48
+ if control is None or control not in levels(frame[factors[0]]):
49
+ raise ValueError("Dunnett needs control= set to an observed group level.")
50
+ elif control is not None:
51
+ raise ValueError("control= applies only to posthocifsig='dunnett'.")
52
+ if method == "games-howell" and frame.groupby(factors[0], observed=True).size().min() < 2:
53
+ raise ValueError("Games–Howell needs at least two observations in each group.")
54
+
55
+
56
+ def _special(method, frame, outcome, factor, model, alpha, control):
57
+ lev = levels(frame[factor])
58
+ samples = [frame.loc[frame[factor] == value, outcome].to_numpy(dtype=float) for value in lev]
59
+ if method == "games-howell" and any(np.var(x, ddof=1) <= 0 for x in samples):
60
+ raise ValueError("Games–Howell needs positive variance in each group.")
61
+ rows = []
62
+ if method in {"tukey", "games-howell"}:
63
+ result = stats.tukey_hsd(*samples, equal_var=method == "tukey")
64
+ ci = result.confidence_interval(1 - alpha)
65
+ for i, j in combinations(range(len(lev)), 2):
66
+ rows.append(
67
+ {
68
+ "group_a": lev[i],
69
+ "group_b": lev[j],
70
+ "estimate": result.statistic[i, j],
71
+ "p_adjusted": result.pvalue[i, j],
72
+ "ci_low": ci.low[i, j],
73
+ "ci_high": ci.high[i, j],
74
+ }
75
+ )
76
+ elif method == "dunnett":
77
+ index = lev.index(control)
78
+ treatment_indices = [i for i in range(len(lev)) if i != index]
79
+ result = stats.dunnett(
80
+ *[samples[i] for i in treatment_indices],
81
+ control=samples[index],
82
+ rng=np.random.default_rng(0),
83
+ )
84
+ ci = result.confidence_interval(1 - alpha)
85
+ for k, i in enumerate(treatment_indices):
86
+ rows.append(
87
+ {
88
+ "group_a": lev[i],
89
+ "group_b": control,
90
+ "estimate": np.mean(samples[i]) - np.mean(samples[index]),
91
+ "statistic": result.statistic[k],
92
+ "p_adjusted": result.pvalue[k],
93
+ "ci_low": ci.low[k],
94
+ "ci_high": ci.high[k],
95
+ }
96
+ )
97
+ elif method == "scheffe":
98
+ rank = len(lev) - 1
99
+ critical = np.sqrt(rank * stats.f.ppf(1 - alpha, rank, model.df_resid))
100
+ for i, j in combinations(range(len(lev)), 2):
101
+ estimate = np.mean(samples[i]) - np.mean(samples[j])
102
+ se = np.sqrt(model.mse_resid * (1 / len(samples[i]) + 1 / len(samples[j])))
103
+ t = estimate / se
104
+ rows.append(
105
+ {
106
+ "group_a": lev[i],
107
+ "group_b": lev[j],
108
+ "estimate": estimate,
109
+ "std_error": se,
110
+ "df": model.df_resid,
111
+ "p_raw": 2 * stats.t.sf(abs(t), model.df_resid),
112
+ "p_adjusted": stats.f.sf(t * t / rank, rank, model.df_resid),
113
+ "ci_low": estimate - critical * se,
114
+ "ci_high": estimate + critical * se,
115
+ }
116
+ )
117
+ for row in rows:
118
+ row.update(
119
+ {
120
+ "family": factor,
121
+ "target": factor,
122
+ "condition": "all observations",
123
+ "test": method,
124
+ "adjustment": method,
125
+ "ci_coverage": "simultaneous",
126
+ "significant": row["p_adjusted"] < alpha,
127
+ }
128
+ )
129
+ return rows
130
+
131
+
132
+ def _slices(effect, frame):
133
+ """Main effects are marginal; interactions produce all simple-effect slices."""
134
+ for target in effect:
135
+ conditions = [col for col in effect if col != target]
136
+ for values in product(*[levels(frame[c]) for c in conditions]):
137
+ yield target, dict(zip(conditions, values))
138
+
139
+
140
+ def _ols_rows(effect, frame, outcome, factors, covariates, model, alpha):
141
+ # Equal-weight marginal means at the analyzed-sample covariate means.
142
+ grid = pd.DataFrame(product(*[levels(frame[col]) for col in factors]), columns=factors)
143
+ for col in covariates:
144
+ grid[col] = frame[col].mean()
145
+ info = getattr(model.model.data, "design_info", None)
146
+ if info is None:
147
+ info = model.model.data.model_spec
148
+ matrix = np.asarray(build_design_matrices([info], grid)[0])
149
+ rows = []
150
+ for target, condition in _slices(effect, frame):
151
+ mask = np.ones(len(grid), dtype=bool)
152
+ for col, value in condition.items():
153
+ mask &= grid[col].to_numpy() == value
154
+ means = {
155
+ value: matrix[mask & (grid[target].to_numpy() == value)].mean(axis=0)
156
+ for value in levels(frame[target])
157
+ }
158
+ for a, b in combinations(means, 2):
159
+ contrast = means[a] - means[b]
160
+ test = model.t_test(contrast)
161
+ ci = np.asarray(test.conf_int(alpha=alpha)).ravel()
162
+ rows.append(
163
+ {
164
+ "target": target,
165
+ "condition": ", ".join(f"{c}={v}" for c, v in condition.items()) or "marginal",
166
+ "group_a": a,
167
+ "group_b": b,
168
+ "estimate": float(np.asarray(test.effect).item()),
169
+ "std_error": float(np.asarray(test.sd).item()),
170
+ "df": model.df_resid,
171
+ "t": float(np.asarray(test.tvalue).item()),
172
+ "p_raw": float(np.asarray(test.pvalue).item()),
173
+ "ci_low": ci[0],
174
+ "ci_high": ci[1],
175
+ "test": "OLS marginal-mean contrast",
176
+ "ci_coverage": "pointwise",
177
+ }
178
+ )
179
+ return rows
180
+
181
+
182
+ def _repeated_rows(effect, frame, outcome, subject, within, alpha):
183
+ rows = []
184
+ for target, condition in _slices(effect, frame):
185
+ chunk = frame
186
+ for col, value in condition.items():
187
+ chunk = chunk.loc[chunk[col] == value]
188
+ # Subject means marginalize over other within factors before comparisons.
189
+ subject_means = (
190
+ chunk.groupby([subject, target], observed=True)[outcome].mean().reset_index()
191
+ )
192
+ for a, b in combinations(levels(frame[target]), 2):
193
+ aa = subject_means.loc[subject_means[target] == a].set_index(subject)[outcome]
194
+ bb = subject_means.loc[subject_means[target] == b].set_index(subject)[outcome]
195
+ paired = target in within
196
+ if paired:
197
+ matched = pd.concat([aa.rename("a"), bb.rename("b")], axis=1).dropna()
198
+ delta = matched.a - matched.b
199
+ df = len(delta) - 1
200
+ estimate = delta.mean()
201
+ se = delta.std(ddof=1) / np.sqrt(len(delta))
202
+ label = "Paired subject-mean t test"
203
+ else:
204
+ estimate = aa.mean() - bb.mean()
205
+ va, vb = aa.var(ddof=1) / len(aa), bb.var(ddof=1) / len(bb)
206
+ se = np.sqrt(va + vb)
207
+ df = (va + vb) ** 2 / (va**2 / (len(aa) - 1) + vb**2 / (len(bb) - 1))
208
+ label = "Welch subject-mean t test"
209
+ if not np.isfinite(se) or se <= 0 or not np.isfinite(df) or df <= 0:
210
+ raise ValueError(
211
+ "A requested comparison has insufficient observations or zero contrast variance."
212
+ )
213
+ t = estimate / se
214
+ margin = stats.t.ppf(1 - alpha / 2, df) * se
215
+ rows.append(
216
+ {
217
+ "target": target,
218
+ "condition": ", ".join(f"{c}={v}" for c, v in condition.items()) or "marginal",
219
+ "group_a": a,
220
+ "group_b": b,
221
+ "estimate": estimate,
222
+ "std_error": se,
223
+ "df": df,
224
+ "t": t,
225
+ "p_raw": 2 * stats.t.sf(abs(t), df),
226
+ "ci_low": estimate - margin,
227
+ "ci_high": estimate + margin,
228
+ "test": label,
229
+ "ci_coverage": "pointwise",
230
+ }
231
+ )
232
+ return rows
233
+
234
+
235
+ def comparisons(
236
+ method,
237
+ effects,
238
+ *,
239
+ frame,
240
+ outcome,
241
+ factors,
242
+ covariates,
243
+ model,
244
+ alpha,
245
+ control=None,
246
+ subject=None,
247
+ within=(),
248
+ ):
249
+ if method is None:
250
+ return None
251
+ if not effects:
252
+ return pd.DataFrame(
253
+ columns=["family", "target", "group_a", "group_b", "estimate", "p_adjusted"]
254
+ )
255
+ if method in SPECIAL:
256
+ return pd.DataFrame(_special(method, frame, outcome, factors[0], model, alpha, control))
257
+ rows = []
258
+ for effect in effects:
259
+ current = (
260
+ _repeated_rows(effect, frame, outcome, subject, within, alpha)
261
+ if subject
262
+ else _ols_rows(effect, frame, outcome, factors, covariates, model, alpha)
263
+ )
264
+ if current:
265
+ adjusted = multipletests(
266
+ [v["p_raw"] for v in current], alpha=alpha, method=ADJUSTMENTS[method]
267
+ )[1]
268
+ for row, p in zip(current, adjusted):
269
+ row.update(
270
+ {
271
+ "family": ":".join(effect),
272
+ "adjustment": method,
273
+ "p_adjusted": p,
274
+ "significant": p < alpha,
275
+ }
276
+ )
277
+ rows.extend(current)
278
+ return pd.DataFrame(rows)