exactsampler 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.
@@ -0,0 +1,7 @@
1
+ """exactsampler: exact Fisher p-values for r x c tables (free core)."""
2
+
3
+ from ._fisher import fisher_exact_rc
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ __all__ = ["fisher_exact_rc", "__version__"]
@@ -0,0 +1,112 @@
1
+ """Exact Fisher test p-values for r x c contingency tables (free core).
2
+
3
+ ``scipy.stats.fisher_exact`` only handles 2x2 tables. The function here
4
+ generalizes Fisher's exact test to arbitrary r x c tables.
5
+
6
+ The p-value follows Fisher's definition: under the null of independence
7
+ conditional on the margins, each table has probability
8
+
9
+ P(X) = prod(r_i!) prod(c_j!) / (N! prod(X_ij!))
10
+
11
+ (the multivariate hypergeometric law); the p-value is the total null
12
+ probability of all tables whose probability is no larger than the observed
13
+ table's. For 2x2 tables this reproduces ``scipy.stats.fisher_exact``
14
+ (two-sided) exactly.
15
+ """
16
+
17
+ import math
18
+
19
+ import numpy as np
20
+
21
+ from ._tables import _count_upper_bound, enumerate_tables
22
+
23
+ __all__ = ["fisher_exact_rc"]
24
+
25
+ _PAID_URL = "https://groundplane0.gumroad.com/l/priui"
26
+
27
+ # Enumeration budget (tables). Tables whose estimated table count exceeds
28
+ # this are refused up front instead of hanging; the estimate itself costs
29
+ # O(r + c), so the refusal is always fast.
30
+ #
31
+ # Why 175,000: the tightest legitimate case in the test suite (3x5, N=16)
32
+ # has an estimated bound of exactly 150,000, so the budget must sit above
33
+ # that or real tables get refused. 175,000 keeps ~17 percent headroom
34
+ # above it while sitting well below the red-team hang cases (bounds in the
35
+ # hundreds of millions), so the safety fix is intact. It is deliberately
36
+ # tighter than the paid product's 200,000 cap: the free tier should drive
37
+ # paid conversion, not replace it. The bound never undercounts (see the
38
+ # soundness test), so the true enumerated count at the boundary is
39
+ # typically far below 175,000 and enumeration stays fast.
40
+ _MAX_TABLES = 175_000
41
+
42
+
43
+ def fisher_exact_rc(table):
44
+ """Exact Fisher test p-value for a general r x c contingency table.
45
+
46
+ Parameters
47
+ ----------
48
+ table : array_like, shape (r, c)
49
+ Observed counts (nonnegative integers).
50
+
51
+ Returns
52
+ -------
53
+ float
54
+ Two-sided exact p-value: total null probability of all tables with
55
+ the same margins whose probability is <= the observed table's.
56
+
57
+ Notes
58
+ -----
59
+ Enumerates every table with the observed margins, so it is only
60
+ practical for small tables. Two up-front refusals keep it from
61
+ hanging: tables with more than 8 degrees of freedom
62
+ (``(r-1) * (c-1) > 8``) are refused on shape, and tables whose
63
+ estimated enumeration cost exceeds 175,000 tables are refused on
64
+ cost (the estimate is O(r + c), so the refusal itself is instant).
65
+
66
+ Tie classification (which tables count as "as or more extreme") is done
67
+ in exact integer arithmetic (no floating-point tolerance), so the
68
+ result is the true Fisher p-value up to summation rounding.
69
+ """
70
+ T = np.asarray(table)
71
+ if T.ndim != 2:
72
+ raise ValueError("table must be 2-dimensional")
73
+ if np.any(T < 0):
74
+ raise ValueError("table entries must be nonnegative")
75
+ if not np.all(np.isfinite(T)):
76
+ raise ValueError("table entries must be finite")
77
+ if not np.all(np.equal(np.mod(T, 1), 0)):
78
+ raise ValueError("table entries must be integers")
79
+ T = T.astype(np.int64)
80
+ r = tuple(int(v) for v in T.sum(axis=1))
81
+ c = tuple(int(v) for v in T.sum(axis=0))
82
+ if (len(r) - 1) * (len(c) - 1) > 8:
83
+ raise ValueError(
84
+ f"table too large to enumerate exactly ({len(r)}x{len(c)}); "
85
+ "the full version ($30, one-time) adds a Monte Carlo exact "
86
+ f"test for large tables: {_PAID_URL}"
87
+ )
88
+ if _count_upper_bound(r, c, _MAX_TABLES) > _MAX_TABLES:
89
+ raise ValueError(
90
+ "Free version refuses tables whose estimated enumeration cost "
91
+ "exceeds 175,000 tables (the estimate is a conservative upper "
92
+ "bound, so the true table count is lower). "
93
+ "The full version ($30, one-time) adds the exactly-uniform "
94
+ "fixed-margin table sampler and the Monte Carlo exact test for "
95
+ "tables too large to enumerate: "
96
+ "https://groundplane0.gumroad.com/l/priui"
97
+ )
98
+ # Exact tie classification in integer arithmetic: the common factor
99
+ # prod(r_i!) prod(c_j!) / N! cancels, so
100
+ # P(X) <= P(obs) <=> prod(X_ij!) >= prod(obs_ij!).
101
+ obs_w = math.prod(math.factorial(int(v)) for v in T.flat)
102
+ logps = []
103
+ extreme = []
104
+ for X in enumerate_tables(r, c):
105
+ w = math.prod(math.factorial(int(v)) for v in X.flat)
106
+ extreme.append(w >= obs_w)
107
+ # log P(X) up to the cancelled common factor (lgamma: no overflow)
108
+ logps.append(-math.fsum(math.lgamma(int(v) + 1) for v in X.flat))
109
+ m = max(logps)
110
+ norm = m + math.log(math.fsum(math.exp(lp - m) for lp in logps))
111
+ p = math.fsum(math.exp(lp - norm) for lp, ex in zip(logps, extreme) if ex)
112
+ return min(1.0, max(0.0, p))
@@ -0,0 +1,117 @@
1
+ """Table enumeration for the free exactsampler core.
2
+
3
+ This is the free subset of the table machinery: everything
4
+ :func:`exactsampler.fisher_exact_rc` needs to enumerate Omega(r, c),
5
+ and nothing else. The uniform sampler, the table counter, and the
6
+ Monte Carlo test live in the paid version only.
7
+ """
8
+
9
+ import math
10
+ import numbers
11
+
12
+ import numpy as np
13
+
14
+ __all__ = ["enumerate_tables"]
15
+
16
+
17
+ def _to_int_margin_value(x, name):
18
+ """Coerce one margin entry to int, rejecting non-integers loudly."""
19
+ if isinstance(x, numbers.Integral):
20
+ return int(x)
21
+ if isinstance(x, float) and x.is_integer():
22
+ return int(x)
23
+ raise ValueError(f"{name} must be integers; got {x!r}")
24
+
25
+
26
+ def _validate_margins(row_sums, col_sums):
27
+ """Return ``(r, c)`` as tuples of ints, raising on bad input."""
28
+ try:
29
+ r = tuple(_to_int_margin_value(x, "row_sums") for x in row_sums)
30
+ c = tuple(_to_int_margin_value(x, "col_sums") for x in col_sums)
31
+ except TypeError as exc:
32
+ raise ValueError("margins must be sequences of integers") from exc
33
+ if any(x < 0 for x in r) or any(x < 0 for x in c):
34
+ raise ValueError("margins must be nonnegative")
35
+ if sum(r) != sum(c):
36
+ raise ValueError(
37
+ f"row sums (total {sum(r)}) and column sums (total {sum(c)}) "
38
+ "must have equal totals"
39
+ )
40
+ return r, c
41
+
42
+
43
+ def _feasible_rows(total, caps):
44
+ """Yield every tuple ``x`` with ``sum(x) == total`` and ``0 <= x[j] <= caps[j]``."""
45
+ caps = tuple(caps)
46
+ if not caps:
47
+ if total == 0:
48
+ yield ()
49
+ return
50
+ first, rest = caps[0], caps[1:]
51
+ for v in range(0, min(first, total) + 1):
52
+ for tail in _feasible_rows(total - v, rest):
53
+ yield (v,) + tail
54
+
55
+
56
+ def _as_2d(table, m, n):
57
+ arr = np.asarray(table, dtype=np.int64).reshape(m, n)
58
+ return arr
59
+
60
+
61
+ def _count_upper_bound(row_sums, col_sums, budget):
62
+ """Cheap upper bound on the number of tables with the given margins.
63
+
64
+ Every row of a feasible table is a weak composition of its row sum into
65
+ ``len(col_sums)`` parts, so the number of tables is at most
66
+ ``prod_i C(r_i + ncols - 1, ncols - 1)``; the same holds with rows and
67
+ columns swapped, and the smaller of the two bounds is used. Evaluated
68
+ in log space with early exit, so this costs O(r + c) cheap operations
69
+ even for enormous margins (it never enumerates anything).
70
+
71
+ Returns an int: the bound itself, or ``budget + 1`` when the bound is
72
+ known to exceed ``budget`` (the exact value is then irrelevant, so it
73
+ is not computed).
74
+ """
75
+ r = tuple(x for x in row_sums if x > 0)
76
+ c = tuple(x for x in col_sums if x > 0)
77
+ if not r or not c or len(r) == 1 or len(c) == 1:
78
+ return 1
79
+ log_budget = math.log(budget)
80
+ best = None
81
+ for margins, nparts in ((r, len(c)), (c, len(r))):
82
+ k = nparts - 1
83
+ total = 0.0
84
+ for m in margins:
85
+ # log C(m + k, k); lgamma is O(1) and overflow-free
86
+ total += math.lgamma(m + k + 1) - math.lgamma(k + 1) - math.lgamma(m + 1)
87
+ if total > log_budget:
88
+ break
89
+ if best is None or total < best:
90
+ best = total
91
+ if best > log_budget:
92
+ return budget + 1
93
+ return max(1, int(math.exp(best)))
94
+
95
+
96
+ def enumerate_tables(row_sums, col_sums):
97
+ """Yield every table in Omega(r, c) as a 2-D ``numpy`` int array.
98
+
99
+ Only feasible for small tables (the number of tables grows
100
+ exponentially). Used here for exact tests.
101
+ """
102
+ r, c = _validate_margins(row_sums, col_sums)
103
+ m, n = len(r), len(c)
104
+
105
+ def rec(rows_left, cols_left, acc):
106
+ if not rows_left:
107
+ if all(x == 0 for x in cols_left):
108
+ yield _as_2d(acc, m, n)
109
+ return
110
+ for x in _feasible_rows(rows_left[0], tuple(cols_left)):
111
+ yield from rec(
112
+ rows_left[1:],
113
+ [cj - xj for cj, xj in zip(cols_left, x)],
114
+ acc + [x],
115
+ )
116
+
117
+ yield from rec(list(r), list(c), [])
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: exactsampler
3
+ Version: 0.1.0
4
+ Summary: Exact Fisher p-values for r-by-c contingency tables (free core)
5
+ Author: Groundplane Labs
6
+ License: MIT
7
+ Project-URL: Homepage, https://groundplane0.gumroad.com/l/priui
8
+ Keywords: fisher exact test,contingency table,exact test,statistics,biostatistics
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: numpy
17
+ Dynamic: license-file
18
+
19
+ # exactsampler
20
+
21
+ Free core of ExactSampler: exact Fisher p-values for r-by-c tables.
22
+
23
+ **The problem**
24
+ Your contingency table is bigger than 2x2 and you need an exact p-value. scipy's `fisher_exact` stops at 2x2. Your options are: approximate it and hope, learn R, or pip install this.
25
+
26
+ **What it does**
27
+ `fisher_exact_rc(table)` computes the exact two-sided Fisher p-value for r-by-c tables of modest size by enumerating every table with the observed margins. Ties are classified in exact integer arithmetic, so the result is the true p-value up to summation rounding. On 2x2 tables it agrees with scipy to 1e-14. Search terms: Fisher's exact test rxc Python, exact p-value contingency table Python, fisher exact r x c table.
28
+
29
+ **Limits**
30
+ Exact enumeration is for small-to-moderate tables. Tables beyond 8 degrees of freedom are refused outright instead of hanging, as are tables whose estimated enumeration cost exceeds 175,000 tables (the estimate is a conservative upper bound on the true count; a balanced 2x2 table refuses around N=836). This free core has no uniform table sampler, no Monte Carlo exact test, and no CLI.
31
+
32
+ **Install**
33
+
34
+ ```bash
35
+ pip install exactsampler
36
+ ```
37
+
38
+ Needs Python 3.9 or newer and NumPy.
39
+
40
+ ```python
41
+ from exactsampler import fisher_exact_rc
42
+ print(fisher_exact_rc([[2, 3], [3, 2]]))
43
+ ```
44
+
45
+ This is the free core: exact Fisher p-values for r-by-c tables. The full version ($30, one-time) adds the exactly-uniform fixed-margin table sampler and the Monte Carlo exact test for tables too large to enumerate: https://groundplane0.gumroad.com/l/priui
@@ -0,0 +1,8 @@
1
+ exactsampler/__init__.py,sha256=nIDWVgv2IlEjQpzwukDzNWXzYRvf1VaO_XjIbGwl6Cg,179
2
+ exactsampler/_fisher.py,sha256=lW0dMs3tBODS09U5OtY6f4WWFiMG_lkQ7UnPEnjWNMQ,4784
3
+ exactsampler/_tables.py,sha256=_tL7aoBiPZLANXXrRfh1wdwbjBQGocyqoTKXICjQ6nI,4021
4
+ exactsampler-0.1.0.dist-info/licenses/LICENSE,sha256=E-nK1L0MERx8owbskcU4J6x8ivUWVIY6wynWY6SZZSw,1073
5
+ exactsampler-0.1.0.dist-info/METADATA,sha256=ef5f2Vn3HQjW5dIkhVtFL-H7AZCHwyggo3gZAfbvDXE,2217
6
+ exactsampler-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
7
+ exactsampler-0.1.0.dist-info/top_level.txt,sha256=FlieebkKb-mE4ESN-VDLjrd_WZB0WG8o6KEDWxOywG4,13
8
+ exactsampler-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Groundplane Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ exactsampler