rstatspython 0.1.0__py3-none-any.whl → 0.1.1__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 CHANGED
@@ -7,5 +7,5 @@ from .regression import lm, logmodel
7
7
  from .result import AnalysisResult
8
8
  from .visualization import vis
9
9
 
10
- __version__ = "0.1.0"
10
+ __version__ = "0.1.1"
11
11
  __all__ = ["AnalysisResult", "aov", "chisq", "descriptives", "lm", "logmodel", "table", "vis"]
rstats/anova.py CHANGED
@@ -8,6 +8,7 @@ import pandas as pd
8
8
  import pingouin as pg
9
9
  from patsy import ModelDesc
10
10
  from scipy import stats
11
+ from scipy.linalg import helmert
11
12
  from statsmodels.stats.anova import anova_lm
12
13
 
13
14
  from ._data import (
@@ -27,6 +28,59 @@ from .regression import coding_table, fit_ols, ols_diagnostics
27
28
  from .result import AnalysisResult
28
29
 
29
30
 
31
+ def _repeated_corrections(tests, frame, outcome, subject, within, between, effects):
32
+ """Compute corrections on orthonormal within-subject contrasts."""
33
+ index = [subject, *between]
34
+ wide = frame.pivot(index=index, columns=within, values=outcome).sort_index(axis=1)
35
+ if between:
36
+ wide = wide - wide.groupby(level=between[0], observed=True).transform("mean")
37
+ residual_df = len(wide) - (frame[between[0]].nunique() if between else 1)
38
+ for row in tests.itertuples():
39
+ factors = [factor for factor in within if factor in effects.get(row.effect, [])]
40
+ if not factors:
41
+ continue
42
+ profiles = wide
43
+ if len(within) == 2 and len(factors) == 1:
44
+ profiles = wide.T.groupby(level=factors[0], observed=True).mean().T
45
+ contrast = helmert(frame[factors[0]].nunique(), full=False)
46
+ if len(factors) == 2:
47
+ contrast = np.kron(contrast, helmert(frame[factors[1]].nunique(), full=False))
48
+ dimension = contrast.shape[0]
49
+ tests.loc[row.Index, "eps"] = 1.0
50
+ if dimension == 1:
51
+ continue
52
+ covariance = np.cov(profiles.to_numpy(dtype=float) @ contrast.T, rowvar=False)
53
+ trace = np.trace(covariance)
54
+ if trace <= 0:
55
+ continue
56
+ epsilon = min(1.0, trace**2 / (dimension * np.sum(covariance**2)))
57
+ tests.loc[row.Index, "eps"] = epsilon
58
+ tests.loc[row.Index, "p_gg"] = stats.f.sf(
59
+ row.F, row.df_numerator * epsilon, row.df_denominator * epsilon
60
+ )
61
+ # Mauchly's chi-square approximation uses the residual covariance df.
62
+ sign, log_det = np.linalg.slogdet(covariance)
63
+ if sign <= 0 or residual_df < dimension:
64
+ continue
65
+ log_w = min(0.0, log_det - dimension * np.log(trace / dimension))
66
+ d = dimension
67
+ scale = residual_df - (2 * d**2 + d + 2) / (6 * d)
68
+ chi_square = -scale * log_w
69
+ df = d * (d + 1) / 2 - 1
70
+ second_order = (
71
+ (d + 2)
72
+ * (d - 1)
73
+ * (d - 2)
74
+ * (2 * d**3 + 6 * d**2 + 3 * wide.shape[1] + 2)
75
+ / (288 * (d * scale) ** 2)
76
+ )
77
+ p = stats.chi2.sf(chi_square, df)
78
+ p += second_order * (stats.chi2.sf(chi_square, df + 4) - p)
79
+ tests.loc[row.Index, "W_spher"] = np.exp(log_w)
80
+ tests.loc[row.Index, "p_spher"] = p
81
+ tests.loc[row.Index, "sphericity"] = bool(p > 0.05)
82
+
83
+
30
84
  def _group_descriptives(frame, outcome, factors, alpha):
31
85
  rows = []
32
86
  for keys, chunk in frame.groupby(factors, observed=True, sort=False):
@@ -216,7 +270,7 @@ def aov(
216
270
  within=within[0],
217
271
  between=between[0],
218
272
  subject=subject,
219
- correction=True,
273
+ correction=False,
220
274
  effsize="np2",
221
275
  )
222
276
  effect_map = {
@@ -260,6 +314,13 @@ def aov(
260
314
  # own row; multi-factor designs carry a denominator on each effect.
261
315
  error_df = tests.loc[tests.effect == "Error", "df_numerator"].iloc[0]
262
316
  tests["df_denominator"] = np.where(tests.effect == "Error", np.nan, error_df)
317
+ if between or len(within) == 2:
318
+ # Pingouin 0.6 supports Colab's dependencies but uses a different
319
+ # covariance for mixed designs and two-factor interactions.
320
+ tests = tests.drop(
321
+ columns=["p_gg", "sphericity", "W_spher", "p_spher"], errors="ignore"
322
+ )
323
+ _repeated_corrections(tests, frame, spec.outcome, subject, within, between, effect_map)
263
324
  tests["p"] = (
264
325
  tests["p_gg"].fillna(tests["p_uncorrected"])
265
326
  if correction == "gg" and "p_gg" in tests
rstats/categorical.py CHANGED
@@ -9,17 +9,28 @@ from .result import AnalysisResult
9
9
 
10
10
 
11
11
  def _variables(formula):
12
- if isinstance(formula, str) and "~" not in formula:
13
- return [formula.strip().strip("`")]
12
+ if isinstance(formula, str):
13
+ formula = formula.strip()
14
+ if formula.startswith("~"):
15
+ formula = formula[1:].strip()
16
+ if "~" not in formula and formula:
17
+ return [formula.strip("`")]
14
18
  spec = parse(formula)
15
- if len(spec.predictors) != 1 or any(c in spec.expression for c in "*:+-()"):
16
- raise ValueError("Use 'row ~ column' for a two-way categorical table.")
19
+ if len(spec.tokens) != 1 or spec.expression != next(iter(spec.tokens)):
20
+ raise ValueError("Use 'group' or '~ group' for one variable, or 'group ~ passed' for two.")
21
+ if spec.outcome == spec.predictors[0]:
22
+ raise ValueError("Use two distinct columns for a two-way categorical table.")
17
23
  return [spec.outcome, spec.predictors[0]]
18
24
 
19
25
 
26
+ def _contingency(frame, cols):
27
+ return frame.groupby(cols, observed=True).size().unstack(fill_value=0)
28
+
29
+
20
30
  def table(formula, *, data, percent="valid", missing="drop"):
21
- """Counts and percentages: ``table('group ~ passed', data=df, percent='row')``.
31
+ """Counts and percentages for one column or a two-column formula.
22
32
 
33
+ Use ``table('group', data=df)`` or ``table('group ~ passed', data=df)``.
23
34
  Missing values are excluded and counted separately. ``percent='valid'``
24
35
  uses the valid grand total; row/column/total apply to two-way tables.
25
36
  """
@@ -36,7 +47,7 @@ def table(formula, *, data, percent="valid", missing="drop"):
36
47
  percentages = (100 * counts / len(frame)).rename(columns={"count": "percent"})
37
48
  denominator = len(frame)
38
49
  else:
39
- counts = pd.crosstab(frame[cols[0]], frame[cols[1]])
50
+ counts = _contingency(frame, cols)
40
51
  denominator = (
41
52
  counts.sum(axis=1)
42
53
  if percent == "row"
@@ -64,6 +75,7 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
64
75
  """Pearson independence/GOF test, or explicit Fisher exact for a 2×2 table.
65
76
 
66
77
  ``chisq('group ~ passed', data=df)`` tests independence.
78
+ ``chisq('group', data=df)`` tests goodness of fit against equal proportions.
67
79
  ``chisq([20, 30, 50], expected=[.25, .25, .5])`` tests count proportions.
68
80
  """
69
81
  if method not in {"pearson", "fisher"}:
@@ -72,28 +84,25 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
72
84
  raise TypeError(
73
85
  "correction must be True or False (Yates correction for 2×2 Pearson tests)."
74
86
  )
75
- if isinstance(formula, str):
76
- cols = _variables(formula)
77
- if len(cols) != 2:
78
- raise ValueError(
79
- "For independence use 'group ~ outcome'; for goodness of fit pass a count vector."
80
- )
87
+ cols = _variables(formula) if isinstance(formula, str) else []
88
+ if len(cols) == 2:
81
89
  if expected is not None:
82
90
  raise ValueError("expected proportions apply only to goodness-of-fit count vectors.")
83
91
  frame, notes = complete(data, cols, missing)
84
- observed = pd.crosstab(frame[cols[0]], frame[cols[1]])
92
+ observed = _contingency(frame, cols)
93
+ counts = observed.to_numpy(dtype=np.int64)
85
94
  if min(observed.shape) < 2:
86
95
  raise ValueError(
87
96
  "An independence test needs at least two observed levels per variable."
88
97
  )
89
98
  if correction and observed.shape != (2, 2):
90
99
  raise ValueError("Yates correction is supported only for 2×2 tables.")
91
- chi2, p, dof, exp = stats.chi2_contingency(observed, correction=correction)
92
- residuals = (observed.to_numpy() - exp) / np.sqrt(exp)
100
+ chi2, p, dof, exp = stats.chi2_contingency(counts, correction=correction)
101
+ residuals = (counts - exp) / np.sqrt(exp)
93
102
  if method == "fisher":
94
103
  if observed.shape != (2, 2) or correction:
95
104
  raise ValueError("Fisher's test needs a 2×2 table and correction=False.")
96
- fisher = stats.fisher_exact(observed.to_numpy())
105
+ fisher = stats.fisher_exact(counts)
97
106
  summary = {"odds_ratio": fisher.statistic, "p": fisher.pvalue, "n": len(frame)}
98
107
  title = "Fisher exact test (two-sided)"
99
108
  else:
@@ -103,8 +112,7 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
103
112
  "p": p,
104
113
  "n": len(frame),
105
114
  "cramers_v": np.sqrt(
106
- stats.chi2_contingency(observed, correction=False)[0]
107
- / (len(frame) * min(np.array(observed.shape) - 1))
115
+ np.sum(residuals**2) / (len(frame) * min(np.array(observed.shape) - 1))
108
116
  ),
109
117
  }
110
118
  title = "Pearson chi-square test of independence"
@@ -122,7 +130,16 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
122
130
  else:
123
131
  if method != "pearson" or correction:
124
132
  raise ValueError("Goodness of fit uses method='pearson', correction=False.")
125
- obs = np.asarray(formula, dtype=float)
133
+ labels = None
134
+ notes = []
135
+ if cols:
136
+ frame, notes = complete(data, cols, missing)
137
+ frequencies = frame[cols[0]].value_counts(sort=False)
138
+ frequencies = frequencies[frequencies > 0]
139
+ labels = frequencies.index
140
+ obs = frequencies.to_numpy(dtype=float)
141
+ else:
142
+ obs = np.asarray(formula, dtype=float)
126
143
  if (
127
144
  obs.ndim != 1
128
145
  or len(obs) < 2
@@ -161,14 +178,13 @@ def chisq(formula, *, data=None, expected=None, method="pearson", correction=Fal
161
178
  ]
162
179
  ),
163
180
  "counts": pd.DataFrame(
164
- {"observed": obs, "expected": exp, "pearson_residual": (obs - exp) / np.sqrt(exp)}
181
+ {"observed": obs, "expected": exp, "pearson_residual": (obs - exp) / np.sqrt(exp)},
182
+ index=labels,
165
183
  ),
166
184
  }
167
- title, notes = (
168
- "Chi-square goodness-of-fit test",
169
- [
170
- "Expected proportions must be specified independently of these observations; fitted-probability degrees of freedom are not supported."
171
- ],
185
+ title = "Chi-square goodness-of-fit test"
186
+ notes.append(
187
+ "Expected proportions must be specified independently of these observations; fitted-probability degrees of freedom are not supported."
172
188
  )
173
189
  if (exp < 1).any() or (exp < 5).mean() > 0.2:
174
190
  notes.append(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: rstatspython
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Familiar commands. Complete statistical reports.
5
5
  Project-URL: Repository, https://github.com/drdanrb/Rstats
6
6
  Author: Rstats contributors
@@ -16,7 +16,7 @@ Requires-Dist: matplotlib>=3.9
16
16
  Requires-Dist: numpy>=2.0
17
17
  Requires-Dist: pandas<4,>=2.2
18
18
  Requires-Dist: patsy>=1.0
19
- Requires-Dist: pingouin<0.8,>=0.6
19
+ Requires-Dist: pingouin<0.7,>=0.6.1
20
20
  Requires-Dist: scipy>=1.16
21
21
  Requires-Dist: seaborn>=0.13.2
22
22
  Requires-Dist: statsmodels<0.16,>=0.14.4
@@ -45,11 +45,10 @@ otherwise require several separate calls. Plot independently with `vis()`.
45
45
  ## Install
46
46
 
47
47
  Python 3.12+; see CI for tested versions. This is an early research/teaching
48
- release, not a package published on PyPI. **Do not install the unrelated
49
- `rstats` PyPI package.** Install directly from GitHub:
48
+ release. Install [rstatspython from PyPI](https://pypi.org/project/rstatspython/):
50
49
 
51
50
  ```bash
52
- python -m pip install git+https://github.com/drdanrb/Rstats.git
51
+ python -m pip install -U rstatspython
53
52
  ```
54
53
 
55
54
  Or from the root of the supplied source checkout:
@@ -64,11 +63,13 @@ is required to use the library. In Colab, prefix the installation command with
64
63
  **Runtime → Run all**. The notebook installs Rstats if necessary and downloads
65
64
  the synthetic example data automatically; no file uploads are needed.
66
65
 
67
- PyPI publishing is prepared but awaits the owner's one-time Trusted Publisher
68
- setup. After the first successful publication, students will be able to use
69
- `pip install rstatspython` (or `%pip install rstatspython` in Colab).
70
- Until then, use the working GitHub installation above. See the
71
- [publishing instructions](docs/publishing.md).
66
+ For Colab, use version 0.1.1 or newer. If version 0.1.0 upgraded pandas in your
67
+ session, start a fresh runtime or run
68
+ `%pip install -U "rstatspython>=0.1.1" "pandas==2.2.3"` and restart the session.
69
+ The PyPI distribution is `rstatspython` and the import is `rstats`.
70
+ To install the development version instead, use
71
+ `python -m pip install git+https://github.com/drdanrb/Rstats.git`.
72
+ See the [publishing instructions](docs/publishing.md) for maintaining releases.
72
73
 
73
74
  ## One-line analyses
74
75
 
@@ -79,6 +80,7 @@ import rstats as rs
79
80
  df = pd.read_csv("https://raw.githubusercontent.com/drdanrb/Rstats/main/examples/students.csv")
80
81
 
81
82
  rs.descriptives(data=df, columns=["score", "study_hours"], by="group")
83
+ rs.table("group", data=df)
82
84
  rs.table("group ~ passed", data=df, percent="row")
83
85
  rs.chisq("group ~ passed", data=df)
84
86
  rs.aov("score ~ group", data=df, posthocifsig=True)
@@ -1,13 +1,13 @@
1
- rstats/__init__.py,sha256=YYTi1y18Dw3Sqszym78KJ5bs6sGH3HAPfYrcdFwKD70,384
1
+ rstats/__init__.py,sha256=ZYEE9ArDFIEK9i9DIwV0zuCbZIlZW33Q12d8JnF-BvU,384
2
2
  rstats/_data.py,sha256=JuZChcGaAFzl0lqXzLluNLGwg1a-P8FWPKMERc0ZYOY,6335
3
3
  rstats/_posthoc.py,sha256=oXNZF25K9Ue1Yewaty806uc_CvYqIT2FKtpdd-GUHI8,10905
4
- rstats/anova.py,sha256=jBYKZwHRVjNZ4XnufiZis4jn9vXh6RJQpHLRc59n9fo,18389
5
- rstats/categorical.py,sha256=FdPtTJWkAJGvPmXY5LyuJg544HAuic41vBQN_GdBGo8,7563
4
+ rstats/anova.py,sha256=piJ5ydgxdtYznLO95TOFPeTigSLYrn28iASiqDuww5A,21263
5
+ rstats/categorical.py,sha256=L7H_AlI46D3zi-bPVOM6HZb43w5kUEncRnWzrWfSVc4,8216
6
6
  rstats/descriptive.py,sha256=N8reqKq98IVifZ9S0ZZuLOlxrgtxNEM-3uLpdXPq5G4,4520
7
7
  rstats/regression.py,sha256=JB3biAwyDBwkFbTFScDF6Q4Z9nKLF8j_qvqvK_9nhf0,11415
8
8
  rstats/result.py,sha256=Kqfh4DhZdMOuTImOuJEZBpO7C9ZULblMcvsPQV9eGj4,2479
9
9
  rstats/visualization.py,sha256=d_eCAIiYxv92qwnkhNpmn-wmAZ8rSL4xPsOc4zxQd14,6501
10
- rstatspython-0.1.0.dist-info/METADATA,sha256=pudtDDYjFv-pseW_8VL5Vu9OVdxEY3oGDXUrgZK4VnM,7474
11
- rstatspython-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
- rstatspython-0.1.0.dist-info/licenses/LICENSE,sha256=0yeTcDCu3Tzp-Nohq_s8AuuGtQFumkZ7ABKvCpt4r-s,1076
13
- rstatspython-0.1.0.dist-info/RECORD,,
10
+ rstatspython-0.1.1.dist-info/METADATA,sha256=dBG8-DIK00c0VohdKV_4_Y3SxZvtDnzlWzr7KqDVczI,7560
11
+ rstatspython-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ rstatspython-0.1.1.dist-info/licenses/LICENSE,sha256=0yeTcDCu3Tzp-Nohq_s8AuuGtQFumkZ7ABKvCpt4r-s,1076
13
+ rstatspython-0.1.1.dist-info/RECORD,,