bayesplain 0.0.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.
Files changed (39) hide show
  1. bayesplain/__init__.py +97 -0
  2. bayesplain/_config.py +105 -0
  3. bayesplain/_contingency.py +286 -0
  4. bayesplain/_correlation.py +191 -0
  5. bayesplain/_groups.py +483 -0
  6. bayesplain/_means.py +282 -0
  7. bayesplain/_proportions.py +334 -0
  8. bayesplain/core/__init__.py +49 -0
  9. bayesplain/core/beta_binomial.py +264 -0
  10. bayesplain/core/correlation.py +303 -0
  11. bayesplain/core/dirichlet_multinomial.py +532 -0
  12. bayesplain/core/grid.py +159 -0
  13. bayesplain/core/hierarchical.py +123 -0
  14. bayesplain/core/intervals.py +220 -0
  15. bayesplain/core/normal_t.py +317 -0
  16. bayesplain/data/collisions.csv.gz +0 -0
  17. bayesplain/data/la_blockgroups.csv.gz +0 -0
  18. bayesplain/data/la_tracts.csv.gz +0 -0
  19. bayesplain/data/parcels.csv.gz +0 -0
  20. bayesplain/datasets.py +342 -0
  21. bayesplain/frequentist.py +510 -0
  22. bayesplain/priors.py +669 -0
  23. bayesplain/result.py +1243 -0
  24. bayesplain/teach.py +1100 -0
  25. bayesplain/tests/__init__.py +1 -0
  26. bayesplain/tests/test_beta_binomial.py +140 -0
  27. bayesplain/tests/test_contingency.py +185 -0
  28. bayesplain/tests/test_correlation.py +210 -0
  29. bayesplain/tests/test_dirichlet_multinomial.py +363 -0
  30. bayesplain/tests/test_groups.py +240 -0
  31. bayesplain/tests/test_means.py +249 -0
  32. bayesplain/tests/test_proportions.py +200 -0
  33. bayesplain/tests/test_result.py +293 -0
  34. bayesplain/tests/test_teach.py +355 -0
  35. bayesplain-0.0.0.dist-info/METADATA +310 -0
  36. bayesplain-0.0.0.dist-info/RECORD +39 -0
  37. bayesplain-0.0.0.dist-info/WHEEL +5 -0
  38. bayesplain-0.0.0.dist-info/licenses/LICENSE.txt +29 -0
  39. bayesplain-0.0.0.dist-info/top_level.txt +1 -0
bayesplain/__init__.py ADDED
@@ -0,0 +1,97 @@
1
+ """Bayesian answers to the questions frequentist tests are usually asked.
2
+
3
+ ``bayesplain`` gives you the Bayesian version of the handful of tests an
4
+ introductory statistics course is built around -- proportions, means,
5
+ contingency tables, correlation, group comparisons -- and prints the
6
+ conventional test alongside it every time.
7
+
8
+ Three design commitments
9
+ ------------------------
10
+ **Estimation first, Bayes factors second.** The headline output is a posterior,
11
+ a credible interval, and the probability of clearing a threshold you name.
12
+ ``BF = 4.2`` is not a sentence anyone puts in a memo, so the Bayes factor is a
13
+ method call rather than a printed default.
14
+
15
+ **Every result carries its frequentist twin.** The chi-square statistic, the t,
16
+ the p-value, the confidence interval -- computed and printed next to the
17
+ posterior, with a plain-English note on what each does and does not claim. You
18
+ cannot use this package without seeing both numbers for every analysis you run.
19
+
20
+ **No sampler in the dependency chain.** numpy and scipy, full stop, with
21
+ matplotlib optional. Everything is a conjugate posterior, a closed-form Bayes
22
+ factor, or a one-dimensional integral. It installs in a Colab cell in seconds,
23
+ with no compiler and no convergence warnings, ever.
24
+
25
+ Getting started
26
+ ---------------
27
+ >>> import bayesplain as bf
28
+ >>> res = bf.compare_proportions(
29
+ ... successes=[34, 51],
30
+ ... n=[220, 240],
31
+ ... labels=["District A", "District B"],
32
+ ... )
33
+ >>> print(res.summary()) # doctest: +SKIP
34
+ >>> round(res.probability(">", 0), 2)
35
+ 0.94
36
+
37
+ See Also
38
+ --------
39
+ bayesplain.priors : Named priors and what each one assumes.
40
+ bayesplain.frequentist : The conventional tests, computed on their own.
41
+ bayesplain.core : The mathematics, as pure functions.
42
+ """
43
+
44
+ from __future__ import annotations
45
+
46
+ from . import core, datasets, frequentist, priors, teach
47
+ from ._config import (
48
+ DEFAULT_DRAWS,
49
+ DEFAULT_SEED,
50
+ get_draws,
51
+ get_seed,
52
+ set_draws,
53
+ set_seed,
54
+ )
55
+ from ._contingency import SMALL_EFFECT_V, contingency
56
+ from ._correlation import correlation
57
+ from ._groups import compare_groups
58
+ from ._means import compare_means, mean
59
+ from ._proportions import compare_proportions, proportion
60
+ from .result import BayesFactor, Decision, Result
61
+
62
+ try: # pragma: no cover - depends on install method
63
+ from importlib.metadata import PackageNotFoundError, version
64
+
65
+ __version__ = version("bayesplain")
66
+ except (ImportError, PackageNotFoundError): # pragma: no cover
67
+ __version__ = "0.0.0.dev0"
68
+
69
+ __all__ = [
70
+ # analyses
71
+ "proportion",
72
+ "compare_proportions",
73
+ "contingency",
74
+ "SMALL_EFFECT_V",
75
+ "mean",
76
+ "compare_means",
77
+ "correlation",
78
+ "compare_groups",
79
+ # result types
80
+ "Result",
81
+ "Decision",
82
+ "BayesFactor",
83
+ # sub-packages
84
+ "priors",
85
+ "frequentist",
86
+ "core",
87
+ "datasets",
88
+ "teach",
89
+ # configuration
90
+ "get_seed",
91
+ "set_seed",
92
+ "get_draws",
93
+ "set_draws",
94
+ "DEFAULT_SEED",
95
+ "DEFAULT_DRAWS",
96
+ "__version__",
97
+ ]
bayesplain/_config.py ADDED
@@ -0,0 +1,105 @@
1
+ """Package-wide defaults, chosen for a classroom rather than for a lab.
2
+
3
+ The seed is fixed by default. That is unusual for a research package and
4
+ correct for a teaching one: if every student in the room gets different digits
5
+ in the last decimal place, office hours fill up with questions about Monte
6
+ Carlo noise instead of questions about statistics.
7
+
8
+ Having hidden that noise, the package then surfaces it deliberately -- every
9
+ summary of a sampled quantity prints its Monte Carlo standard error, and one
10
+ short lesson on why the last digit wobbles costs less than a term of
11
+ confusion.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import numpy as np
17
+
18
+ __all__ = [
19
+ "DEFAULT_SEED",
20
+ "DEFAULT_DRAWS",
21
+ "get_seed",
22
+ "set_seed",
23
+ "get_draws",
24
+ "set_draws",
25
+ "make_rng",
26
+ ]
27
+
28
+ DEFAULT_SEED = 12345
29
+ DEFAULT_DRAWS = 100_000
30
+
31
+ _state = {"seed": DEFAULT_SEED, "draws": DEFAULT_DRAWS}
32
+
33
+
34
+ def get_seed() -> int | None:
35
+ """Return the current default seed.
36
+
37
+ Returns
38
+ -------
39
+ int or None
40
+ The seed used when a call does not supply its own. ``None`` means
41
+ draws are non-reproducible.
42
+ """
43
+ return _state["seed"]
44
+
45
+
46
+ def set_seed(seed: int | None) -> None:
47
+ """Set the default seed for every subsequent analysis.
48
+
49
+ Parameters
50
+ ----------
51
+ seed : int or None
52
+ Seed to use. Pass ``None`` for genuinely random draws, which is the
53
+ right choice when demonstrating that Monte Carlo error is real.
54
+ """
55
+ if seed is not None:
56
+ seed = int(seed)
57
+ _state["seed"] = seed
58
+
59
+
60
+ def get_draws() -> int:
61
+ """Return the current default number of posterior draws.
62
+
63
+ Returns
64
+ -------
65
+ int
66
+ Draws taken for quantities that require sampling.
67
+ """
68
+ return _state["draws"]
69
+
70
+
71
+ def set_draws(n_draws: int) -> None:
72
+ """Set the default number of posterior draws.
73
+
74
+ Parameters
75
+ ----------
76
+ n_draws : int
77
+ Must be at least 1000; below that, Monte Carlo error starts showing up
78
+ in the second decimal place of a reported probability.
79
+ """
80
+ n_draws = int(n_draws)
81
+ if n_draws < 1000:
82
+ raise ValueError(
83
+ f"n_draws must be at least 1000, got {n_draws}. Below that, Monte "
84
+ "Carlo error is large enough to change a reported probability."
85
+ )
86
+ _state["draws"] = n_draws
87
+
88
+
89
+ def make_rng(seed: int | None = "unset") -> np.random.Generator:
90
+ """Build a random generator, honouring the package default.
91
+
92
+ Parameters
93
+ ----------
94
+ seed : int, None, or 'unset'
95
+ An explicit seed, ``None`` for non-reproducible draws, or the sentinel
96
+ ``'unset'`` to fall back to the package default.
97
+
98
+ Returns
99
+ -------
100
+ numpy.random.Generator
101
+ A fresh generator.
102
+ """
103
+ if isinstance(seed, str) and seed == "unset":
104
+ seed = _state["seed"]
105
+ return np.random.default_rng(seed)
@@ -0,0 +1,286 @@
1
+ """Categorical breakdowns, and whether a table's rows and columns are related.
2
+
3
+ The frequentist counterpart is the chi-square test of independence (week 7),
4
+ and this is the analysis where the Bayesian version has the clearest advantage.
5
+ A chi-square test returns a statistic and a p-value; ask it *how strong* the
6
+ association is and it has nothing to say beyond a point estimate with no
7
+ uncertainty attached. Drawing from the Dirichlet posterior over cell
8
+ probabilities and computing an effect size once per draw gives that quantity a
9
+ full posterior, in closed form, for free.
10
+
11
+ The second advantage shows up in sparse tables. The chi-square approximation
12
+ needs roughly five expected cases per cell and warns below it; the posterior
13
+ does not degrade there at all, it simply gets wider, which is the honest
14
+ response to thin data.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import numpy as np
20
+
21
+ from . import frequentist, priors
22
+ from ._config import get_draws, make_rng
23
+ from .core import dirichlet_multinomial as dm
24
+ from .result import Result
25
+
26
+ __all__ = ["contingency"]
27
+
28
+ #: Conventional bar for "at least a small association", used as the default
29
+ #: threshold for Cramer's V. Unlike a difference or a log odds ratio, V cannot
30
+ #: be negative and a posterior never puts mass at exactly zero, so P(V > 0) is
31
+ #: always 1 and tells you nothing. A conventional floor is the honest
32
+ #: replacement, and naming it out loud is better than implying a null exists.
33
+ SMALL_EFFECT_V = 0.1
34
+
35
+
36
+ def contingency(
37
+ table,
38
+ prior="uninformed",
39
+ scheme: str = "independent_multinomial",
40
+ fixed: str = "rows",
41
+ effect: str = "auto",
42
+ threshold: float | None = None,
43
+ row_labels=None,
44
+ col_labels=None,
45
+ n_draws: int | None = None,
46
+ seed="unset",
47
+ ) -> Result:
48
+ """Test whether the rows and columns of a table are related.
49
+
50
+ Parameters
51
+ ----------
52
+ table : array_like
53
+ Counts, shape ``(R, C)``. Rows are the groups you sampled; columns are
54
+ the categories you counted within each group. A pandas crosstab works
55
+ directly, and its labels are picked up automatically.
56
+ prior : str, float, or ConcentrationPrior, default 'uninformed'
57
+ Dirichlet concentration over the cells. See
58
+ :func:`bayesplain.priors.describe`.
59
+ scheme : str, default 'independent_multinomial'
60
+ Which Gunel-Dickey sampling scheme the study design justifies; one of
61
+ :data:`bayesplain.core.dirichlet_multinomial.SCHEMES`. The default
62
+ matches "we sampled a fixed number of cases in each group", which is
63
+ how planning data is usually gathered. The choice only affects the
64
+ Bayes factor, never the posterior over the effect size.
65
+ fixed : {'rows', 'columns'}, default 'rows'
66
+ Which margin the design fixed, for the independent-multinomial scheme.
67
+ effect : {'auto', 'cramers_v', 'log_odds_ratio'}, default 'auto'
68
+ The effect size to put a posterior on. ``'auto'`` uses the log odds
69
+ ratio for a 2x2 table, where zero means exactly no association, and
70
+ Cramer's V otherwise.
71
+ threshold : float, optional
72
+ The value the reported probability is measured against. Defaults to 0
73
+ for the log odds ratio and to :data:`SMALL_EFFECT_V` for Cramer's V.
74
+ row_labels, col_labels : sequence of str, optional
75
+ Names for the rows and columns. Read from a pandas object when not
76
+ supplied.
77
+ n_draws : int, optional
78
+ Number of draws. Defaults to the package setting.
79
+ seed : int or None, optional
80
+ Seed for the draws.
81
+
82
+ Returns
83
+ -------
84
+ Result
85
+ Call ``.summary()`` for the full report.
86
+
87
+ Examples
88
+ --------
89
+ The doll-preference study of Hraba and Grant (1970), as analysed by Jamil
90
+ et al. (2017): 62 of 89 African American children preferred a black doll,
91
+ while 60 of 71 white children preferred a white doll.
92
+
93
+ >>> import bayesplain as bp
94
+ >>> res = bp.contingency(
95
+ ... [[62, 27], [11, 60]],
96
+ ... row_labels=["Black children", "white children"],
97
+ ... col_labels=["black doll", "white doll"],
98
+ ... )
99
+ >>> round(res.bayes_factor().log_bf10, 2)
100
+ 23.03
101
+ >>> res.frequentist.pvalue < 0.001
102
+ True
103
+
104
+ Notes
105
+ -----
106
+ The Bayes factor is validated against the published values in Jamil et al.
107
+ (2017) for all four sampling schemes.
108
+ """
109
+ row_labels, col_labels, counts = _read_table(table, row_labels, col_labels)
110
+ resolved = priors.resolve_table(prior)
111
+ n_draws = get_draws() if n_draws is None else int(n_draws)
112
+ rng = make_rng(seed)
113
+
114
+ n_rows, n_cols = counts.shape
115
+ if effect == "auto":
116
+ effect = "log_odds_ratio" if counts.shape == (2, 2) else "cramers_v"
117
+ if effect not in {"cramers_v", "log_odds_ratio"}:
118
+ raise ValueError(
119
+ f"effect must be 'auto', 'cramers_v', or 'log_odds_ratio', got {effect!r}."
120
+ )
121
+ if effect == "log_odds_ratio" and counts.shape != (2, 2):
122
+ raise ValueError(
123
+ f"the log odds ratio is only defined for a 2x2 table, but this one "
124
+ f"is {n_rows}x{n_cols}. Use effect='cramers_v'."
125
+ )
126
+
127
+ cells = dm.posterior_cell_draws(
128
+ counts, concentration=resolved.a, size=n_draws, rng=rng
129
+ )
130
+ if effect == "log_odds_ratio":
131
+ draws = dm.log_odds_ratio(cells)
132
+ reference = 0.0 if threshold is None else float(threshold)
133
+ quantity = (
134
+ f"log odds ratio — {col_labels[0]} vs {col_labels[1]}, "
135
+ f"across {row_labels[0]} and {row_labels[1]}"
136
+ )
137
+ subject = "log odds ratio"
138
+ unit, scale, decimals = "", 1.0, 2
139
+ else:
140
+ draws = dm.cramers_v(cells)
141
+ reference = SMALL_EFFECT_V if threshold is None else float(threshold)
142
+ quantity = (
143
+ f"strength of association (Cramér's V) between "
144
+ f"{'rows' if n_rows > 2 else ' and '.join(row_labels)} and "
145
+ f"{'columns' if n_cols > 2 else ' and '.join(col_labels)}"
146
+ )
147
+ subject = "association strength"
148
+ unit, scale, decimals = "", 1.0, 3
149
+
150
+ log_bf10 = dm.log_bayes_factor_independence(
151
+ counts, concentration=resolved.a, scheme=scheme, fixed=fixed
152
+ )
153
+ twin = frequentist.chi_square_independence(counts)
154
+
155
+ notes = _build_notes(counts, twin, effect, reference)
156
+
157
+ def _refit(spec):
158
+ return contingency(
159
+ counts,
160
+ prior=spec,
161
+ scheme=scheme,
162
+ fixed=fixed,
163
+ effect=effect,
164
+ threshold=reference,
165
+ row_labels=row_labels,
166
+ col_labels=col_labels,
167
+ n_draws=n_draws,
168
+ seed=seed,
169
+ )
170
+
171
+ return Result(
172
+ quantity=quantity,
173
+ draws=draws,
174
+ posterior=None, # no closed form for an effect size built from a table
175
+ prior=resolved,
176
+ subject=subject,
177
+ analysis="contingency",
178
+ frequentist=twin,
179
+ log_bf10=log_bf10,
180
+ bf_alternative="an association",
181
+ bf_caveat=(
182
+ f"Compares 'rows and columns are related' against 'they are "
183
+ f"independent', under the {scheme.replace('_', ' ')} sampling "
184
+ f"scheme. Which scheme is right depends on what your design fixed "
185
+ f"in advance, and the four differ by roughly a full evidence "
186
+ f"category. Prior-sensitive; run .sensitivity()."
187
+ ),
188
+ unit=unit,
189
+ display_scale=scale,
190
+ decimals=decimals,
191
+ direction_reference=reference,
192
+ components=_row_profiles(cells, row_labels),
193
+ component_axis="share of each row falling in the first column (%)",
194
+ component_scale=100.0,
195
+ refit=_refit,
196
+ prior_ladder=priors.SENSITIVITY_LADDER,
197
+ n_draws=n_draws,
198
+ notes=notes,
199
+ )
200
+
201
+
202
+ # ---------------------------------------------------------------------------
203
+ # Helpers
204
+ # ---------------------------------------------------------------------------
205
+
206
+
207
+ def _read_table(table, row_labels, col_labels):
208
+ """Pull counts and labels out of an array or a pandas crosstab."""
209
+ if hasattr(table, "columns") and hasattr(table, "index"):
210
+ if row_labels is None:
211
+ row_labels = [str(v) for v in table.index]
212
+ if col_labels is None:
213
+ col_labels = [str(v) for v in table.columns]
214
+ values = table.to_numpy()
215
+ else:
216
+ values = table
217
+
218
+ counts = dm.validate_table(values)
219
+ n_rows, n_cols = counts.shape
220
+
221
+ row_labels = (
222
+ [f"row {i + 1}" for i in range(n_rows)]
223
+ if row_labels is None
224
+ else [str(v) for v in row_labels]
225
+ )
226
+ col_labels = (
227
+ [f"column {j + 1}" for j in range(n_cols)]
228
+ if col_labels is None
229
+ else [str(v) for v in col_labels]
230
+ )
231
+ if len(row_labels) != n_rows:
232
+ raise ValueError(
233
+ f"row_labels has {len(row_labels)} names but the table has {n_rows} rows."
234
+ )
235
+ if len(col_labels) != n_cols:
236
+ raise ValueError(
237
+ f"col_labels has {len(col_labels)} names but the table has "
238
+ f"{n_cols} columns."
239
+ )
240
+ return row_labels, col_labels, counts
241
+
242
+
243
+ def _row_profiles(cells, row_labels):
244
+ """Posterior draws of each row's share in the first column.
245
+
246
+ Gives the components plot something concrete to show: the rows are only
247
+ "related" to the columns insofar as their category profiles differ, so
248
+ seeing those profiles side by side is what makes an association legible.
249
+ """
250
+ row_totals = cells.sum(axis=2)
251
+ with np.errstate(divide="ignore", invalid="ignore"):
252
+ shares = np.where(row_totals > 0, cells[:, :, 0] / row_totals, np.nan)
253
+ return {label: shares[:, i] for i, label in enumerate(row_labels)}
254
+
255
+
256
+ def _build_notes(counts, twin, effect, reference):
257
+ """Warnings that matter for reading this particular table."""
258
+ notes = []
259
+ expected = _expected_counts(counts)
260
+ sparse = int((expected < 5).sum())
261
+ if sparse:
262
+ notes.append(
263
+ f"{sparse} of {counts.size} cells have expected counts below 5, "
264
+ "where the chi-square approximation is unreliable. The posterior "
265
+ "is unaffected — it just gets wider, which is the honest response "
266
+ "to thin data."
267
+ )
268
+ if effect == "cramers_v":
269
+ notes.append(
270
+ f"Cramér's V cannot be negative, so P(above {reference:g}) is "
271
+ "measured against a conventional 'small association' bar rather "
272
+ "than a null. Set threshold= to a value that matters for your "
273
+ "decision instead."
274
+ )
275
+ if counts.sum() < 40:
276
+ notes.append(
277
+ f"only {int(counts.sum())} observations in total, so the prior is "
278
+ "doing visible work here — run .sensitivity()"
279
+ )
280
+ return notes
281
+
282
+
283
+ def _expected_counts(counts):
284
+ """Compute the expected counts under independence."""
285
+ total = counts.sum()
286
+ return np.outer(counts.sum(axis=1), counts.sum(axis=0)) / total
@@ -0,0 +1,191 @@
1
+ """Two things moving together, and how much of that we actually know.
2
+
3
+ The frequentist counterpart is Pearson's r with its p-value (week 8). The
4
+ Bayesian version treats the correlation as a quantity to be estimated, which
5
+ turns "is there a relationship" into "how strong is it, and how sure are we" --
6
+ a question that has an answer a planner can use.
7
+
8
+ Two warnings belong with this analysis and nowhere else in the course, so they
9
+ are attached to every result as notes rather than left to the lecture.
10
+
11
+ **Ecological correlation.** A correlation computed on tracts, districts, or
12
+ counties is a statement about *those areas*, not about the people in them.
13
+ Robinson (1950) showed the two can differ in sign, not merely in size. Nothing
14
+ in a correlation coefficient warns you when you have crossed that line.
15
+
16
+ **The modifiable areal unit problem.** The same underlying data, aggregated to
17
+ different boundaries, produces different correlations. Redraw the districts and
18
+ the number changes. This is not measurement error to be averaged away; it means
19
+ the correlation is partly a property of the geography you chose.
20
+
21
+ And the ordinary caveat, which the package will not stop repeating: nothing
22
+ here makes a finding causal.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import numpy as np
28
+
29
+ from . import frequentist, priors
30
+ from ._config import get_draws, make_rng
31
+ from .core import correlation as core_corr
32
+ from .core import grid as grid_utils
33
+ from .result import Result
34
+
35
+ __all__ = ["correlation"]
36
+
37
+
38
+ def correlation(
39
+ x,
40
+ y,
41
+ prior="uninformed",
42
+ labels=None,
43
+ aggregated: bool = False,
44
+ n_draws: int | None = None,
45
+ seed="unset",
46
+ ) -> Result:
47
+ """Estimate the correlation between two variables.
48
+
49
+ The posterior is computed from the exact sampling density of the
50
+ correlation coefficient, evaluated on a grid and sampled by inverting its
51
+ cumulative distribution. Not a conjugate update and not MCMC -- a
52
+ one-dimensional integral, which is all this problem needs.
53
+
54
+ Parameters
55
+ ----------
56
+ x, y : array_like
57
+ Paired observations. Rows where either value is missing are dropped.
58
+ prior : str, float, or CorrelationPrior, default 'uninformed'
59
+ Stretched-beta prior width on the correlation. The default is flat on
60
+ (-1, 1). See :func:`bayesplain.priors.describe`.
61
+ labels : sequence of str, optional
62
+ Names of the two variables, used in output.
63
+ aggregated : bool, default False
64
+ Set to ``True`` when the rows are geographic areas rather than
65
+ individuals. This adds the ecological-correlation and modifiable-areal-
66
+ unit warnings to the result, because a correlation between tract
67
+ averages is not a correlation between people.
68
+ n_draws : int, optional
69
+ Number of draws. Defaults to the package setting.
70
+ seed : int or None, optional
71
+ Seed for the draws.
72
+
73
+ Returns
74
+ -------
75
+ Result
76
+ Call ``.summary()`` for the full report.
77
+
78
+ Examples
79
+ --------
80
+ >>> import numpy as np, bayesplain as bp
81
+ >>> rng = np.random.default_rng(0)
82
+ >>> x = rng.normal(size=60)
83
+ >>> y = 0.5 * x + rng.normal(size=60)
84
+ >>> res = bp.correlation(x, y, labels=["density", "transit use"])
85
+ >>> res.probability(">", 0) > 0.95
86
+ True
87
+ """
88
+ a, b = core_corr.validate_pair(x, y)
89
+ n = a.size
90
+ resolved = priors.resolve_correlation(prior)
91
+ n_draws = get_draws() if n_draws is None else int(n_draws)
92
+ rng = make_rng(seed)
93
+
94
+ if labels is None:
95
+ labels = ("x", "y")
96
+ labels = tuple(str(item) for item in labels)
97
+ if len(labels) != 2:
98
+ raise ValueError(f"labels needs exactly two names, got {len(labels)}.")
99
+
100
+ twin = frequentist.correlation(a, b)
101
+ r = twin.statistic
102
+
103
+ rho_grid, density = core_corr.posterior_on_grid(r, n, kappa=resolved.kappa)
104
+ draws = grid_utils.sample_from_grid(density, rho_grid, size=n_draws, rng=rng)
105
+ log_bf10 = core_corr.log_bayes_factor(r, n, kappa=resolved.kappa)
106
+
107
+ notes = _build_notes(n, aggregated)
108
+
109
+ def _refit(spec):
110
+ return correlation(
111
+ a,
112
+ b,
113
+ prior=spec,
114
+ labels=labels,
115
+ aggregated=aggregated,
116
+ n_draws=n_draws,
117
+ seed=seed,
118
+ )
119
+
120
+ return Result(
121
+ quantity=f"correlation between {labels[0]} and {labels[1]}",
122
+ draws=draws,
123
+ posterior=None, # grid-based; no closed-form scipy distribution
124
+ prior=resolved,
125
+ subject="correlation",
126
+ analysis="correlation",
127
+ frequentist=twin,
128
+ log_bf10=log_bf10,
129
+ bf_alternative="a relationship",
130
+ bf_caveat=(
131
+ "Compares 'the two variables are related' against 'they are "
132
+ "completely unrelated'. A correlation of exactly zero is rarely "
133
+ "what anyone believes, and this number moves with the prior width "
134
+ "— run .sensitivity()."
135
+ ),
136
+ unit="",
137
+ display_scale=1.0,
138
+ decimals=3,
139
+ direction_reference=0.0,
140
+ components=None,
141
+ custom_plots={"scatter": _scatter_plot(a, b, labels)},
142
+ refit=_refit,
143
+ prior_ladder=priors.CORRELATION_SENSITIVITY_LADDER,
144
+ n_draws=n_draws,
145
+ notes=notes,
146
+ )
147
+
148
+
149
+ # ---------------------------------------------------------------------------
150
+ # Helpers
151
+ # ---------------------------------------------------------------------------
152
+
153
+
154
+ def _build_notes(n: int, aggregated: bool) -> list[str]:
155
+ """Caveats that belong with every correlation, and some with only a few."""
156
+ notes = [
157
+ "A correlation is not a cause. Nothing in this analysis rules out a "
158
+ "third variable driving both, or the arrow pointing the other way."
159
+ ]
160
+ if aggregated:
161
+ notes.append(
162
+ "These rows are areas, not people. A correlation between area "
163
+ "averages can differ from the correlation among individuals, "
164
+ "sometimes in sign (Robinson 1950), and it will change if the "
165
+ "boundaries are redrawn. Report the geography you used."
166
+ )
167
+ if n < 25:
168
+ notes.append(
169
+ f"only {n} pairs, so the interval is wide and the posterior is "
170
+ "noticeably asymmetric — read the interval, not the point estimate"
171
+ )
172
+ return notes
173
+
174
+
175
+ def _scatter_plot(a, b, labels):
176
+ """Build the scatter-plot callable this result exposes as kind='scatter'."""
177
+
178
+ def draw(ax):
179
+ ax.scatter(a, b, s=22, alpha=0.55, color="#4a4e69", edgecolor="none")
180
+ # A least-squares line, purely to guide the eye. The posterior above
181
+ # is about the correlation, not about this line's slope.
182
+ if np.ptp(a) > 0:
183
+ slope, intercept = np.polyfit(a, b, 1)
184
+ span = np.array([a.min(), a.max()])
185
+ ax.plot(span, slope * span + intercept, color="#c9184a", lw=1.5)
186
+ ax.set_xlabel(labels[0])
187
+ ax.set_ylabel(labels[1])
188
+ ax.spines[["top", "right"]].set_visible(False)
189
+ return ax
190
+
191
+ return draw